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

Pages: 1-

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-12 12:35

Bump.

Name: Anonymous 2012-07-12 12:39

You check for eof with eof-object?. Just remove the variable.

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.

Name: Anonymous 2012-07-13 4:14

>>4
I took your advice here:
You could also probably stuff proc and main into the same function and avoid the communication.

And I think it's probably the best option. I haven't actually used continuations at all, so I'll need to learn about them. Thanks for the help.

Name: Anonymous 2012-07-13 5:07

HANDLE MY ANUS

Name: Anonymous 2012-07-13 9:52

>>4
Two-args if considered harmful! And you could use receive to make the code look better.

;; Also in SRFI-8
(define-syntax (receive vs body body+ ...)
  (syntax-rules ()
    ((receive vs expr body body+ ...)
     (call-with-values (lambda () expr) (lambda vs body body+ ...)))))

(define (main)
  (receive (sum more?)
    (display sum) (newline)
    (when more? (main)))

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