2014-08-30 34 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