35 lines
978 B
Common Lisp
35 lines
978 B
Common Lisp
;;; FILES 4: NUMBERS FROM FILES (solution)
|
|
|
|
(defparameter *count-file* "lisplings-counts.txt")
|
|
|
|
(defun save-counts ()
|
|
(with-open-file (out *count-file* :direction :output :if-exists :supersede)
|
|
(format out "10~%")
|
|
(format out "20~%")
|
|
(format out "5~%"))
|
|
t)
|
|
|
|
(defun sum-counts ()
|
|
(with-open-file (in *count-file*)
|
|
(sum-rest in)))
|
|
|
|
(defun sum-rest (in)
|
|
(let ((line (read-line in nil nil)))
|
|
(if line
|
|
(+ (parse-integer line) (sum-rest in))
|
|
0)))
|
|
|
|
(defun first-number (s)
|
|
(parse-integer s :junk-allowed t))
|
|
|
|
;;; ------------------------------------------------------------------
|
|
;;; Checks. Read them - they tell you what to aim for - but leave
|
|
;;; them unchanged.
|
|
;;; ------------------------------------------------------------------
|
|
|
|
(check (save-counts))
|
|
(check-equal 35 (sum-counts))
|
|
(check-equal 12 (first-number "12 apples"))
|
|
(check-equal nil (first-number "no digits here"))
|
|
(check-error (parse-integer "12 apples") 'parse-error)
|