c
2020-5-3 23:34:33

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?


sorawee
2020-5-3 23:53:01

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))


sorawee
2020-5-3 23:57:03

The heavy-lifting comes from andmap and ormap which are generalization of all-true and one-true.


c
2020-5-3 23:57:41

If I didn’t have access to the advanced bits of Racket like in HTDP was what I wrote OK?


sorawee
2020-5-3 23:58:10

Yes! Totally.


c
2020-5-3 23:59:11

sweet, thanks :slightly_smiling_face:


sorawee
2020-5-3 23:59:15

Strictly speaking, if you wanna follow HtDP, you probably wanna follow its design recipe. Like writing signatures, etc.


sorawee
2020-5-3 23:59:53

Wait a minute


sorawee
2020-5-4 00:00:29

This is why you should write tests :slightly_smiling_face:


sorawee
2020-5-4 00:00:37

> (one-true '(#f)) #t


sorawee
2020-5-4 00:00:56

@c


c
2020-5-4 00:01:41

whoops!


c
2020-5-4 00:08:14

(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:


sorawee
2020-5-4 00:08:44

Yep, that would do it


greg
2020-5-4 01:35:15

People almost always put a space after an identifier and an an open paren. So (λ (x y) or (lambda (x y).


greg
2020-5-4 01:37:58

(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.)


greg
2020-5-4 01:39:32

truef seems fine, depending on whether you care about one-true being able to short-circuit (stop at first non-true value).


greg
2020-5-4 01:40:39

And same for all-true.


greg
2020-5-4 01:42:59

(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.)


c
2020-5-4 02:03:12

Thanks for the tips :+1:


rokitna
2020-5-4 02:04:39

Should one-true return false if the list is empty? Right now it looks like it returns true.


rokitna
2020-5-4 02:06:15

Oops, sorawee pointed that out already, below. :)


rokitna
2020-5-4 02:06:43

(…or something like it)


c
2020-5-4 02:12:04

:smile: