gurdingering
gurdingering

Reputation: 237

Racket - How to use foldr to evaluate if any element in a list satisfies an argument?

I have the task of writing a program called any? that requires an input of a list and one-argument procedure and then tells you if any element in that list satisfies the procedure.

ex: (any? odd? (list 2 4 6 8)) -> false

I need to use foldr in the program.

(define (any? procedure list1)
  (foldr (lambda (x y) (if (procedure x) true (any? procedure y))) false list1))

This is what I have so far, but when I run the program on (any? odd? (list 2 4 6 8)) I keep getting an error saying "foldr : third argument must be a list, given false". I think this is because the base case of empty becomes the boolean false, which then is substituted for y, which is invalid since you need a list to run the recursive call.

Can someone help me go through the thought process to fix this?

Upvotes: 1

Views: 1372

Answers (1)

Jay Kominek
Jay Kominek

Reputation: 8783

foldr handles the recursion for you; you shouldn't be calling any? again inside of the lambda. Instead, the false branch can just be y.

Or, a bit more obviously, perhaps:

(define (any? procedure lst)
  (foldr (lambda (x y) (or (procedure x) y)) #f lst))

Additionally, the error you're getting is because inside of the lambda, y is a boolean value. You're then passing it in as the second argument to any?, where you're expecting a list. Sadness results.

Upvotes: 5

Related Questions