"Optional" parameters - p. 83
--If the symbol &optional occurs in the parameter list of a function, then all
the arguments after it are optional, and default to nil.
1.
(defun philosoph (thing &optional property) ;; property defaults to nil
(list thing 'is property))
>(philosoph 'existence)
(EXISTENCE IS NIL)
(defun philosoph (thing &optional (property 'fun)) ;; property defaults to 'fun
(list thing 'is property))
>(philosoph 'existence)
(EXISTENCE IS FUN)
2. Using &optional for tail recursion
;;Vers. 1 - no tail recursion, (uses backtracking)
(defun my-length (lst)
(if (null lst)
0
(+ 1 my-length(rest (lst)))))
;;Vers. 2 - tail recursion (no backtracking) with an auxiliary function
(defun my-length (lst)
(my-length-aux lst 0))
(defun my-length-aux (lst count)
(if (null lst)
count
(my-length-aux (rest lst) (+ 1 count))))
;;Vers. 3 - tail recursion (no backtracking) with &optional
(defun my-length (lst &optional (count 0)) ;;count defaults to 0
(if (null lst)
count
(my-length (rest lst) (+ 1 count))))
>(my-length '(a (b c) (d e) f))
4