代码之家  ›  专栏  ›  技术社区  ›  David J.

这个基本的scheme函数有什么问题

  •  0
  • David J.  · 技术社区  · 3 年前

    我正在尝试编写一个scheme函数,它可以执行以下操作(摘自SICP):

    练习1.3。定义一个以三个数字为参数的过程 返回两个较大数字的平方和。

    以下是我的尝试:

    (define (square-sum-larger a b c)
      (cond ((and (< a b) (< a c))) (+ (* b b) (* c c)))
      (cond ((and (< b c) (< b a))) (+ (* a a) (* c c)))
      (cond ((and (< c a) (< c b))) (+ (* b b) (* a a)))
    )
    

    当我把这个输入到biwa scheme解释器中时,我得到以下信息:

    (square-sum-larger 4 5 6)
    16
    

    自从 4 不到 5 6 ,第一个条件不应该被计算吗,这意味着 5. 6. 应该归还吗?

    1 回复  |  直到 3 年前
        1
  •  2
  •   Kaz    3 年前
    (define (square-sum-larger a b c)
      (cond ((and (< a b) (< a c))) (+ (* b b) (* c c))) ;; this is thrown away
      (cond ((and (< b c) (< b a))) (+ (* a a) (* c c))) ;; this is thrown away
      (cond ((and (< c a) (< c b))) (+ (* b b) (* a a)))
    )
    

    只有最后一个 cond 做任何有用的事;前一个 康德 表达式没有任何副作用,因为它们只执行计算,不使用它们的值。方案编译器可以完全消除这些死代码。

    你可能想把所有的子句合并成一个条件:

    (define (square-sum-larger a b c)
      (cond ((and (< a b) (< a c))) (+ (* b b) (* c c))
            ((and (< b c) (< b a))) (+ (* a a) (* c c))
            ((and (< c a) (< c b))) (+ (* b b) (* a a))))