Re:Functional Programming Doesn’t Work (and what to do about...
by lutorm on Tuesday December 29, 2009 @09:58AM
(#1020543)
Um, 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?
Re:Functional Programming Doesn’t Work (and what to do about...
by DavidSJ on Tuesday December 29, 2009 @09:21PM
(#1021768)
With 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))))
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.