Consider this infinite Fibonacci sequence:
var fib = fcn(ab){a,b:=ab; ab.del(0)+(a+b); a}.fp(L(0,1));
Ask it for a Fibonacci number and you get the first one. Ask again and you get the next one and so on:
> do(15){print(fib(),”,”)} → 0,1,1,2,3,5,8,13,21,34,55,89,144,233,377
It never restarts, it just continues the same sequence:
> fib() → 610
> fib() → 987
How does it do this? By using a closure over a mutable list that holds two Fibonacci numbers. This list is the parameter to a function that uses it like a shift register: the value-to-be-returned is popped off the front of the list and sum of the two is appended (del(0) is the pop and +(a+b) is the append). The list and the function are bound together in a partial application (the fp()) so that every time the function runs, the parameter is the next number(s) in the sequence.