功能限制:
- 使用 Racket BSL
- 不允许使用逻辑运算符
- 只能使用 if、参数名称、#true 和 #false(尽管可能不需要全部)
- 覆盖测试所有可能的参数输入组合
- 不允许使用以下形式的 if(如果参数 #true #false)
这是我迄今为止尝试过的(但我使用了不允许的逻辑运算符(and,not,or):
; same? : Boolean Boolean -> Boolean
; returns true if either both boolean
; parameters are true or both are false
(check-expect (same? #t #t) #t)
(check-expect (same? #t #f) #f)
(check-expect (same? #f #t) #f)
(check-expect (same? #f #f) #t)
(define (same? x y)
(or (and x y) (not (or x y))))
; TODO: Design the function non-agreement? that takes two Boolean parameters
; and returns true if at least one of them is false.
; non-agreement? : Boolean Boolean -> Boolean
; returns true if at least one of the boolean
; parameters is false
(check-expect (non-agreement? #t #t) #f)
(check-expect (non-agreement? #t #f) #t)
(check-expect (non-agreement? #f #t) #t)
(check-expect (non-agreement? #f #f) #t)
(define (non-agreement? x y)
(not (and x y))
; TODO: Design the function follow-directions that takes two Boolean parameters:
; * if the first is false, it simply returns the second;
; * if the first is true, it returns the opposite of the second
; follow-directions : Boolean Boolean -> Boolean
; returns the second boolean parameter if the first
; is false; otherwise, returns the opposite of the
; second boolean parameter if the first is true
(check-expect (follow-directions #t #t) #f)
(check-expect (follow-directions #t #f) #t)
(check-expect (follow-directions #f #t) #t)
(check-expect (follow-directions #f #f) #f)
(define (follow-directions x y)
(or (and x (not y)) (and (not x) y)))
回答1
可以通过使用参数的 values 来取消以 (if parameter #true #false)
的形式使用 if
的限制。
例如。如果是 x = #true
,在评估 x 一个 if
语句后,代码将只运行 then 分支。在这个分支中,我确定 x = #true
所以它可以在我需要 #true
的任何地方(在这个分支中)替换。如果 x = #false
那么我可以在 else 分支中用 x
替换 #false
。
(define (same? x y)
(if x
y ; = (if y #true #false)
(if y
x ; = #false
#true)))
(define (non-agreement? x y)
(if x
(if y
#false
x) ; = #true
#true))
(define (follow-directions x y)
(if x
(if y
#false
x) ; = #true
y))