[previous] [up] [next]     [index]
Next: Syntax of lambda Up: Intermezzo 4 Defining Functions on Previous: Intermezzo 4 Defining Functions on

Intermezzo 4 Defining Functions on the Fly

Many uses of abstract functions require the definition of auxiliary functions. Consider filter1, which consumes a filtering function, a list, and a filtering item. In the previous section alone, we encountered three uses of filter1 with three different auxiliary functions: squared?, tex2html_wrap_inline72246 , and eq-ir?.

Since these auxiliary functions are only used as arguments to filter1, we should employ the program organization guidelines from the preceding intermezzo ([cross-reference]). That is, we should use a local-expression to indicate that the application of filter1 and the auxiliary function definition belong together. Here is one possible arrangement for the filter1-eq-ir? combination:

;; find : list-of-IRs symbol -> boolean
(define (find aloir t) 
  (local ((define (eq-ir? ir p) 
            (symbol=? (ir-name ir) p))) 
    (filter1 eq-ir? aloir t))) 

An alternative arrangement places the local-expression where the function is needed:

;; find : list-of-IRs symbol -> boolean
(define (find aloir t) 
  (filter1 (local ((define (eq-ir? ir p) 
                     (symbol=? (ir-name ir) p))) 
             eq-ir?) 
           aloir t)) 
This alternative is feasible because the names of functions--like eq-ir?--are now legitimate expressions and can play the role of local's body. Thus the local-expression introduces a function definition and returns the function as its result. Because good programmers use abstract functions and organize their programs in a tidy manner, it is not surprising that Scheme provides a short-hand for this particular, frequent use of local. The short-hand is called a lambda-expression and greatly facilitates the introduction of functions like eq-ir?, squared?, or tex2html_wrap_inline72246 . The following two subsections introduce the syntax and semantics of lambda-expressions. The last subsection discusses its pragmatics.





PLT