这是条件表达式的语法:
(cond
[ConditionExpression1 ResultExpression1]
[ConditionExpression2 ResultExpression2]
...
[ConditionExpressionN ResultExpressionN])
(cond
[ConditionExpression1 ResultExpression1]
[ConditionExpression2 ResultExpression2]
...
[else DefaultResultExpression])
条件表达式的求值遵循 2 条规则
1) 规则 cond_false
(cond == (cond
[#false ...] ; first line removed
[condition2 answer2] [condition2 answer2]
...) ...)
2) 规则 cond_true
(cond == answer-1
[#true answer-1]
[condition2 answer2]
...)
第二条规则也适用于条件为 else 时(但请注意 else 只能出现在最后一个子句中)。
示例:
(cond
[(= 2 0) #false]
[(> 2 1) (string=? "a" "a")]
[else (= (/ 1 2) 9)])
== {通过评估 (= 2 0) 到 #false}
(cond
[#false #false]
[(> 2 1) (string=? "a" "a")]
[else (= (/ 1 2) 9)])
== {按规则cond_false}
(cond
[(> 2 1) (string=? "a" "a")]
[else (= (/ 1 2) 9)])
== {通过评估 (> 2 1) 到 #true}
(cond
[#true (string=? "a" "a")]
[else (= (/ 1 2) 9)])
== {按规则cond_true}
(string=? "a" "a")
== {通过评估 (string=? "a" "a") 到 true}
#true
(define (mymax x1 x2 x3)
(cond
((and (x1 > x2) (x1 > x3)) x1)
(else (and (x2 > x1) (x2 > x3)) x2)
(else (and (x3 > x1) (x3 > x2)) x3)
))
(print (mymax 10 5 1))
(2 > 1) 这样的表达式将不起作用。应该是(> 2 1)。 function application 的语法是前缀语法,即左括号后面应该是函数名,函数名后面应该是参数。
您得到的错误是第二个子句的语法错误。 (else (and (x2 > x1) (x2 > x3)) x2) 该子句有 3 个部分:else、(and (x2 > x1) (x2 > x3)) 和 x2。但是按照cond的语法,一个子句应该只有2个。
去掉elses 并添加> 前缀后:
(define (mymax x1 x2 x3)
(cond
((and (> x1 x2) (> x1 x3)) x1)
((and (> x2 x1) (> x2 x3)) x2)
((and (> x3 x1) (> x3 x2)) x3)))
(print (mymax 10 5 1))
程序打印10。但请注意,它不适用于(mymax 5 5 5),因此我们将所有>s 转为>=s:
(define (mymax x1 x2 x3)
(cond
[(and (>= x1 x2) (>= x1 x3)) x1]
[(and (>= x2 x1) (>= x2 x3)) x2]
[(and (>= x3 x1) (>= x3 x2)) x3]))
(mymax 10 5 1)
; => 10
(mymax 5 5 5)
; => 5
最后,函数不会“返回”值。一个更好的心智模型是认为他们的身体减少到一个价值。
(define (f x-1 ... x-n)
f-body)
(f v-1 ... v-n)
; == f-body
; with all occurrences of x-1 ... x-n
; replaced with v-1 ... v-n, respectively
请参阅:Racket Guide、The Racket Reference、HtDP。