conditional-statements - 对象#f 或#t 不适用
问题描述
我正在尝试创建一个函数,该函数获取传入的 3 个数字中较大的 2 个的平方和。(SICP中的练习 1.3 )
当我运行以下代码时,我收到错误“;对象#f 不适用。” 如果我在函数调用中切换 3 和 1,错误消息将显示 #t 而不是 #f。
(define (sumOfSquareOfLargerTwoNumbers a b c) (
cond (
( (and (> (+ a b) (+ a c) ) (> (+ a b) (+ b c) ) ) (+ (square a) (square b) ) )
( (and (> (+ a c) (+ a b) ) (> (+ a c) (+ b c) ) ) (+ (square a) (square c) ) )
( (and (> (+ b c) (+ a b) ) (> (+ b c) (+ a c) ) ) (+ (square b) (square c) ) )
)
))
(sumOfSquareOfLargerTwoNumbers 1 2 3)
我假设适当的条件会返回真,我会得到较大的两个数字的平方。有人可以解释为什么我会收到此错误吗?
解决方案
前面的括号太多cond
,这导致了问题:
(cond (((and
您的解决方案的正确语法应该是:
(define (sumOfSquareOfLargerTwoNumbers a b c)
(cond ((and (> (+ a b) (+ a c)) (> (+ a b) (+ b c)))
(+ (square a) (square b)))
((and (> (+ a c) (+ a b)) (> (+ a c) (+ b c)))
(+ (square a) (square c)))
((and (> (+ b c) (+ a b)) (> (+ b c) (+ a c)))
(+ (square b) (square c)))))
发生的事情是条件评估为布尔值,并且意外的括号使它看起来像一个过程应用程序,所以你最终得到了这样的结果:
(#t 'something)
这当然失败,因为#t
或#f
不是程序,不能应用。只需注意括号并使用具有语法着色和代码格式的良好 IDE,您将不会再遇到此问题。
推荐阅读
- ffmpeg - 使用 frameskip 从视频 FFMPEG 中提取帧并相应地命名。\
- ruby-on-rails - 如何对关联错误消息进行分组?
- php - 按值对 Laravel 集合进行排序
- javascript - 为什么我的 fetch 在第一次调用时返回错误,但在后续调用中却没有?
- python - 使用基准年计算指数
- javascript - 我应该使用什么下拉菜单里面有很多元素?
- typescript - 如何在 Webpack 上避免重复的 sass 导入(使用 @use)
- c++ - 如何将 c 样式的字符串或字符串文字附加到 std::vector
? - python-3.6 - 如何将 TensorFlow 对象检测 API 模型转换为 TFLite?
- java - java中的正偶数代码帮助(Uncaught SyntaxError: Unexpected identifier",)