我刚学习了几天,但教授给我安排了一个练习。但是,我的代码无法编译,有人能告诉我编码部分哪里出错了吗?

(defun( MIN-2 a b)
(cond
((and (numberp a) (numberp b) (<= a b)) a b)
((and (numberp a) (numberp b) nil) ERROR)
)
)发布于 2019-02-20 08:35:48
直译:
(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)))并请缩进您的代码,不要留下括号周围。
发布于 2019-02-20 20:57:08
为什么您的代码失败
有人能告诉我我的编码部分哪里出了问题吗?
(defun( MIN-2 a b)
(cond
((and (numberp a) (numberp b) (<= a b)) a b)
((and (numberp a) (numberp b) nil) ERROR)
)
)让我重新格式化您的代码(自动缩进+压缩括号):
(defun (MIN-2 a b) ;; << bad syntax, as already pointed out in another answer
(cond
((and (numberp a) (numberp b) (<= a b))
a
b)
((and (numberp a) (numberp b) nil)
ERROR)))让我们修复defun的语法
(defun MIN-2 (a b)
(cond
((and (numberp a) (numberp b) (<= a b))
a
b)
((and (numberp a) (numberp b) nil)
ERROR)))错误(我正在编译Emacs +SBCL下的代码):
未定义变量:错误
实际上,error在这里是一个自由变量。你需要引用它。
(defun MIN-2 (a b)
(cond
((and (numberp a) (numberp b) (<= a b))
a
b)
((and (numberp a) (numberp b))
'ERROR)))警告:
删除无法到达的代码(错误加下划线)。
实际上,这里的条件是一个and表达式,其中至少有一个表达式是NIL,这意味着连接始终是假的。这种情况是不可能发生的,这就是为什么优化的原因。
此外,第一条的检验是:
(and (numberp a) (numberp b) (<= a b))子句体是a,后面是b,这意味着计算a,它的值被丢弃(从未使用),然后计算b,它的值是cond表达式的值:当两个输入都是a <= b这样的数字时,总是返回b。
显然,这不是你应该做的。其他答案已经涵盖了好的解决办法。
备选方案
我来这里也是为了提供另一种选择,而不一定是对家庭作业友好的答案:
捕获异常
(defun min-2 (a b)
(handler-case (if (<= a b) a b)
(error () 'error)))渔获量例外(之二)
(defun min-2 (a b)
(or (ignore-errors (if (<= a b) a b))
'error))使用泛型函数
(defgeneric min-2 (a b)
(:method ((a number) (b number)) (if (<= a b) a b))
(:method (a b) 'error))发布于 2019-02-20 03:51:34
您使用了错误的语法来定义函数。使用defun function-name (args)
(defun MIN-2 (a b)
(cond
((and (numberp a) (numberp b) (<= a b)) a b)
((and (numberp a) (numberp b) nil) ERROR)
)
)https://stackoverflow.com/questions/54778426
复制相似问题