;; ;; some simple lisp examples ;; ;; a recursive factorial routine, ;; base case: factorial(1) = 1, ;; recursive case: factorial(N) = N * factorial(N-1) ;; (defun myfact (num) (cond ((<= num 1) 1) (t (* num (myfact (- num 1)))) ) ) ; (myfact 4) ; (myfact 12) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; a recursive member function - is atm a member of lst ;; (defun mymember (atm lst) (cond ((null lst) nil) ((eq atm (car lst)) lst) (t (mymember atm (cdr lst))) ) ) ; (mymember 'd '(a b c d e f g)) ; (mymember 'h '(a b c d e f g)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; a recursive list reversal - given (a b c) return (c b a) ;; (defun myreverse (lst) (cond ((= 1 (length lst)) lst) (t (append (myreverse (cdr lst)) (list (car lst)))) ) ) ; (myreverse '(a b c d e f g)) ; (myreverse '((a b c) (d e f g))) ;; another version of list reversal, using an accumulator variable ;; (defun myrev (lst &optional acc) (cond ((atom lst) acc) (t (myrev (cdr lst) (cons (car lst) acc))) ) ) ;;;;;;;the next routine is not tail recursion;;;;;;;;;;;;;;;;;;;;;;; ;; a recursive double-odd, double the odd values, leave the even values alone ;; (defun double-odd (lst) (cond ((null lst) nil) ((oddp (car lst)) (cons (* 2 (car lst)) (double-odd (cdr lst)))) (t (cons (car lst) (double-odd (cdr lst)))) ) ) ; (double-odd '(1 2 3 4 5 6 7 8 9)) ;;;;;;;mapping across lists;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;(mapcar 'evenp '(1 2 3 4 5 6 7 8 9))