0

I would like to take a series of user-input integers, then sum the input. For instance, if the user enters:

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

6

Here is my code so far:

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

1 Answer 1

4

This example is actually more complicated than it should be since it requires multiple things (looping, reading input, and accumulating). I am going to give you two solutions, one which is the easy way and another which is how I would personally do it. First of all the easy way:

(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

More advanced version which is how I would do it:

(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

Edit: Versions of the previous which stop on a new line.

(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)))
Sign up to request clarification or add additional context in comments.

2 Comments

It's worth nothing that y-or-n-p (and yes-or-no-p) read and write to and from *query-io*, not *standard-output*, so it may make sense to do the same when you write "Enter a number: " and (read-line). "The value of *query-io*, called query I/O, is a bidirectional stream to be used when asking questions of the user. The question should be output to this stream, and the answer read from it."
Wow! Thank you very very much. I see that I'm going to really go through some more simple cases in Lisp before I can get to anything meaty. Thank you so much!!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.