From: nick_keighley_nospam@... Date: 2009-02-25T20:24:18+09:00 Subject: Re: reading file to list On 24 Feb, 15:00, nick_keighley_nos...@hotmail.com wrote: > On 17 Jan, 17:16, Xah Lee wrote: > > Here's a interesting toy problem posted by Drew Krause to > > comp.lang.lisp: > > > ------------------------ > > On Jan 16, 2:29 pm, Drew Krause wrote [paraphrased a bit]: > > > OK, I want to create a nested list in Lisp (always of only integers) > > from a text file, such that each line in the text file would be > > represented as a sublist in the 'imported' list. > > > example of a file's content > > > 3 10 2 > > 4 1 > > 11 18 > > > example of programing behavior > > (make-list-from-text "blob.txt") => ((3 10 2) (4 1) (11 18)) > scheme: > > (define (read-line port) >     (define (rec-read-line port line) >         (define next-char (peek-char port)) >         (define number #f) >         (cond ((eof-object? next-char) '()) >               ((char=? next-char #\newline) (read-char port) line) >               ((char-numeric? next-char) >                    (set! number (read port)) >                    (cons number (rec-read-line port line))) >               ((char=? next-char #\space) >                    (read-char port) >                    (rec-read-line port line)) >               (else (error (string-append "bad character \"" >                               (string next-char) "\""))) >     )) > >     (rec-read-line port '()) > ) > > (define (make-int-list port) >     (define line (read-line port)) >     (if (null? line) >         '() >         (cons line (make-int-list port)))) > > (define (make-list-from-text file) >     (make-int-list (open-input-file file))) an assignment-free version (define (read-line port) (define (rec-read-line port line) (let ((next-char (peek-char port))) (cond ((eof-object? next-char) '()) ((char=? next-char #\newline) (read-char port) line) ((char-numeric? next-char) (let ((number (read port))) (cons number (rec-read-line port line)))) ((char=? next-char #\space) (read-char port) (rec-read-line port line)) (else (error (string-append "bad character \"" (string next-char) "\"")))))) (rec-read-line port '())) (define (make-int-list port) (let ((line (read-line port))) (if (null? line) '() (cons line (make-int-list port))))) (define (make-list-from-text file) (make-int-list (open-input-file file))) (define (mk) (make-list-from-text "blob.txt")) number was originally define'd but I discovered there were limits to where you could define things