首页 > 解决方案 > 如何在 Common lisp 中进行多重条件检查?

问题描述

刚学了几天Common Lisp,但是教授给我布置了一个练习。但是,我的代码无法编译,谁能告诉我我的编码部分哪里出错了?这是问题

(defun( MIN-2 a b)
(cond  
((and (numberp a) (numberp b) (<= a b)) a b)
((and (numberp a) (numberp b)    nil) ERROR)
)
)

标签: lispcommon-lisp

解决方案


字面翻译:

(defun min-2 (a b)  ; Define a Lisp function MIN-2 … takes two arguments A and B
  (cond ((and (every #'numberp (list a b)) (<= a b)) a)  ; if … A <= B, returns A
        ((and (every #'numberp (list a b)) (> a b)) b)   ; if … A > B, returns B
        (t 'error)      ; if A or B is not a number (i. e. “else”), returns ERROR

改进:事先只检查一次数字。

(defun min-2 (a b)
  (cond ((not (every #'numberp (list a b))) 'error)
        ((<= a b) a)
        ((> a b) b)))

并且请缩进你的代码,不要把括号放在周围。


推荐阅读