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?

  • $\begingroup$ Welcome to Computer Science Stack Exchange. Please read cs.stackexchange.com/tour, if you have not yet done so. --- Asking for terminology is appropriate, and you did it well, but thanks for reminding me to change your tag. $\endgroup$ – babou Aug 12 '15 at 0:20
  • $\begingroup$ @babou I did thank you, and I wasn't entirely clear on whether asking for terminology was appropriate so I also asked in chat. $\endgroup$ – Kit Sunde Aug 12 '15 at 0:21
  • $\begingroup$ Not that I know of but I could be wrong. That said though there is a term for a function that captures a value and that is called a "closure". $\endgroup$ – Jake Aug 12 '15 at 0:27

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.


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.


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.