;Boolean b1 b2:
;#true & #true => #true
;#true & #false => #true
;#false & #false => #false
我有点知道它是如何工作的,但我不知道如何在 Racket 中编写它。我应该在一个函数中有两个参数,但是如何在 Racket 中编写它。它应该像这样开始吗
(定义(无论是真的吗?b1 b2)
())
回答1
https://stackoverflow.com/a/72251184/16981884https://stackoverflow.com/a/72249539/16981884 表明 either-true?
的主体可能只是(or b1 b2)
或 (if b1 #t b2)
(甚至是 (if b2 #t b1)
)
either-true?
的“目的”的字面实现可能是:
(define (either-true? b1 b2) ;; Boolean Boolean -> Boolean
;; produce #t if either b1 or b2 is true, otherwise #f
(cond
[ b1 #t ]
[ b2 #t ]
[else #f ]))
在 Racket 学生语言中,条件形式(if
、cond
、or
等)要求其“问题表达式”为 Boolean values(#t
或 #f
)。其他Racket 语言在条件上下文中使用https://scheme.com/tspl4/start.html#./start:s106 的方案解释。
因此,使用这种对“真实性”的解释,另一个定义可能是:
#lang racket
(define (either-true? b1 b2) ;; Any Any -> Any
;; produce #f if both b1 and b2 #f, otherwise a truthy value
(findf values (list b1 b2)))
值得注意的是,虽然 (either-true? b1 b2)
看起来像 (or b1 b2)
,但有一个显着的区别:如果 b1 为真,则 or
不会评估 b2; either-true?
总是计算两个参数。通过运行可以看出差异:
#lang racket
(require math/number-theory)
(define (either-true? b1 b2)
(or b1 b2))
(time (or (prime? 7) (prime? (next-prime (expt 2 1000)))))
(time (either-true? (prime? 7) (prime? (next-prime (expt 2 1000)))))
回答2
(定义(无论是真的吗?b1 b2)(如果 b1 #t b2))
还要确保你有这两个检查期望: (check-expect (either-true?#t #f) #t) (check-expect (either-true?#f #t) #t)
祝你好运 1 大声笑
回答3
您的 either-true?
已经存在于 Racket 中并被称为 or
。
(define (either-true? b1 b2) (or b1 b2))
或者只是这样做:
(define either-true? or)