Common Lisp - 如何总结用户输入

时间:2014-08-30 16:42:47

标签: common-lisp

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

1 <return>
2 <return>
3 <return>
<return>

6

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

(defun stuff ()
  (format t "Enter a number: ")
  (let ((n (read)))
    (+ n)))

1 个答案:

答案 0 :(得分: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

更高级的版本,我将如何做到这一点:

(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

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

(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)))