Re: Programming language difficulties.
- To: mathgroup at smc.vnet.net
- Subject: [mg38413] Re: [mg38382] Programming language difficulties.
- From: Alexander Sauer-Budge <ambudge at MIT.EDU>
- Date: Sat, 14 Dec 2002 03:19:44 -0500 (EST)
- Sender: owner-wri-mathgroup at wolfram.com
You don't need Evaluate for the the makewithdraw function since, unlike the first example, the module gets evaluated when you instantiate a new account. makewithdraw[initbalance_] := Module[{balance = initbalance}, Function[ amount, If[ balance >= amount, balance -= amount; balance, Print[ "Insufficient Funds" ] ] ] ] w1=makewithdraw[100]; w2=makewithdraw[100]; In[701]:= w1[50] Out[701]= 50 In[702]:= w2[70] Out[702]= 30 In[703]:= w2[40] From In[703]:= Insufficient Funds In[704]:= w1[40] Out[704]= 10 Have fun, SICP is an excellent book. Cheers! Alex On Friday, December 13, 2002, at 04:09 AM, Oliver Ruebenkoenig wrote: > Hi again Mathgroup ;-) > > This is a programming example from the wizard book chapter 3. > ( http://mitpress.mit.edu/sicp/full-text/book/book.html ) > > Consider the following: > > withdraw := Evaluate[ > Module[ { balance = 100 }, > Function[ amount, > If[ balance >= amount, > balance -= amount; balance, > Print[ "Insufficient Funds" ] > ] > ] > ] > ] > > In[2]:= withdraw [ 60 ] > > Out[2]= 40 > > In[2]:= withdraw[ 60 ] > Insufficient Funds > > The question now is, can I in Mathematica write a function that takes > as > argument the balance, so that I do not have to use the fixed balance = > 100. Note that in first example balance is _not_ present in the global > context. > > My idea was the following: > > secondWithdraw[ initBalance_ ] := Evaluate[ > Module[ { balance = initBalance }, > Function[ amount, > If[ balance >= amount, > balance -= amount; balance, > Print[ "Insufficient Funds" ] > ] > ] > ] > ] > > In[7]:= W1:=secondWithdraw[ 100 ] > > In[8]:= W1[ 60 ] > Out[8]= If[initBalance >= 60, balance$2 -= 60; balance$2, >> Print[Insufficient Funds]] > > So this however does not work. I _assume_ that Evaluate hits to early. > The evaluation of balance >= amount to initBalance >= amount is too > early. Is this the problem? How can I circumvent it? > > I'd be glad for any insights you might have. > > > Oliver Ruebenkoenig, <ruebenko at imtek.de> > Phone: ++49 +761 203 7293 > >