Higher-order Function - Example

Example

The following examples are not intended to compare and contrast programming languages, since each program performs a different task. Also, the idea of a "scripting language" is beyond the scope of this article.

This Python program contains the higher-order function g which takes a function as its first argument and returns a number. This example prints 100 ( g(f,7)= (7+3)×(7+3) ).

def f(x): return x + 3 def g(function, x): return function(x) * function(x) print g(f, 7)

This Haskell code is the equivalent of the Python program above.

f = (+3) g function x = function x * function x main = print $ g f 7

In this Scheme example the higher-order function g takes a number and returns a function. The function a takes a number and returns that number plus 7. (e.g. a(3)=10).

(define (g x) (lambda (y) (+ x y))) (define a (g 7)) (display (a 3))

In this Erlang example the higher-order function or_else/2 takes a list of functions (Fs) and argument (X). It evaluates the function F with the argument X as argument. If the function F returns false then the next function in Fs will be evaluated. If the function F returns {false,Y} then the next function in Fs with argument Y will be evaluated. If the function F returns R the higher-order function or_else/2 will return R. Note that X, Y and R can be functions. Example returns false.

or_else(, _) -> false; or_else(, X) -> or_else(Fs, X, F(X)). or_else(Fs, X, false) -> or_else(Fs, X); or_else(Fs, _, {false, Y}) -> or_else(Fs, Y); or_else(_, _, R) -> R. or_else(,3.23).

In this JavaScript example the higher-order function ArrayForEach takes an array and a method in as arguments and calls the method on every element in the array.

function ArrayForEach(array, func) { for(i = 0; i < array.length; i++) { if(i in array) { func(array); } } } function log(msg) { console.log(msg); } ArrayForEach(,log);

Read more about this topic:  Higher-order Function

Famous quotes containing the word example:

    Our intellect is not the most subtle, the most powerful, the most appropriate, instrument for revealing the truth. It is life that, little by little, example by example, permits us to see that what is most important to our heart, or to our mind, is learned not by reasoning but through other agencies. Then it is that the intellect, observing their superiority, abdicates its control to them upon reasoned grounds and agrees to become their collaborator and lackey.
    Marcel Proust (1871–1922)