how to write function that returns function

Kragen Sitaker kragen at pobox.com
Tue May 21 09:52:32 EDT 2002


Michael Hudson <mwh at python.net> writes:
> Well, I just swiped this from the online version of SICP:
> 
> (define (make-withdraw balance)
>   (lambda (amount)
>     (if (>= balance amount)
>         (begin (set! balance (- balance amount))
>                balance)
>         "Insufficient funds")))
> 
> (define W1 (make-withdraw 100))
> (define W2 (make-withdraw 100))
> (W1 50)
> 50
> (W2 70)
> 30
> (W2 40)
> "Insufficient funds"
> (W1 40)
> 10
> 
> I don't suppose you need telling that in Python you do this like so:
> 
> class Balance:
>     def __init__(self, balance):
>         self.balance = balance
>     def withdraw(self, amount):
>         if amount <= self.balance:
>             self.balance -= amount
>             return self.balance
>         else:
>             return "Insufficient funds"
> 
> >>> W1 = Balance(100)
> >>> W2 = Balance(100)
> >>> W1.withdraw(50)
> 50
> >>> W2.withdraw(70)
> 30
> >>> W2.withdraw(40)
> 'Insufficient funds'
> >>> W1.withdraw(40)
> 10

FWIW closures are differently flexible than class instances; you can
have several closures that share the same state, for example, while
you can inspect the state of Python class instances (without the
debugger, which lets you do the same for closures in many Schemes).




More information about the Python-list mailing list