Day 33/100: Busy day / Closures

Today was a bit busier than I thought it would be. I did some playing around with trying to better understand closures. I think I understand them a little better but one of things I'm having trouble with is figuring out how something magically becomes a closure.

Take this for instance:

 (define (make-serial-number-generator)
   (let ((current-serial-number 0))
     (lambda ()
       (set! current-serial-number (+ current-serial-number 1))
       current-serial-number)))

 (define entry-sn-generator (make-serial-number-generator))

I understand that in this case a new instance of the procedure make-serial-number-generator needs to be wrapped in entry-en-generator otherwise it won't work properly (it gets reset each time). However:

(define counter
(let ((count 0))
    (lambda (x)
    (set! count (+ x count))
    count)))

This doesn't need the wrapping and I can use (counter 3) to increment the counter by 3. Worse, I can't seem to replicate the need for the generator wrapper.

So confused.

Any help on what the difference is would be appreciated. Thanks!


links

social