在Common Lisp中循环使用字符串中的行

时间:2014-03-15 20:49:05

标签: lisp common-lisp

我试图理解为什么这一小段代码无法按预期工作。 我希望它打印出“foo”,但实际上我得到的是

CL-USER> (stringloop)
null output T
 line output NIL

NIL

我希望我使用do错误,但我无法弄清楚是什么。

(defun stringloop ()
(with-input-from-string (s "foo" :index j )
  (do ((line (read-line s nil) ;; var init-form
         (read-line s nil))) ;; step=form
      ((null line) (progn (format t "null output ~a~% "(null line)) (format t "line output ~a~% " line))))))

1 个答案:

答案 0 :(得分:6)

你没有在循环体中放任何东西。你的函数读取一行("foo"),对它没有任何作用,然后读取另一行(nil),你的终止条件变为真,你打印空行。

运行此修改后的版本以查看发生的情况:

     (defun stringloop ()
       (with-input-from-string (s "foo")
         (do ((line (read-line s nil) ;; var init-form
                    (read-line s nil))) ;; step=form
             ((null line) (format t "termination condition - line: ~s~% " line))
           (format t "in loop - line: ~s~%" line))))