One use of self-modifying functions is to provide for learning without
introducing data structures outside the function. If some function takes
a long time to execute, always returns the same result when called with
the same arguments, and is expected to be called often with the same
arguments, it may be useful to learn what the result is for each
frequently used set of arguments. This learning can be stored inside
the function by having the function modify itself each time it is
called with a new set of arguments.
Here is a simple example which computes the square of a number.
The example has been fully tested in Allegro Common Lisp.
The learner_square function takes only one argument but can be modified
readily to use more than one. When learner_square is first defined, the
middle of the lambda_list is:
(COND (NIL)
(T (LET* # # # RESULT)))
When learner_square is called with x = 3, it returns 9 and redefines
itself so now the middle of the lambda_list is:
(COND (NIL)
((EQUAL X 3) 9)
(T (LET* # # # RESULT)))
If learner_square is ever called again with x=3, 9 is returned from
the cond without recomputing the result and without the function
redefining itself.
If learner_square is called with x = -7, it returns 49 and redefines
itself so now the middle of the lambda_list is:
(COND (NIL)
((EQUAL X -7) 49)
((EQUAL X 3) 9)
(T (LET* # # # RESULT)))
So now it will return the answer without having to calculate or redefine
itself if it is called with x=3 or x=-7.
(defun learner_square (x)
(cond (nil) ; The (nil) is just a placeholder
(t
(let* ((result (* x x))
(lambda_list (function-lambda-expression
(symbol-function 'learner_square)))
(arguments (cadr lambda_list))
(body (caddr (caddr lambda_list)))
(answers (cdr body)))
(rplacd answers
(cons (list (list 'equal 'x x) result)
(cdr answers)))
(eval `(defun learner_square ,arguments ,body))
result))))
This function was a lot simpler to write in older versions of Lisp.
Common Lisp makes it a big deal to get the lambda list defining a
function. Bring back getd.