Take the 2-minute tour ×
Mathematica Stack Exchange is a question and answer site for users of Mathematica. It's 100% free, no registration required.

For example, write a function add:

add[3] return 3

add[4] return 7

add[10] return 17

share|improve this question

1 Answer 1

up vote 15 down vote accepted

Module and Function

Possibly the easiest way is to use a unique symbol generated with Module to hold the value:

Module[{x = 0},
 add = x += # &;
]

add[3]
add[4]
add[10]
3
7
17

Or generating such a function:

makeAccumulator[init_: 0] := 
  Module[{x = init},
    x += # &
  ]

add = makeAccumulator[99];

add[3]
add[4]
add[10]
102
106
116

DownValues definitions

Another approach is to store the value in a separate rule attached to the same symbol:

add[] = 0;
add[x_] := add[] += x;

add[3]
add[4]
add[10]
3
7
17

Here I used add[] to hold the value but you could use any other pattern you wish. Also, this makes it easy to reset the counter: just do add[] = (* new value *).

share|improve this answer
2  
@yohbs By the way, perfect!: i.stack.imgur.com/j8vPn.png –  Mr.Wizard Jan 31 '13 at 13:14
    
yes! unfortunately, I've earned some reputation now, and I can no longer take over the world. –  yohbs Jan 31 '13 at 23:07
    
Why not Unique instead of Module to generate the counter storage? While it works, I'm not sure it's a good idea to rely on leaking Module variables this way. But I bring it up because I'd be glad to understand why it might be relied on. –  Joel Klein Feb 1 '13 at 0:00
    
@JoelKlein I believe you could use Unique["x", Temporary] to get similar behavior to the Module but you will still need With to get it into the parts of the code you want so you're "reinventing the wheel" as I see it. I don't see this as "leaking" variables but simply using Module efficiently. Admittedly I'm not the best at exhaustive analysis of programming constructs; if you're interested you should ask Leonid. –  Mr.Wizard Feb 1 '13 at 2:20

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.