"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."
withdraw = (do: var balance = 100; do amt: if amt <= balance then balance := balance - amt; balance else throw new RuntimeException("Insufficient funds") fi done; done;) (); println (withdraw 10); // prints 90 println (withdraw 10); // prints 80 println (withdraw 10); // prints 70
Last updated: 16 March 2022Tags: pattern implementation structural yeti