How to read user input in Lisp

I am very new to Lisp and am trying to write a program that simply asks the user to enter 3 numbers and then sums them up and outputs the result.

I read that you can use a function like:

(defvar a)

(setq a (read))

      

To set a variable in Lisp, but when I try to compile my code with LispWorks, I get the following error:

End of file while reading stream #<Concatenated Stream, Streams = ()>

It seems to me that this should be relatively simple and have no idea where I am going wrong.

+3


source to share


2 answers


I haven't worked with LispWorks, so this is just a guess.

When the compiler traverses your code, it hits a line (setq a (read))

, it tries to read the input, but there is no input stream at compile time, so you get an error.

Write a function:



(defvar a)

(defun my-function ()
  (setq a (read))

      

It should work.

+4


source


This should evaluate correctly in Lisp:

(defun read-3-numbers-&-format-sum ()
  (flet ((prompt (string)
           (format t "~&~a: " string)
           (read nil 'eof nil)))
    (let ((x (prompt "first number"))
          (y (prompt "second number"))
          (z (prompt "third number")))
      (format t "~&the sum of ~a, ~a, & ~a is:~%~%~a~%"
              x y z (+ x y z)))))

      

Just evaluate the above function definition, then run the form:



(read-3-numbers-&-format-sum)

      

in the LispWorks interpreter.

+2


source







All Articles