Common Lisp - 如何总结用户输入

Aar*_*ron 0 common-lisp

我想取一系列用户输入的整数,然后对输入求和.例如,如果用户输入:

1 <return>
2 <return>
3 <return>
<return>
Run Code Online (Sandbox Code Playgroud)

6
Run Code Online (Sandbox Code Playgroud)

到目前为止,这是我的代码:

(defun stuff ()
  (format t "Enter a number: ")
  (let ((n (read)))
    (+ n)))
Run Code Online (Sandbox Code Playgroud)

mal*_*per 5

这个例子实际上比它应该更复杂,因为它需要多个东西(循环,读取输入和累积).我将给你两个解决方案,一个是简单的方法,另一个是我亲自做的.首先是简单的方法:

(defun stuff (&optional (acc 0)) ; An optional argument for keeping track of the sum.
  (if (y-or-n-p "Do you want to continue?") ; Ask if they want to continue
      (progn (format t "Enter a number: ")  ; If they say yes we need to ask them for the
             (stuff (+ acc (read))))        ; number, read it, add it to the sum, and
                                            ; continue. We need progn because we need to
                                            ; execute two pieces of code (format and stuff) in the if
      acc)) ; If they say no, then return the total sum
Run Code Online (Sandbox Code Playgroud)

更高级的版本,我会这样做:

(defun stuff ()
  (loop while (y-or-n-p "Do you want to continue?") ; while they want to continue
        do  (format t "Enter a number: ")           ; print the prompt
        sum (parse-integer (read-line))))           ; read the line, parse the integer, and sum it
Run Code Online (Sandbox Code Playgroud)

编辑:上一个停在新行上的版本.

(defun stuff (&optional (acc 0))
  (let ((line (read-line)))
    (if (string= line "") ; If this line is the empty string
        acc               ; return the sum
        (stuff (+ acc (parse-integer line)))))) ; otherwise recur and sum the number on the line

(defun stuff ()
  (loop for line = (read-line)
        until (string= line "")
        sum (parse-integer line)))
Run Code Online (Sandbox Code Playgroud)