Section 22

# How to Design Programs: An Introduction to Programming and Computing

This preview shows pages 1–3. Sign up to view the full content.

How to Design Programs: An Introduction to Computing and Programming [Go to first , previous , next page; contents ; index ] Section 22 Designing Abstractions with First-Class Functions We have seen that functions can consume functions and how important that is for creating single points of control in a function. But functions not only can consume functions, they can also produce them. More precisely, expressions in the new Scheme can evaluate to functions. Because the body of a function definition is also an expression, a function can produce a function. In this section, we first discuss this surprising idea and then show how it is useful for abstracting functions and in other contexts. 22.1 Functions that Produce Functions While the idea of producing a function may seem strange at first, it is extremely useful. Before we can discuss the usefulness of the idea, though, we must explore how a function can produce a function. Here are three examples: (define (f x) first) (define (g x) f) (define (h x) (cond ((empty? x) f) ((cons? x) g))) The body of f is first , a primitive operation, so applying f to any argument always evaluates to first . Similarly, the body of g is f , so applying g to any argument always evaluates to f . Finally, depending on what kind of list we supply as an argument to h , it produces f or g . None of these examples is useful but each illustrates the basic idea. In the first two cases, the body of the function definition is a function. In the last case, it evaluates to a function. The examples are useless because the results do not contain or refer to the argument. For a function f to produce a function that contains one of f 's arguments, f must define a function and return it as the result. That is, f 's body must be a local -expression. Recall that local -expressions group definitions and ask DrScheme to evaluate a single expression in the context of these definitions. They can occur wherever an expression can occur, which means the following definition is legal: (define (add x) (local ((define (x-adder y) (+ x y))) x-adder)) The function add consumes a number; after all, x is added to y . It then defines the function x-adder with a local - expression. The body of the local -expression is x-adder , which means the result of add is x-adder . file:///C|/Documents%20and%20Settings/Linda%20Graue...How%20to%20Design%20Programs/curriculum-Z-H-28.html (1 of 13) [2/5/2008 4:50:50 PM]

This preview has intentionally blurred sections. Sign up to view the full version.

View Full Document