sample problem: procedures with state
- problem
write a procedure that takes a procedure p of one argument
and returns another procedure, that behaves exactly like p
except when presented with the argument ‘how-many,
which causes it to return the number of times p has been called.
- example
(define sc (counter square))
(sc 3) ==> 9
(sc 4) ==> 16
(sc ‘how-many) ==> 2
- solution
(define (counter p)(let ((ct 0)) (lambda (i) (if (eq? i ‘how-many) ct (begin (set! ct (inc ct)) (p i))))))