Higher-order functions: Difference between revisions

Line 1,557:
 
{{FormulaeEntry|page=https://formulae.org/?script=examples/Higher-order_functions}}
 
'''Solution'''
 
'''Case 1 (from Rosetta code)''' Passing a function as an argument to another function.
 
The following function takes a function as its first parameter, and other two parameters, x and y. When this function "Do" is called, it will perform the given function taking as arguments the values x and y.
 
[[File:Fōrmulæ - Higher-order functions 01.png]]
 
[[File:Fōrmulæ - Higher-order functions 02.png]]
 
[[File:Fōrmulæ - Higher-order functions 03.png]]
 
An anonymous function (a lambda expression) can be passed directly:
 
[[File:Fōrmulæ - Higher-order functions 04.png]]
 
[[File:Fōrmulæ - Higher-order functions 05.png]]
 
For the next example, the function to be passed, when invoked, will perform several operation to the same two arguments. It will add them, subtract them, multiply them, divide them and power them. Finally it will return a list with the results.
 
[[File:Fōrmulæ - Higher-order functions 06.png]]
 
[[File:Fōrmulæ - Higher-order functions 07.png]]
 
Up now, however, it is the half of the story. Let us build an example where a function takes a function as parameter, and returns another function.
 
'''Case 2 (from Wikipedia)''' Passing a function as an argument to another function, and returning a function
 
The following function is a higher-order function. It takes as its unique parameter the function f. When the function is invoked, it will apply twice the function f and will return it. In other words, it will return a new function, which is the composition of the function f with itself.
 
[[File:Fōrmulæ - Higher-order functions 08.png]]
 
The next function is an ordinary one. It returns the values given as argument added with 3.
 
[[File:Fōrmulæ - Higher-order functions 09.png]]
 
In the next example, g is a dynamically created function.
 
[[File:Fōrmulæ - Higher-order functions 10.png]]
 
[[File:Fōrmulæ - Higher-order functions 11.png]]
 
Since the '''Apply twice''' returns a function, it can be immediately invoked:
 
[[File:Fōrmulæ - Higher-order functions 12.png]]
 
[[File:Fōrmulæ - Higher-order functions 11.png]]
 
=={{header|GAP}}==
2,120

edits