racket - 如何设计一个接受两个 Boolean 参数并在其中一个(或两个)参数为真时返回真的函数?

;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 学生语言中,条件形式(ifcondor 等)要求其“问题表达式”为 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)

相似文章

java - 在线程中设置一个 volatile 变量

我试图在其他线程中设置一个名为accelerationCheck的易失性布尔变量,并从“主线程”中检索它的value。如果加速度在至少500毫秒内低于-7,则此变量必须为真,否则为假。问题是我有时会在...

随机推荐

最新文章