[plt-scheme] reading a whole file

From: Jens Axel Soegaard (jensaxel at soegaard.net)
Date: Tue Nov 4 10:39:59 EST 2008

Matthias Felleisen wrote:
> On Nov 4, 2008, at 9:52 AM, Shriram Krishnamurthi wrote:
>> Thanks, Robby.
>> 1. It might be nice if someone w/ Cookbook access posted this version
>> w/ a comment about atomicity.
> Could someone explain why the cookbook uses an accumulator and reverse? 
I guess you are referring to this snippet?

(define (readlines filename)
  (call-with-input-file filename
    (lambda (p)
      (let loop ((line (read-line p))
                 (result '()))
        (if (eof-object? line)
            (reverse result)
            (loop (read-line p) (cons line result)))))))

But what would you use instead of an accumulator?

The obvious solution

(define (readlines filename)
  (call-with-input-file filename
    (lambda (p)
      (let loop ()
        (let ((line (read-line p)))
          (if (eof-object? line)
              (cons line (loop))))))))

breaks on implementations with a small stack.

Jens Axel Søgaard

-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.racket-lang.org/users/archive/attachments/20081104/d809848d/attachment.html>

Posted on the users mailing list.