;;; FILES 4: NUMBERS FROM FILES ;;; ;;; A file full of text can be full of numbers wearing strings. ;;; PARSE-INTEGER takes one off: ;;; ;;; (parse-integer "42") => 42 ;;; ;;; With :JUNK-ALLOWED T it reads the leading number and ignores ;;; the rest; without it, junk is a PARSE-ERROR. No number at all, ;;; and the junk-allowed answer is NIL. ;;; ;;; SAVE-COUNTS below is complete: the exercise writes the very ;;; file it reads. (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))) ;; TODO: The lines of IN, each parsed into a number, added up. (defun sum-rest (in) (parse-integer (read-line in))) ;; TODO: The leading number in the string S, junk allowed - NIL ;; when S has no number at all. (defun first-number (s) (parse-integer s)) ;;; ------------------------------------------------------------------ ;;; 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)