42 lines
1.3 KiB
Common Lisp
42 lines
1.3 KiB
Common Lisp
;;; FILES 2: READING LINES
|
|
;;;
|
|
;;; (read-line in) returns the next line as a string. At the end of
|
|
;;; the file it signals an error - unless you say what to hand back
|
|
;;; instead:
|
|
;;;
|
|
;;; (read-line in nil nil) => the next line, or NIL at the end
|
|
;;;
|
|
;;; NIL at the end is the base case the recursion chapter taught:
|
|
;;; read a line, cons it onto the rest.
|
|
;;;
|
|
;;; SAVE-POEM below is complete: the exercise writes the very file
|
|
;;; it reads, so the checks need nothing from outside.
|
|
|
|
(defparameter *poem-file* "lisplings-poem.txt")
|
|
|
|
(defun save-poem ()
|
|
(with-open-file (out *poem-file* :direction :output :if-exists :supersede)
|
|
(format out "(lisp is life)~%")
|
|
(format out "lambda forever~%")
|
|
(format out "close the parens~%"))
|
|
t)
|
|
|
|
(defun poem-lines ()
|
|
(with-open-file (in *poem-file*)
|
|
(poem-rest in)))
|
|
|
|
;; TODO: The lines still waiting in the stream IN, in order - NIL
|
|
;; once READ-LINE hands you NIL.
|
|
(defun poem-rest (in)
|
|
(read-line in))
|
|
|
|
;;; ------------------------------------------------------------------
|
|
;;; Checks. Read them - they tell you what to aim for - but leave
|
|
;;; them unchanged.
|
|
;;; ------------------------------------------------------------------
|
|
|
|
(check (save-poem))
|
|
(check-equal '("(lisp is life)" "lambda forever" "close the parens")
|
|
(poem-lines))
|
|
(check-equal 3 (length (poem-lines)))
|