UP | HOME
Land of Lisp

Zhao Wei

How can man die better than facing fearful odds, for the ashes of his fathers and the temples of his Gods? -- By Horatius.

1. exercise

ref: chapter01

  1. 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).

  2. 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))))))
    
    
  3. 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)))))
    
  4. 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))