首页 > 解决方案 > 对象#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)

我假设适当的条件会返回真,我会得到较大的两个数字的平方。有人可以解释为什么我会收到此错误吗?

标签: conditional-statementsschemesicp

解决方案


前面的括号太多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,您将不会再遇到此问题。


推荐阅读