Return Styles: Pseud0ch, Terminal, Valhalla, NES, Geocities, Blue Moon. Entire thread

Handling eof in Scheme

Name: Anonymous 2012-07-12 8:38

I'm fairly new to Scheme and I wrote the following code:

(define (to-digit c)
 (- (char->integer c) (char->integer #\0)))

(define eof-flag #f)

(define (proc c)
 (cond ((eof-object? c) (set! eof-flag #t) 0)
  ((char=? c #\newline) 0)
  ((char-numeric? c) (+ (to-digit c) (proc (read-char))))
  (else (proc (read-char)))))

(define (main)
 (display (proc (read-char)))
 (newline)
 (cond (eof-flag #t)
  (else (main))))

(main)

I'm just wondering whether there's a better way to handle eof that doesn't require the use of a separate variable. Also, do you know of a more portable way for writing to-digit? Thanks!

Name: Anonymous 2012-07-13 2:47

scheme doesn't have the cleanest looking system for multiple return values, but it works:


(define (to-digit c)
  (- (char->integer c) (char->integer #\0)))

(define (proc c accumulation)
  (cond ((eof-object? c) (values accumulation #f))
        ((char=? c #\newline) (values accumulation #t))
        ((char-numeric? c) (proc (read-char) (+ (to-digit c) accumulation)))
        (else (proc (read-char) accumulation))))

(define (main)
  (call-with-values (lambda () (proc (read-char) 0))
                    (lambda (sum more?)
                      (display sum) (newline)
                      (if more? (main)))))

(main)


You could also return the number and flag in a list together, but extracting the values with car and cadr looks ugly. You could also probably stuff proc and main into the same function and avoid the communication.

Newer Posts
Don't change these.
Name: Email:
Entire Thread Thread List