如何在Lisp中读取用户输入

cho*_*ope 5 lisp common-lisp lispworks

我对Lisp并不陌生,正在尝试编写一个程序,仅要求用户输入3个数字,然后对它们求和并打印输出。

我读到您可以使用类似的功能:

(defvar a)

(setq a (read))
Run Code Online (Sandbox Code Playgroud)

要在Lisp中设置变量,但是当我尝试使用LispWorks编译代码时,出现以下错误:

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

我觉得这应该相对简单,不知道我要去哪里错。

Mar*_*ark 5

我没有使用LispWorks,所以只是一个猜测。

当编译器遍历您的代码时,它到达line (setq a (read)),它尝试读取输入,但是在编译时没有输入流,因此会出现错误。

编写一个函数:

(defvar a)

(defun my-function ()
  (setq a (read))
Run Code Online (Sandbox Code Playgroud)

它应该工作。


小智 5

这应该在你的 Lisp 中正确评估:

(defun read-3-numbers-&-format-sum ()
  (flet ((prompt (string)
           (format t "~&~a: " string)
           (finish-output)
           (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)))))
Run Code Online (Sandbox Code Playgroud)

只需评估上面的函数定义,然后运行表单:

(read-3-numbers-&-format-sum)
Run Code Online (Sandbox Code Playgroud)

在您的 LispWorks 解释器处。