reading file to list
nick_keighley_nospam at hotmail.com
nick_keighley_nospam at hotmail.com
Wed Feb 25 06:24:07 EST 2009
On 24 Feb, 15:00, nick_keighley_nos... at hotmail.com wrote:
> On 17 Jan, 17:16, Xah Lee <xah... at gmail.com> 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))
<snip>
> 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"))
<snip>
number was originally define'd but I discovered there were
limits to where you could define things
More information about the Python-list
mailing list