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 22Designing Abstractions with First-Class FunctionsWe 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 FunctionsWhile 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 fis first, a primitive operation, so applying fto any argument always evaluates to first. Similarly, the body of gis f, so applying gto any argument always evaluates to f. Finally, depending on what kind of list we supply as an argument to h, it produces for 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 fto produce a function that contains one of f's arguments, fmust 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 addconsumes a number; after all, xis added to y. It then defines the function x-adderwith a local-expression. The body of the local-expression is x-adder, which means the result of addis x-adder. (1 of 13) [2/5/2008 4:50:50 PM]
has intentionally blurred sections.
Sign up to view the full version.