Higher-order functionsTutorial (draft)Functions - Abstraction and application againHigher-order: two well-known examplesDocumentation and user's manualTable of contentsOCaml programs

Higher-order: two well-known examples

   
  

Function composition

First consider mathematics.

Recall that the function composition of two or more functions uses the output of one function as the input of another. For instance, f such that f(x)=cos(x2) is the composition of the cos function and the squaring function (here denoted by sq), which is usually written cos o sq.

Now consider Objective Caml:

let compose = function (g, f) -> (function x -> g (f (x)))

is a high-order function whose type is

('a -> 'b) * ('c -> 'a) -> ('c -> 'b)

Then

compose (cos, (function x -> x *. x))

represents the mathematical function cos o sq.

Its type is

float -> float

Here is an example of applying it:

(compose (cos, (function x -> x *. x))) (-4.3)

   
  

Derivation

Here numerical derivation is considerd rather than symbolic (also called formal) derivation.

A functional value that computes an approximate derivative of a function from real numbers to real numbers is bound to  deriv :

let deriv = function 
  f -> (function x -> let
                        dx = 1e-7
                      in
                        (f (x +. dx) -. f (x -. dx)) /. (2.0 *. dx))

The type of  deriv  is

(float -> float) -> (float -> float)

Here is an example of applying it. The result approximately represents the mathematical function cos:

let approx_cos = deriv (sin)

Applying  approx_cos  to the  float  value  0.  returns:

0.999999999999998335


Latest update : October 5, 2006
This document was translated from LaTeX by Hyperlatex 2.5, which is not the latest version of Hyperlatex.

Higher-order functionsTutorial (draft)Functions - Abstraction and application againHigher-order: two well-known examplesDocumentation and user's manualTable of contentsOCaml programs