[plt-scheme] Passing procedures are parameters.

From: David Van Horn (dvanhorn at ccs.neu.edu)
Date: Mon Feb 2 20:16:45 EST 2009

aditya shukla 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.

Start with this program:

#lang scheme
(require htdp/testing)

;; [Listof Any] -> Boolean
;; Are all the elements in the list numbers?
(define (all-number? ls)
   (cond [(empty? ls) true]
         [else (and (number? (first ls))
                    (all-number? (rest ls)))]))

(check-expect (all-number? empty) true)
(check-expect (all-number? (list 1 2 3)) true)
(check-expect (all-number? (list 1 2 true)) false)

;; [Listof Any] -> Boolean
;; Are all the elements in the list booleans?
(define (all-boolean? ls)
   (cond [(empty? ls) true]
         [else (and (boolean? (first ls))
                    (all-boolean? (rest ls)))]))

(check-expect (all-boolean? empty) true)
(check-expect (all-boolean? (list true false true)) true)
(check-expect (all-boolean? (list 1 2 true)) false)

(generate-report)


Look at the definition of all-number? and all-boolean?.  Circle what is 
different between them.  Write a new function that has a definition with 
what is common between all-number? and all-boolean? and for each thing 
that is different, add a parameter and use that parameter in place of 
the piece you circled.  Now redefine all-number? and all-boolean? in 
terms of this new function, giving as an argument the thing that was 
different.  Now make sure all your (unchanged) tests pass.

This process, which is called Function Abstraction, is spelled-out in 
more detail in Section 19 of HtDP (htdp.org).  It leads naturally to 
higher-order programs, which is what you will get in this case if you 
follow the process correctly.

David



Posted on the users mailing list.