Path: utzoo!attcan!uunet!snorkelwacker!bloom-beacon!RPAL.COM!shaff From: shaff@RPAL.COM (Mike Shaff) Newsgroups: comp.lang.scheme Subject: Counter in SIOD Message-ID: <9008151504.AA15562@rpal.com> Date: 15 Aug 90 15:04:45 GMT References: <1990Aug15.005252.8122@agate.berkeley.edu> Sender: daemon@athena.mit.edu (Mr Background) Reply-To: shaff@rpal.com Organization: The Internet Lines: 37 ciao, ericco@ssl.berkeley.edu wrote: (define (cnt x) (lambda () (let ((y x)) (set! y (+ y 1))))) Eric is looking for a function that saves state with respect to y (actually he probably has something totally different in mind, but he did not want to complicate things). There are two problems with this code. First, you are not spawning a new closure (combination of state and lexical body). Second the use of set! to return a result leads to unspecified execution. Below is an example of how to obtain the functionality you want. (define spawn-counter (lambda (x) ;Take in our starting point (let ((y x)) ;capture it (lambda () ;return a new closure that will... (set! y (+ y 1)) ;bang on state each time called y)))) ;and return the new status ;Value: spawn-counter (define counter (spawn-counter 10)) ;Value: counter (counter) ;Value: 11 (counter) ;Value: 12 Enjoy, anonymous closures are one of Scheme's most wonderful things. The other things? Macros? No, just dreaming... mas Once in a while you get shown the light in the strangest of places if you look at it right.