8

For example, write a function add:

add[3] return 3

add[4] return 7

add[10] return 17

cormullion
  • 24,243
  • 4
  • 64
  • 133
matrix42
  • 6,996
  • 2
  • 26
  • 62

1 Answers1

17

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

Mr.Wizard
  • 271,378
  • 34
  • 587
  • 1,371
  • 2
    @yohbs By the way, perfect!: http://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 01 '13 at 00: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 01 '13 at 02:20