3 ms·
function A behaves differently depending on the number of times function B has been called and vice-versa. In C, this is easy! It can be done quickly and clean
by DavidSJ 17y ago
function A behaves differently depending on the number of times function B has been called and vice-versa.
In C, this is easy! It can be done quickly and cleanly by adding some global variables. In purely functional code, this is somewhere between a major rearchitecting of the data flow and hopeless.
In Common Lisp, I'd DEFVAR a variable with dynamic scope, then LET its value be incremented on each call to B. I'd never use SETQ or its variants. There's no major re-architecting here, and no breakage of the functional style. Dynamically-bound variables are like implicitly passed-through arguments to every function call.
- DavidSJ 17y agoThat said, this only works if all the calls to B are still on the stack. I'm not sure what the problem being solved is so I might have misunderstood the intention here.
- lutorm 17y agoUm, in purely functional code isn't this by definition not possible? As in that the definition of "functional" means that it has no side effects and the return value depend only on the input values?
- DavidSJ 17y agoWith dynamic variable binding, there are no side effects, because the LET is undone as soon as its scope is exited. Think of dynamic variables as constituting merely the implicit passing of a symbol->value hash table as an argument to every function call, and a LET as a local modification to this hash table. So: (defvar a 10) (defun x () (if (= a 0) t (let ((a (- a 1))) (x)))) behaves the same as: (defun x (&optional (a 10)) (if (= a 0) t (x (- a 1))))