by shigemk2

当面は技術的なことしか書かない

対話によるCommon Lisp入門 44 cond

ifを入れ子にしまくるより、confを使ったほうが便利なときもある。
多分岐ができるから。

(cond (c1 f1)
      (c2 f2)
      .....
      (cn fn))

で、condを使った例。

(defun compute (form)
  (cond ((atom form) form)
        ((eql (second form) '+)
              (+ (compute (first form))
                 (compute (third form))))
        ((eql (second form) '-)
              (- (compute (first form))
                 (compute (third form))))
        ((eql (second form) '*)
              (* (compute (first form))
                 (compute (third form))))
        ((eql (second form) '/)
              (/ (compute (first form))
                 (compute (third form))))
         (t nil)))

(print (compute '(3 + 4)))
(print (compute '(3 - 4)))
(print (compute '(3 * 4)))
(print (compute '(3 / 4)))

(trace compute)
(print (compute '((16 / 4) - (2 * 2))))

結果

7 
-1 
12 
3/4 

1. Trace: (COMPUTE '((16 / 4) - (2 * 2)))
2. Trace: (COMPUTE '(16 / 4))
3. Trace: (COMPUTE '16)
3. Trace: COMPUTE ==> 16
3. Trace: (COMPUTE '4)
3. Trace: COMPUTE ==> 4
2. Trace: COMPUTE ==> 4
2. Trace: (COMPUTE '(2 * 2))
3. Trace: (COMPUTE '2)
3. Trace: COMPUTE ==> 2
3. Trace: (COMPUTE '2)
3. Trace: COMPUTE ==> 2
2. Trace: COMPUTE ==> 4
1. Trace: COMPUTE ==> 0
0