'How to design a function that takes two Boolean parameters and returns true if either (or both) of the parameters are true?
;Boolean b1 b2:
;#true & #true => #true
;#true & #false => #true
;#false & #false => #false
I kind of know how it works, but I don't know how to write it in Racket. I should have two parameters in a function, but how can I write that in Racket. Should it starts like
(define (either-true? b1 b2)
())
Solution 1:[1]
Other
answers
show that the body of either-true? could be just(or b1 b2) or (if b1 #t b2) (or even (if b2 #t b1) )
A literal implementation of the "purpose" of either-true? could be:
(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 ]))
In the Racket student languages, conditional forms (if, cond, or, etc) require their
"question-expressions" to be Boolean values (#t or #f). Other Racket languages use
the Scheme interpretation of any non-#f value as true
in conditional contexts.
So yet another definition, using this interpretation of "truthiness", could be:
#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)))
It's worth noting that, although (either-true? b1 b2) looks like (or b1 b2), there
is a significant difference: or will not evaluate b2 if b1 is true; either-true? always
evaluates both arguments. The difference can be seen by running:
#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)))))
Solution 2:[2]
(define (either-true? b1 b2) (if b1 #t b2))
also make sure you have both of these check-expects: (check-expect (either-true? #t #f) #t) (check-expect (either-true? #f #t) #t)
good luck with fundies 1 lol
Solution 3:[3]
Your either-true? exists already in Racket and is called or.
(define (either-true? b1 b2) (or b1 b2))
Or just do:
(define either-true? or)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | mnemenaut |
| Solution 2 | |
| Solution 3 | Gwang-Jin Kim |
