views:

2627

answers:

2

How would you use set! in 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?

+2  A: 

Easiest approach is probably to store some external state and have the implementation of f affect it's contents.

(define x 0)
(define (f n) (let ((tmp x)) (set! x n) tmp))

Thus, x is initally 0 and each call to f will return the current value of x and save the argument as the new value of x. Thus (f 0) followed by (f 1) will both return 0, leaving the final x value of 1. While evaluating (f 1) followed by (f 0) will yield 0 then 1, with a final x of 0.

Andrew Beyer
A: 

With call/cc.

(define (f)
  (call/cc
    (lambda (c) (+ (c 0) (c 1)))))

(write (f))

Invoking c within either argument to + causes f to return immediately, yielding 0 or 1 depending which argument is evaluated first.

But I suspect it will always evaluate left-to-right and thus return 0.

finnw