隨着應用的常規格式和一些意見,你的代碼是:
(defun sum (n m)
;; if n and m are integers
(if (and (integerp n) (integerp m))
;; then …
(cond
;; first case: if the expression `(zerop n)` is true, then return m
((zerop n) m)
;; second case: if the expression `(zerop m)` is true, then return n
((zerop m) n)
;; third case: if the expression `if` is true, then
;; evaluate (< n 0), evaluate (sum (+ n 1) (- m 1)),
;; and return (sum (- n 1) (+ m 1))
(if (< n 0)
(sum (+ n 1) (- m 1))
(sum (- n 1) (+ m 1))))
;; else return nil
nil))
當我評價emacs的這個定義,然後嘗試評估,例如,(sum 2 3)
,我得到的錯誤居然是:
Debugger entered--Lisp error: (void-variable if)
(cond ((zerop n) m) ((zerop m) n) (if (< n 0) (sum ... ...) (sum ... ...)))
(if (and (integerp n) (integerp m)) (cond (... m) (... n) (if ... ... ...)) nil)
sum(2 3)
eval((sum 2 3))
eval-last-sexp-1(nil)
eval-last-sexp(nil)
call-interactively(eval-last-sexp nil nil)
因爲第三子句試圖採取的if
值作爲一個變量。我期望你想要的是,否則條款。使第三條相同形式的其他符合條件,將永遠是真實的,例如,t
:
(defun sum (n m)
(if (and (integerp n) (integerp m))
(cond
((zerop n) m)
((zerop m) n)
(t (if (< n 0)
(sum (+ n 1) (- m 1))
(sum (- n 1) (+ m 1)))))
nil))
然後(sum 2 3)
回報5
。