2014-08-30 36 views
0

我想采取一系列用户输入整数,然后求和输入。举例来说,如果用户输入:Common Lisp - 如何求和用户输入

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

6 

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

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

回答

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))) 
+1

这是值得什么,[** Y型或-NP **](http://www.lispworks.com/documentation/HyperSpec/Body/f_y_or_n.htm)(和**是 - 或 - no-p **)从[** \ * query-io \ ***]读取和写入(http://www.lispworks.com/documentation/HyperSpec/Body/v_debug_.htm#STquery-ioST) ,而不是** \ *标准输出\ ***,因此在您编写**“输入数字:”**和**(读取线**)时执行相同的操作可能有意义。 “** \ * query-io \ ***的值,被称为查询I/O,是在询问用户问题时使用的双向流。问题应该输出到这个流中,答案从它。” – 2014-08-31 12:37:37

+0

哇!非常非常感谢你。我明白,在我可以得到任何有趣的东西之前,我会真正通过Lisp中的一些更简单的例子。非常感谢!! – Aaron 2014-08-31 17:15:51