PDA

View Full Version : Functions as Returned Values



danbaron
27-05-2011, 08:47
(Mostly taken from, "Structure and Interpretation of Computer Programs", p.72.)

For relatively very small values of dx, the derivative of a function, f(x), is defined as,

Df(x) = (f(x + dx) - f(x)) / dx.

Df(x), is the slope of the function, at the value x.

Using calculus, you can determine that, for instance, when f(x) equals x^3, then, Df(x) equals 3 * x^2.

So, when f(x) equals x^3, Df(x), when x equals 5, equals 3 * 5^2, equals 75.

It means that the slope of x^3, at x equals 5, is 75.

On the computer, we can get a numerical approximation to the derivative of a particular function, f(x), and for a particular value of x, by using the definition of Df(x), and no calculus.

Below, there are two definitions for the derivative.

The first one ("deriv-1") takes two parameters, a function to take the derivative of, and the value of x.

The second one ("deriv-2") takes one parameter, the function to take the derivative of. In it you can see the word, "lambda". All it means is that deriv-2 is going to return a function as its value. The function in the lambda definition is the function that is returned.

Notice, in the REPL interactions, the different parentheses structures for the two function calls.

For deriv-1, both cube and 5 are passed to it.

For deriv-2, only cube is passed to it, and an anonymous (unnamed) function is returned, and then applied to 5.

:idea:


' code ------------------------------------------------------------------------------------------------------------------------------------------

#lang racket

(define dx (expt 10.0 -10))

(define (cube x) (* x x x))

(define (deriv-1 f x)
(/ (- (f (+ x dx)) (f x)) dx))

(define (deriv-2 f)
(lambda (x)
(/ (- (f (+ x dx)) (f x)) dx)))

' REPL interactions -----------------------------------------------------------------------------------------------------------------------------

Welcome to DrRacket, version 5.1 [3m].
Language: racket.

> (deriv-1 cube 5)
75.000059496233

> ((deriv-2 cube) 5)
75.000059496233
>