简体   繁体   中英

Looping over lines in a string in Common Lisp

I'm trying to understand why this small piece of code does not work as expected. I would expect it to print out "foo", but in fact what I get is

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

NIL

I expect I am using do wrong, but I've not be able to figure out what.

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

You didn't put anything in the loop body. Your function reads a line ( "foo" ), does nothing with it, then reads another line ( nil ), your termination condition becomes true, and you print the null line.

Run this modified version to see what's happening:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM