为什么在 Lisp 中读取文件时 read-line 会运行两次?

发布于 2024-09-24 14:54:22 字数 441 浏览 0 评论 0原文

这是用 lisp 实现“cat”命令的代码,如书中所述 ANSI Common Lisp,第 122 页。

(defun pseudo-cat (file)
  (with-open-file (str file :direction :input)
    (do ((line (read-line str nil 'eof)
               (read-line str nil 'eof)))
        ((eql line 'eof))
      (format t "~A~%" line))))

为什么 read-line 函数运行两次?我尝试只用一行读取来运行它,但 Lisp 无法完成代码。

This is the code to implement the 'cat' command with lisp, as is explained in the book ANSI Common Lisp, page 122.

(defun pseudo-cat (file)
  (with-open-file (str file :direction :input)
    (do ((line (read-line str nil 'eof)
               (read-line str nil 'eof)))
        ((eql line 'eof))
      (format t "~A~%" line))))

Why is the read-line function run twice? I tried to run it with only one read-line, but the Lisp couldn't finish the code.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

冬天旳寂寞 2024-10-01 14:54:22

DO变量的语法为:变量、初始化形式、更新形式。在这种情况下,初始化形式与更新形式相同。但 DO 中没有这种情况的简写,所以你必须写两次。

The syntax of DO variables is: variable, initialization form, update form. In this case, the initialization form is the same as the update form. But there is no shorthand for that case in DO, so you have to write it out twice.

四叶草在未来唯美盛开 2024-10-01 14:54:22

您需要阅读 DO 的语法: http://www.lispworks.com/ Documentation/HyperSpec/Body/m_do_do.htm

第一个 READ-LINE 形式是 init 形式,第二个是 step 形式。因此,在第一次迭代中,变量被设置为 init-form 的结果。在接下来的迭代中,变量被设置为步骤形式的值。

You need to read the syntax of DO: http://www.lispworks.com/documentation/HyperSpec/Body/m_do_do.htm

The first READ-LINE form is the init-form and the second is the step-form. So in the first iteration the variable is set to the result of the init-form. In the next iterations the variable is set to the value of the step-form.

无风消散 2024-10-01 14:54:22

您可以使用(listen file)来测试是否可以读取该文件。

这是我的打印文件功能

(defun print-file (filename)
  "Print file on stdout."
  (with-open-file (file filename :direction :input)
          (loop
             (when (not (listen file)) (return))
             (write-line (read-line file)))))

You can use (listen file) for test if you can read from the file.

This is my print-file function

(defun print-file (filename)
  "Print file on stdout."
  (with-open-file (file filename :direction :input)
          (loop
             (when (not (listen file)) (return))
             (write-line (read-line file)))))
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文