[plt-scheme] Passing procedures are parameters.

From: Joe Marshall (jmarshall at alum.mit.edu)
Date: Mon Feb 2 20:05:48 EST 2009

On Mon, Feb 2, 2009 at 4:44 PM, aditya shukla
<adityashukla1983 at gmail.com> wrote:
> Hello guys , i am new to scheme and still learning to think in the
> procedural way.I have a question.Is there a way to pass  a predicate as a
> parameter .for example
> (
> every? predicate lst) returns #f if any element of lst fails to
> satisfy predicate, and returns #t otherwise.
>> (every? number? '(a b c 3 e))
> #f
>> (every? number? '(1 2 3 5 4))
> #t
> I can use map and check is the elements in the list are numbers .But what if
> i have to check for any other predicate.I mean can this be generalized.

You bet.  Any predicate with a name, whether you define it yourself or
whether it is built in will work.

(define my-test (lambda (thing) (and (number? thing) (even? thing) (>
thing 12))))

(every? my-test '(1 2 3 5 4)) => #f

(every? my-test '(42 88)) => #t

In fact, you can even use predicates that
*don't* have names but are just a tiny snippet of code:

;; Check if every word is a 4-letter word.
(every? (lambda (w) (and (string? w) (= (string-length w) 4))) list-of-words)

Rule of thumb for Scheme:
If it ought to be generalizable, it is.


Posted on the users mailing list.