A single function needs to carry forward state from call to call, but you do not want to polute your environment with a global variable.
Use the
let form to define a lexical closure before the actual lambda expression that is the state-carrying function.
(define function-with-static-var
(let ((static-a 0) (static-b '()))
(lambda (a-number)
(set! static-b
(cons (list a-number
(set! static-a (+ a-number static-a))
static-b)))))
(function-with-static-var 1) => ((1 1))
(function-with-static-var 2) => ((2 3)(1 1))
(function-with-static-var 3) => ((3 6)(2 3)(1 1))
(function-with-static-var 4) => ((4 10)(3 6)(2 3)(1 1))
As with global variables, the use of static variables in this function introduces mutators into the code, and so the code is no longer purely functional. To retain purely functional code it is necessary to pass the additional state into the function.
IdiomMonadicProgramming and
IdiomStreams are two structured ways of handling this sort of state.
This is also a good way to remove so-called "magic numbers" from code. By defining constants within a
let expression or a
module they are hidden from the global namespace. This use of the let-before-the-lambda trick remains a pure-functional method of programming.
This method can also avoids unnecessary allocation in any code that uses constant values. For example the code below allocates a new string to hold the magic phrase every time it is called.
(define (magic-phrase name)
(let ((phrase "abracadabra"))
(string-append name " the magic phrase is " phrase)))
By using the static variable idiom we can ensure only a single allocation:
(define magic-phrase
(let ((phrase "abracadabra"))
(lambda (name)
(string-append name " the magic phrase is " phrase))))
The general case of this optimisation is known as lambda-lifting.
The term static variables comes from C. C does not provide closures but a limited form of closure can be imitated by declaring variables as static.
This is my first contribution... Hopefully it doesn't suck.
I like it. --
NoelWelsh - 14 Sep 2004
Needs work, please. Eg, function-with-static-var has unbalanced parens and there are numerous typos in the discussion.
Fixed --
NoelWelsh - 10 Apr 2007
--
JonathanArkell - 07 Sep 2004