HDTP has an exercise where you create functions that check if all members of a list are true (all-true
) and if one is (one-true
). As the code for both is almost identical, I switched to #lang racket
and tried it with a lambda. This is what I got:
(define (all-true list-of-bools)
(truef (λ(x y) (and x y)) list-of-bools))
(define (one-true list-of-bools)
(truef (λ(x y) (or x y)) list-of-bools))
(define (truef f list-of-bools)
(cond
[(empty? list-of-bools) true]
[else (f
(first list-of-bools)
(truef f (rest list-of-bools)))]))
Does this look idiomatic? Am I doing anything wonky or formatting oddly?
If you are in #lang racket
land, this is probably more idiomatic
(define all-true (curry andmap values))
(define one-true (curry ormap values))
Or more verbosely but easily understandable
(define (all-true xs) (andmap (lambda (x) x) xs))
(define (one-true xs) (ormap (lambda (x) x) xs))
The heavy-lifting comes from andmap
and ormap
which are generalization of all-true
and one-true
.
If I didn’t have access to the advanced bits of Racket like in HTDP was what I wrote OK?
Yes! Totally.
sweet, thanks :slightly_smiling_face:
Strictly speaking, if you wanna follow HtDP, you probably wanna follow its design recipe. Like writing signatures, etc.
Wait a minute
This is why you should write tests :slightly_smiling_face:
> (one-true '(#f))
#t
@c
whoops!
(define (truef f end-bool list-of-bools)
(cond
[(empty? list-of-bools) end-bool]
[else (f
(first list-of-bools)
(truef f end-bool (rest list-of-bools)))]))
:slightly_smiling_face:
Yep, that would do it
People almost always put a space after an identifier and an an open paren. So (λ (x y)
or (lambda (x y)
.
(If you’re coming from a non-lisp, this will probably also help your brain from “mis-parsing” what are function applications and arguments, especially in bigger expressions.)
truef
seems fine, depending on whether you care about one-true
being able to short-circuit (stop at first non-true value).
And same for all-true
.
(I was starting to write something how the similarity of your truef
to fold
, but that might be N/A for what HtDP is trying to do at this point, idk.)
Thanks for the tips :+1:
Should one-true
return false if the list is empty? Right now it looks like it returns true.
Oops, sorawee pointed that out already, below. :)
(…or something like it)
:smile: