8
$\begingroup$

For example, write a function add:

add[3] return 3

add[4] return 7

add[10] return 17

$\endgroup$
17
$\begingroup$

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

The simplest way I can think of to reset this counter to e.g. 77:

add[77 - add[0]];

add[3]
80

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.

It easy to reset the counter: just do add[] = (* new value *)

$\endgroup$
  • 2
    $\begingroup$ @yohbs By the way, perfect!: i.stack.imgur.com/j8vPn.png $\endgroup$ – Mr.Wizard Jan 31 '13 at 13:14
  • $\begingroup$ yes! unfortunately, I've earned some reputation now, and I can no longer take over the world. $\endgroup$ – yohbs Jan 31 '13 at 23:07
  • $\begingroup$ 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. $\endgroup$ – Joel Klein Feb 1 '13 at 0:00
  • $\begingroup$ @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. $\endgroup$ – Mr.Wizard Feb 1 '13 at 2:20

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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