- A recursive function is a function that calls itself
one or more times within its body.
- A recursive function is tail-recursive, if when the
base case is hit, the answer is known and no more
computation needs to be done in the unwinding of the
recursion. Tail recursion is very good in Common Lisp
because the compiler will detect it and automatically
translate the code into an iterative construct.
- One common form of recursion is rest recursion.
(defun my-reverse (alist)
(if (null alist)
nil
(append (my-reverse (rest alist)) (list (first alist)))
)
)
- Another common form of recursion is first/rest recursion.
(defun reverse-all (alist)
(cond
((null alist) nil)
((atom alist) alist)
(t (append (reverse-all (rest alist)) (list (reverse-all (first alist)))))
)
)
- It is possible to use optional parameters.
(defun add (n &optional (m 0)) ;; if m is not supplied, it is 0
(+ n m)
)
(add 10) ;; one way to call the above function
(add 10 5) ;; another way
- It is possible to use rest parameters.
(defun how-many (n &rest numbers)
(+ 1 (length numbers))
)
(how-many 1)
(how-many 1 2)
(how-many 1 2 3) ;; Cool, huh?
- It is possible to use keyword parameters.
(defun add (&key (number1 0) (number2 0))
(+ number1 number2)
)
(add)
(add :number1 5)
(add :number1 5 :number2 10)
(add :number2 10 :number1 5)