【问题标题】:Why can't I use 'and' as the predicate in my 'cond' expression? [duplicate]为什么我不能在“cond”表达式中使用“and”作为谓词? [复制]
【发布时间】:2022-01-11 22:19:06
【问题描述】:

我是一名自学成才的软件工程师,正在努力通过遵循强烈推荐的 SICP 书来填补他们的 CS 知识空白。我在第一个练习中遇到了问题,我很确定这是一个语法问题,但我无法弄清楚。

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

#lang sicp

(define (square x) (* x x))

(define (squaresum x y) (+ (square x) (square y)))

(define
  (squaresumlg x y z)
  (cond
    (and (> x z) (> y z)) (squaresum x y)
    (and (> x y) (> z y)) (squaresum x z)
    (and (> y x) (> z x)) (squaresum y z)))

(squaresumlg 1 2 3)

为了运行它,我将 DrRacket 与 'sicp' 包一起使用。 and 表达式自己运行得很好,但在 cond 表达式中,我收到错误:

and: bad syntax in: and

谁能告诉我我的程序哪里出了问题?如果您对如何更有效地做到这一点有任何建议,请告诉我。

【问题讨论】:

  • 我之前遇到过这个问题,但无法理解答案。我不认为它回答了我的问题,但我可能错了。

标签: scheme racket sicp


【解决方案1】:

您缺少一些括号,cond 中的每个条件都应该被() 包围。您还缺少一个案例,请考虑一下 - 如果两个数字相同会发生什么?这应该可以修复缺少括号的错误:

(define (squaresumlg x y z)
  (cond
    ((and (> x z) (> y z)) (squaresum x y))
    ((and (> x y) (> z y)) (squaresum x z))
    ((and (> y x) (> z x)) (squaresum y z))
    (else (error "oops, you forgot to handle this case!"))))

这个例子表明你仍然需要为边缘情况制定逻辑(总是使用else 子句!)。也许使用>= 会有所帮助?

(squaresumlg 1 1 3)

【讨论】:

  • 谢谢!这解决了我的语法问题。我认为你是对的,我需要处理一些其他情况,现在错误消失了,我可以处理逻辑了。
  • @ElliottRhys 我很高兴!我不想破坏乐趣,但是如果您查找“SICP 练习 1.3”,您会在此站点中找到解决方案。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-09-24
  • 1970-01-01
相关资源
最近更新 更多