Skip to main content

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


For example, write a function add:


add[3] return 3


add[4] return 7


add[10] return 17



Answer




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


Comments