# How can I define a function that can accumulate its parameter?

For example, write a function add:

-

## 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 += # &;
]


3
7
17


Or generating such a function:

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


102
106
116


## DownValues definitions

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

add[] = 0;


3

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 *).
@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