For example, write a function add:
add[3] return 3
add[4] return 7
add[10] return 17
For example, write a function add:
add[3] return 3
add[4] return 7
add[10] return 17
Module and FunctionPossibly 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 definitionsAnother 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 *)
Unique["x", Temporary]to get similar behavior to theModulebut you will still needWithto 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 usingModuleefficiently. Admittedly I'm not the best at exhaustive analysis of programming constructs; if you're interested you should ask Leonid. – Mr.Wizard Feb 01 '13 at 02:20