asdfghjkl
asdfghjkl

Reputation: 393

Defining a procedure given a predicate in racket

Given a predicate that tests a single item, such as positive?, I am trying to create an all-are version of it for testing whether all elements of the list satisfy the predicate

Ex:
((all-are positive?) '(1 2 3 4)) => #t
((all-are even?) '(2 4 5 6 8)) => #f

all-are should take a predicate as an argument and return a new function that can be applied to the list of elements

Upvotes: 0

Views: 789

Answers (2)

Rajeev
Rajeev

Reputation: 41

Just trying to only use the basics of 'foldr', the code turns out to be:

(define (all-are pred l)
   (foldr (λ (x y)
      (and y (pred x))) #t l))

Try to use foldr, foldl and other basics and figure out the necessary parameters, this will be a good programming practice....Hope it helps!!!

Upvotes: 0

Óscar López
Óscar López

Reputation: 236004

That's quite simple to express in terms of an existing procedure: andmap - which returns #t if a given predicate, when applied to all the elements in a list, evaluates to true for all of them:

(define ((all-are predicate) lst)
  (andmap predicate lst))

I'm using a bit of syntactic sugar for returning a curried procedure, because the question states that a function must be returned. It works as expected:

((all-are positive?) '(1 2 3 4))
> #t

((all-are even?) '(2 4 5 6 8))
> #f

I'm guessing that you have to implement the procedure from scratch, and not using existing procedures as in my solution. A good exercise would be to turn the short version above (which demonstrates the general idea of what needs to be done) into something simpler using only basic forms - that's probably what your teacher expects from you.

Upvotes: 3

Related Questions