3

Two examples, one in PHP:

function adder($i){
  static $a = 0; 
  $a += $i; 
  return $a;
}

A similar effect can be achieved with closures in javascript:

var adder = (function(){ 
  var a = 0; 
  return function(i){ 
    a += i;
    return a;
  } 
})();

In javascript I've really just created an object. Implementation details not withstanding, does stateful-functions have a formal name?

babou
  • 19,645
  • 43
  • 77
Kit Sunde
  • 131
  • 3

2 Answers2

3

Not that I know of, but "stateful function" is reasonably descriptive. In informal conversation, that's what I'd use, as long as I suspect the audience will understand what I mean. In formal writing, I might still use the same phrase but also provide a careful definition of what I meant by that phrase. Really, that's a large part of what "formal" writing is about: it's about being precise about what you mean.

D.W.
  • 167,959
  • 22
  • 232
  • 500
1

In the realm of functional programing, functions that give the same result when called with the same arguments are usually called pure.

The Wikipedia page explicitly adds the condition that mutable variables should not be modified by the function call, though presumably they mean mutable variables that can be observed outside of the function scope which shouldn't be the case for the variable a in your adder function (in a sane language).

This would make the result of adder an impure function, though that might have some negative connotation.

cody
  • 8,427
  • 33
  • 64