MathGroup Archive 2009

[Date Index] [Thread Index] [Author Index]

Search the Archive

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: <hconr9$1lj$1@smc.vnet.net>

On Nov 3, 2:58 am, Erik Max Francis <m... at alcyone.com> wrote:
> The deposit function doesn't work, though:
>
> In[6]:= a = create["test", 100]
>
> Out[6]= Account["test", 100]
>
> In[7]:= getBalance[a]
>
> Out[7]= 100
>
> In[8]:= deposit[a, 25]
>
> During evaluation of In[8]:= Set::setps: Account[test,100] in the part
> assignment is not a symbol. >>
>
> Out[8]= 125
>
> In[9]:= getBalance[a]
>
> Out[9]= 100
>
> But here's what I'm confused; if I do what getBalance does manually, it
> works fine:
>
> In[10]:= a[[BALANCE]] += 25
>
> Out[10]= 125
>
> In[11]:= a
>
> Out[11]= 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[55]:= deposit[a, 25]

Out[55]= 125

In[56]:= getBalance[a]

Out[56]= 125

-Rob


  • Prev by Date: Re: ForAll testing equality, and Limit evaluating wrong
  • Next by Date: Re: Re: How to calculate a union
  • Previous by thread: MathKernel7 produces no Graphics
  • Next by thread: Re: Set::setps error? Twitter.m's OOP-like approach?