Common Lisp-如何汇总用户输入

亚伦

我想采用一系列用户输入的整数,然后求和输入。例如,如果用户输入:

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

6

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

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

实际上,此示例比应有的示例复杂得多,因为它需要进行多项操作(循环,读取输入和累加)。我将为您提供两种解决方案,一种是简便的方法,另一种是我个人的解决方案。首先简单的方法:

(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)))

本文收集自互联网,转载请注明来源。

如有侵权,请联系[email protected] 删除。

编辑于
0

我来说两句

0条评论
登录后参与评论

相关文章

来自分类Dev

如何构建Common Lisp项目?

来自分类Dev

如何构建Common Lisp项目?

来自分类Dev

Common Lisp:写入外部程序输入

来自分类Dev

如何在Common Lisp中映射功能?

来自分类Dev

如何从Common Lisp调用Go程序

来自分类Dev

Common Lisp:如何覆盖插槽访问器?

来自分类Dev

如何在Common Lisp中映射功能?

来自分类Dev

如何从Common Lisp调用Go程序

来自分类Dev

如何从 JSCL 方法调用 Common Lisp 代码

来自分类Dev

从Common Lisp中的输入解析2D数组

来自分类Dev

(组成)在Common Lisp中

来自分类Dev

Jupyter和Common Lisp

来自分类Dev

Common Lisp中的'()vs()

来自分类Dev

#ifndef在Common Lisp中

来自分类Dev

〜|的含义 以Common Lisp格式

来自分类Dev

如何在Common Lisp中实现短路的“ and”宏?

来自分类Dev

如何在Common Lisp中修改函数绑定?

来自分类Dev

如何在Common Lisp中定义宏时间的包装

来自分类Dev

在Common Lisp的幕后如何实现“ tagbody”和“ go”?

来自分类Dev

在Common Lisp中,如何保留变量输出的大小写

来自分类Dev

如何在Common Lisp中要求关键字参数?

来自分类Dev

在Common Lisp中,如何测试变量是否特殊?

来自分类Dev

如何在Common Lisp中获取课程信息?

来自分类Dev

如何在Common Lisp中返回变量的值和名称

来自分类Dev

如何使用SBCL正确保存Common Lisp图像?

来自分类Dev

如何在Linux上的Common Lisp中内存映射文件?

来自分类Dev

如何在Common Lisp中编写opengl ES 2.0 / 3.0?

来自分类Dev

Common-Lisp:如何对字符串的字符进行排序?

来自分类Dev

如何在Common Lisp中遍历列表和范围?