"You are writing a function with a free variable. How do you bundle a function with a data value defined outside the procedure's body?" If the data value is defined inside the procedure, remember, it gets reset to the same value each time, and obviously this isn't going to track state at all well. "So you might try defining the balance outside the function." But that doesn't work, because now the value isn't encapsulated anymore. "Therefore, create the function in an environment where its free variables are bound to local variables."
The only key thing to note here is that "withdraw" references a lambda, a function literal in Scheme. We'll try to keep this flavor in the other language implementations, just to be faithful:
(define withdraw (let ((balance 100)) ;; balance is defined here, (lambda (amount) (if (>= balance amount) ;; so this reference is bound (begin (set! balance (- balance amount)) balance) (error "Insufficient funds" balance))) ))
Last updated: 16 March 2022Tags: pattern implementation structural scheme