Exercise 3.8
From BluWiki
Exercise 3.8
Define a simple procedure f such that evaluating (+ (f 0) (f 1)) will return 0 if the arguments to + are evaluated from left to right but will return 1 if the arguments are evaluated from right to left.
The procedure f can return an arbitrary value the first time it is called, and otherwise needs to satisfy the following two properties:
- (f 0) returns <math>-y+1</math>, where <math>y</math> is the value that was returned on the previous call
- (f 1) returns <math>-y</math>, where <math>y</math> is the value that was returned on the previous call
(define f (let ((prev 0)) (lambda (x) (if (= x 0) (begin (set! prev (- 1 prev)) prev) (begin (set! prev (- 0 prev)) prev)))))
Another take on it ... slow echo answers with previous runs argument. 0 is used during first run.
(define (make-slow-echo) (let ((last-seen 0)) (lambda (x) (let ((return last-seen)) (set! last-seen x) return))))
(define f (make-slow-echo)) (+ (f 0) (f 1)) ;-> 0 (define g (make-slow-echo)) (+ (g 1) (g 0)) ;-> 1
Ozten 12:37, 2 October 2007 (EDT)