Re: Set::setps error? Twitter.m's OOP-like approach?
- To: mathgroup at smc.vnet.net
- Subject: [mg104593] Re: Set::setps error? Twitter.m's OOP-like approach?
- From: ragfield <ragfield at gmail.com>
- Date: Wed, 4 Nov 2009 01:39:04 -0500 (EST)
- References: <email@example.com>
On Nov 3, 2:58 am, Erik Max Francis <m... at alcyone.com> wrote: > The deposit function doesn't work, though: > > In:= a = create["test", 100] > > Out= Account["test", 100] > > In:= getBalance[a] > > Out= 100 > > In:= deposit[a, 25] > > During evaluation of In:= Set::setps: Account[test,100] in the part > assignment is not a symbol. >> > > Out= 125 > > In:= getBalance[a] > > Out= 100 > > But here's what I'm confused; if I do what getBalance does manually, it > works fine: > > In:= a[[BALANCE]] += 25 > > Out= 125 > > In:= a > > Out= Account["test", 125] > > The Set::setps error is about Blocks so I suppose I'm running into some > scoping issue but I don't follow what it is. What am I missing here? > What's the right way to write getBalance? By the time deposit is called "a" has already evaluated to Account ["test", 100], which means a[[BALANCE]] += 25 at that point really means 100 += 25. What you are looking for is "call by reference" behavior, and the way to get it is to use one of the Hold* attributes. In this case you want to first argument of your deposit function to remain unevaluated so the actual symbol "a" is passed into the function in rather than the value of "a". You'll also need to change the pattern of the first argument from _Account to _Symbol. This works how you want: SetAttributes[deposit, HoldFirst] deposit[account_Symbol, amount_] := account[[BALANCE]] += amount In:= deposit[a, 25] Out= 125 In:= getBalance[a] Out= 125 -Rob