我为什么会收到错误消息:cond:期望有一个带有问题和答案的子句

问题描述

为什么会出现错误cond: expected a clause with a question and an answer,but found a clause with only one part?我在做什么错了?

基本上,我必须确定判别式是正数还是负数。

(define (has-real-roots? a b c)
  (cond
    [(positive? (- (square b) (* 4 a c)))]
    [else false]))

解决方法

根据documentationcond表达式中的每个子句都需要两个部分:“问题”(条件)和“答案”(要返回的值)。您的代码缺少第一个子句的“答案”部分,在这种情况下,返回true是合适的:

(define (has-real-roots? a b c)
  (cond [(positive? (- (square b) (* 4 a c))) true]
        [else false]))

但是您实际上并不需要在这里使用cond,这更简单并且可以完成相同的操作:

(define (has-real-roots? a b c)
  (positive? (- (* b b) (* 4 a c))))
,

Racket Documentation

如果您要检查的东西只有一个,或者我们将其称为case,那么我们就使用cond。您应该匹配语言语法。

#lang racket
(cond
    [#false 'you-wont-entry-this-part-because-test-express-is-false]
    [#false 'you-wont-entry-this-part-because-test-express-is-false]
    [#true 'entry-this]
    [else 'last-condiction])

#|
(cond
  [test-express-1 if-test-express-1-is-true-do-this]
  [test-express-2 if-test-express-2-is-true-do-this]
  ...
  [else if-test-express-1-to-n-all-false-do-this])
|#