1. exercise
ref: chapter01
power(x n) where x and n are integers
(defun power (x n) (cond ((= n 0) 1) ((evenp n) (expt (power x (/ n 2)) 2)) (t (* x (power x (- n 1)))))) (power 2 13)
Notice: Its execution time is not n it is log(n).
Write a function that count the number of atoms in an expression.
;; (count-atoms '(a (b) (c))) = 3 (defun count-atoms (exp) (cond ((null exp) 0) ((atom exp) 1) (t (+ (count-atoms (first exp)) (count-atoms (rest exp)))))) (count-atoms '(a (b) (c (d (e (f))))))
Write a function that counts the number of times a expression occurs anywhere within another expression.
(defun count-anywhere (item tree) (cond ((equal item tree) 1) ((atom tree) 0) (t (+ (count-anywhere item (first tree)) (count-anywhere item (rest tree)))))) (count-anywhere 'a '(a ((a) b) a (a (a (a)))))
compute dot product of two list
(defun dot (xs ys) (if (eq (length xs) (length ys)) (apply #'+ (mapcar #'* xs ys)) nil)) (dot '(1 2 3) '(2 3 4))