I am trying to fully understand Objects and local states of their variables
This code seems to produce different results for the same procedure called multiple times, meaning the local variable changes:
(define new-withdraw
(let ((balance 100))
(lambda (amount)
(if (>= balance amount)
(begin (set! balance (- balance amount))
balance)
"Insufficient funds"))))
For this other code, it produces the same result, which means it creates a new local variable for every procedure call:
(define (make-account)
(let ((balance 100))
(define (withdraw amount)
(if (>= balance amount)
(begin (set! balance (- balance amount))
balance)
"Insufficient funds"))
(define (deposit amount)
(set! balance (+ balance amount))
balance)
(define (dispatch m)
(cond ((eq? m 'withdraw) withdraw)
((eq? m 'deposit) deposit)
(else (error "Unknown request -- MAKE-ACCOUNT"
m))))
dispatch))
My questions are:
Why do they behave differently despite creating a local variable using let?
Is there a way one can make the second code work as the first one without passing
balance
as a parameter ofmake-account
?
Thank you