読者です 読者をやめる 読者になる 読者になる

by shigemk2

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

対話によるCommon Lisp入門 46 otherwise

読書ノート

対話によるCommon Lisp入門 44 cond - by shigemk2
computeをcondからcaseへ
ohterwiseはどのキーリストにも見つからない場合を表す。

(defun compute (form)
  (if (atom form) form
      (case (second form)
        (+ (+ (compute (first form))
              (compute (third form))))
        (- (- (compute (first form))
              (compute (third form))))
        (* (* (compute (first form))
              (compute (third form))))
        (/ (/ (compute (first form))
              (compute (third form))))
        (otherwise 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 

;; Tracing function COMPUTE.
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