Higher-order functions: Difference between revisions
(Modula-3) |
m (Fixed lang tags.) |
||
Line 2: | Line 2: | ||
=={{header|ActionScript}}== |
=={{header|ActionScript}}== |
||
<lang actionscript> |
<lang actionscript>package { |
||
package { |
|||
public class MyClass { |
public class MyClass { |
||
Line 21: | Line 20: | ||
} |
} |
||
} |
} |
||
}</lang> |
|||
} |
|||
</lang> |
|||
=={{header|Ada}}== |
=={{header|Ada}}== |
||
===Simple Example=== |
===Simple Example=== |
||
<lang ada> |
<lang ada>with Ada.Text_Io; use Ada.Text_Io; |
||
with Ada.Text_Io; use Ada.Text_Io; |
|||
procedure Subprogram_As_Argument is |
|||
type Proc_Access is access procedure; |
|||
procedure Subprogram_As_Argument is |
|||
type Proc_Access is access procedure; |
|||
procedure Second is |
|||
begin |
|||
Put_Line("Second Procedure"); |
|||
end Second; |
|||
procedure Second is |
|||
begin |
|||
Put_Line("Second Procedure"); |
|||
end Second; |
|||
begin |
|||
First( |
procedure First(Proc : Proc_Access) is |
||
begin |
|||
end Subprogram_As_Argument; |
|||
Proc.all; |
|||
</lang> |
|||
end First; |
|||
begin |
|||
First(Second'Access); |
|||
end Subprogram_As_Argument;</lang> |
|||
===Complex Example=== |
===Complex Example=== |
||
<lang ada> |
<lang ada>with Ada.Text_Io; use Ada.Text_Io; |
||
with Ada.Text_Io; use Ada.Text_Io; |
|||
procedure Subprogram_As_Argument_2 is |
|||
procedure Subprogram_As_Argument_2 is |
|||
-- Definition of an access to long_float |
|||
-- Definition of an access to long_float |
|||
type Lf_Access is access Long_Float; |
|||
type Lf_Access is access Long_Float; |
|||
-- Definition of a function returning Lf_Access taking an |
|||
-- integer as a parameter |
|||
-- Definition of a function returning Lf_Access taking an |
|||
-- integer as a parameter |
|||
function Func_To_Be_Passed(Item : Integer) return Lf_Access is |
|||
Result : Lf_Access := new Long_Float; |
|||
function Func_To_Be_Passed(Item : Integer) return Lf_Access is |
|||
begin |
|||
Result : Lf_Access := new Long_Float; |
|||
Result.All := 3.14159 * Long_Float(Item); |
|||
begin |
|||
Result |
return Result; |
||
end Func_To_Be_Passed; |
|||
return Result; |
|||
end Func_To_Be_Passed; |
|||
-- Definition of an access to function type matching the function |
|||
-- signature above |
|||
-- Definition of an access to function type matching the function |
|||
-- signature above |
|||
type Func_Access is access function(Item : Integer) return Lf_Access; |
|||
type Func_Access is access function(Item : Integer) return Lf_Access; |
|||
-- Definition of an integer access type |
|||
-- Definition of an integer access type |
|||
type Int_Access is access Integer; |
|||
type Int_Access is access Integer; |
|||
-- Define a function taking an instance of Func_Access as its |
|||
-- parameter and returning an integer access type |
|||
-- Define a function taking an instance of Func_Access as its |
|||
-- parameter and returning an integer access type |
|||
function Complex_Func(Item : Func_Access; Parm2 : Integer) return Int_Access is |
|||
Result : Int_Access := new Integer; |
|||
begin |
|||
Result : Int_Access := new Integer; |
|||
Result.All := Integer(Item(Parm2).all / 3.14149); |
|||
begin |
|||
Result |
return Result; |
||
end Complex_Func; |
|||
end Complex_Func; |
|||
-- Declare an access variable to hold the access to the function |
|||
-- Declare an access variable to hold the access to the function |
|||
F_Ptr : Func_Access := Func_To_Be_Passed'access; |
|||
F_Ptr : Func_Access := Func_To_Be_Passed'access; |
|||
-- Declare an access to integer variable to hold the result |
|||
-- Declare an access to integer variable to hold the result |
|||
Int_Ptr : Int_Access; |
|||
Int_Ptr : Int_Access; |
|||
begin |
|||
begin |
|||
-- Call the function using the access variable |
|||
-- Call the function using the access variable |
|||
Int_Ptr := Complex_Func(F_Ptr, 3); |
|||
Put_Line(Integer'Image(Int_Ptr.All)); |
|||
Int_Ptr := Complex_Func(F_Ptr, 3); |
|||
end Subprogram_As_Argument_2;</lang> |
|||
Put_Line(Integer'Image(Int_Ptr.All)); |
|||
end Subprogram_As_Argument_2; |
|||
</lang> |
|||
=={{header|ALGOL 68}}== |
=={{header|ALGOL 68}}== |
||
<lang algol68>PROC first = (PROC(LONG REAL)LONG REAL f) LONG REAL: |
|||
( |
|||
f(1) + 2 |
|||
); |
|||
PROC second = (LONG REAL x)LONG REAL: |
|||
( |
|||
x/2 |
|||
); |
|||
main: ( |
|||
printf(($xg(5,2)l$,first(second))) |
|||
)</lang> |
|||
) |
|||
Output: |
Output: |
||
<lang algol68>+2.50</lang> |
|||
+2.50 |
|||
=={{header|AmigaE}}== |
=={{header|AmigaE}}== |
||
Line 133: | Line 127: | ||
ENDPROC</lang> |
ENDPROC</lang> |
||
=={{header|AutoHotkey}}== |
=={{header|AutoHotkey}}== |
||
<lang AutoHotkey> |
<lang AutoHotkey>func = round |
||
msgbox % %func%(4.5)</lang> |
|||
func = round |
|||
msgbox % %func%(4.5) </lang> |
|||
=={{header|C}}== |
=={{header|C}}== |
||
'''Simple example''' |
'''Simple example''' |
||
Line 143: | Line 136: | ||
Definition of a function whose only parameter is a pointer to a function with no parameters and no return value: |
Definition of a function whose only parameter is a pointer to a function with no parameters and no return value: |
||
<lang c> |
<lang c>void myFuncSimple( void (*funcParameter)(void) ) |
||
{ |
|||
/* ... */ |
|||
(*funcParameter)(); /* Call the passed function. */ |
|||
funcParameter(); /* Same as above with slight different syntax. */ |
|||
/* ... */ |
|||
}</lang> |
|||
Note that you ''can't'' call the passed function by " *funcParameter() ", since that would mean "call funcParameter and than apply the * operator on the returned value". |
Note that you ''can't'' call the passed function by " *funcParameter() ", since that would mean "call funcParameter and than apply the * operator on the returned value". |
||
Line 157: | Line 150: | ||
Call: |
Call: |
||
<lang c> |
<lang c>void funcToBePassed(void); |
||
/* ... */ |
|||
myFuncSimple(&funcToBePassed);</lang> |
|||
'''Complex example''' |
'''Complex example''' |
||
Line 167: | Line 160: | ||
Definition of a function whose return value is a pointer to int and whose only parameter is a pointer to a function, whose (in turn) return value is a pointer to double and whose only parameter is a pointer to long. |
Definition of a function whose return value is a pointer to int and whose only parameter is a pointer to a function, whose (in turn) return value is a pointer to double and whose only parameter is a pointer to long. |
||
<lang c> |
<lang c>int* myFuncComplex( double* (*funcParameter)(long* parameter) ) |
||
{ |
|||
long* inLong; |
|||
double* outDouble; |
|||
/* ... */ |
|||
outDouble = (*funcParameter)(inLong); /* Call the passed function and store returned pointer. */ |
|||
outDouble = funcParameter(inLong); /* Same as above with slight different syntax. */ |
|||
/* ... */ |
|||
}</lang> |
|||
Call: |
Call: |
||
<lang c> |
<lang c>double* funcToBePassed(long* parameter); |
||
/* ... */ |
|||
int* outInt; |
|||
outInt = myFuncComplex(&funcToBePassed);</lang> |
|||
'''Pointer''' |
'''Pointer''' |
||
Line 193: | Line 186: | ||
Finally, declaration of a pointer variable of the proper type to hold such a function as myFunc: |
Finally, declaration of a pointer variable of the proper type to hold such a function as myFunc: |
||
<lang c> |
<lang c>int* (*funcPointer)( double* (*funcParameter)(long* parameter) ); |
||
/* ... */ |
|||
funcPointer = myFuncComplex;</lang> |
|||
Of course, in a real project you shouldn't write such a convoluted code, but use some typedef instead, in order to break complexity into steps. |
Of course, in a real project you shouldn't write such a convoluted code, but use some typedef instead, in order to break complexity into steps. |
||
Line 213: | Line 206: | ||
{{works with|Visual C++|2005}} |
{{works with|Visual C++|2005}} |
||
<lang cpp> |
<lang cpp>#include <iostream> |
||
template<class Func> |
|||
void first(Func func) |
|||
{ |
|||
func(); |
|||
} |
|||
void second() |
|||
{ |
|||
std::cout << "second" << std::endl; |
|||
} |
|||
int main() |
|||
{ |
|||
first(second); |
|||
return 0; |
|||
}</lang> |
|||
===Template and Inheritance=== |
===Template and Inheritance=== |
||
Line 236: | Line 229: | ||
{{works with|Visual C++|2005}} |
{{works with|Visual C++|2005}} |
||
<lang cpp> |
<lang cpp>#include <iostream> |
||
#include <functional> |
|||
template<class Func> |
|||
typename Func::result_type first(Func func, typename Func::argument_type arg) |
|||
{ |
|||
return func(arg); |
|||
} |
|||
class second : public std::unary_function<int, int> |
|||
{ |
|||
public: |
|||
result_type operator()(argument_type arg) |
|||
{ |
{ |
||
return |
return arg * arg; |
||
} |
} |
||
}; |
|||
class second : public std::unary_function<int, int> |
|||
int main() |
|||
{ |
|||
{ |
|||
public: |
|||
std::cout << first(second(), 2) << std::endl; |
|||
result_type operator()(argument_type arg) |
|||
return 0; |
|||
}</lang> |
|||
return arg * arg; |
|||
} |
|||
}; |
|||
int main() |
|||
{ |
|||
std::cout << first(second(), 2) << std::endl; |
|||
return 0; |
|||
}</lang> |
|||
=={{header|Clean}}== |
=={{header|Clean}}== |
||
Take a function as an argument and apply it to all elements in a list: |
Take a function as an argument and apply it to all elements in a list: |
||
<lang clean>map f [x:xs] = [f x:map f xs] |
|||
map f [] = []</lang> |
|||
Pass a function as an argument: |
Pass a function as an argument: |
||
<lang clean>incr x = x + 1 |
|||
Start = map incr [1..10]</lang> |
|||
Do the same using a anonymous function: |
Do the same using a anonymous function: |
||
<lang clean>Start = map (\x -> x + 1) [1..10]</lang> |
|||
Do the same using currying: |
Do the same using currying: |
||
<lang clean>Start = map ((+) 1) [1..10]</lang> |
|||
=={{header|Groovy}}== |
=={{header|Groovy}}== |
||
As [[closures]]: |
As [[closures]]: |
||
<lang groovy>first = { func -> func() } |
|||
second = { println "second" } |
|||
first(second)</lang> |
|||
As functions: |
As functions: |
||
<lang groovy>def first(func) { func() } |
|||
def second() { println "second" } |
|||
first(this.&second)</lang> |
|||
=={{header|Common Lisp}}== |
=={{header|Common Lisp}}== |
||
In Common Lisp, functions are [http://en.wikipedia.org/wiki/First-class_object first class objects], so you can pass function objects as arguments to other functions: |
In Common Lisp, functions are [http://en.wikipedia.org/wiki/First-class_object first class objects], so you can pass function objects as arguments to other functions: |
||
<lang lisp>CL-USER> (defun add (a b) (+ a b)) |
|||
ADD |
|||
CL-USER> (add 1 2) |
|||
3 |
|||
CL-USER> (defun call-it (fn x y) |
|||
(funcall fn x y)) |
|||
CALL-IT |
|||
CL-USER> (call-it #'add 1 2) |
|||
3</lang> |
|||
3 |
|||
=={{header|D}}== |
=={{header|D}}== |
||
Line 362: | Line 355: | ||
=={{header|E}}== |
=={{header|E}}== |
||
<lang e>def map(f, list) { |
|||
var out := [] |
|||
for x in list { |
|||
out with= f(x) |
|||
} |
|||
return out |
|||
} |
|||
? map(fn x { x + x }, [1, "two"]) |
|||
# value: [2, "twotwo"] |
|||
? map(1.add, [5, 10, 20]) |
|||
# value: [6, 11, 21] |
|||
? def foo(x) { return -(x.size()) } |
|||
> map(foo, ["", "a", "bc"]) |
|||
# value: [0, -1, -2]</lang> |
|||
=={{header|Erlang}}== |
=={{header|Erlang}}== |
||
Erlang functions are atoms, and they're considered different functions if their arity (the number of arguments they take) is different. As such, an Erlang function must be passed as <code>fun Function/Arity</code>, but can be used as any other variable: |
Erlang functions are atoms, and they're considered different functions if their arity (the number of arguments they take) is different. As such, an Erlang function must be passed as <code>fun Function/Arity</code>, but can be used as any other variable: |
||
<lang erlang> |
<lang erlang>-module(test). |
||
-module(test). |
|||
-export([first/1, second/0]). |
-export([first/1, second/0]). |
||
first(F) -> F(). |
first(F) -> F(). |
||
second() -> hello. |
second() -> hello.</lang> |
||
</lang> |
|||
Testing it: |
Testing it: |
||
<lang erlang> |
<lang erlang>1> c(tests). |
||
1> c(tests). |
|||
{ok, tests} |
{ok, tests} |
||
2> tests:first(fun tests:second/0). |
2> tests:first(fun tests:second/0). |
||
hello |
hello |
||
3> tests:first(fun() -> anonymous_function end). |
3> tests:first(fun() -> anonymous_function end). |
||
anonymous_function |
anonymous_function</lang> |
||
</lang> |
|||
=={{header|FALSE}}== |
=={{header|FALSE}}== |
||
Anonymous code blocks are the basis of FALSE control flow and function definition. These blocks may be passed on the stack as with any other parameter. |
Anonymous code blocks are the basis of FALSE control flow and function definition. These blocks may be passed on the stack as with any other parameter. |
||
<lang false>[f:[$0>][@@\f;!\1-]#%]r: { reduce n stack items using the given basis and binary function } |
|||
1 2 3 4 0 4[+]r;!." " { 10 } |
|||
1 2 3 4 1 4[*]r;!." " { 24 } |
|||
1 2 3 4 0 4[$*+]r;!. { 30 }</lang> |
|||
=={{header|Forth}}== |
=={{header|Forth}}== |
||
Forth words can be referenced on the stack via their ''execution token'' or XT. An XT is obtained from a word via the quote operator, and invoked via '''EXECUTE'''. Anonymous functions may be defined via ''':NONAME''' (returning an XT) instead of a standard colon definition. |
Forth words can be referenced on the stack via their ''execution token'' or XT. An XT is obtained from a word via the quote operator, and invoked via '''EXECUTE'''. Anonymous functions may be defined via ''':NONAME''' (returning an XT) instead of a standard colon definition. |
||
<lang forth>: square dup * ; |
|||
: cube dup dup * * ; |
|||
: map. ( xt addr len -- ) |
|||
0 do 2dup i cells + @ swap execute . loop 2drop ; |
|||
create array 1 , 2 , 3 , 4 , 5 , |
|||
' square array 5 map. cr \ 1 4 9 16 25 |
|||
' cube array 5 map. cr \ 1 8 27 64 125 |
|||
:noname 2* 1+ ; array 5 map. cr \ 3 5 7 9 11</lang> |
|||
=={{header|Fortran}}== |
=={{header|Fortran}}== |
||
{{works with|Fortran|90 and later}} |
{{works with|Fortran|90 and later}} |
||
use the EXTERNAL attribute to show the dummy argument is another function rather than a data object. i.e. |
use the EXTERNAL attribute to show the dummy argument is another function rather than a data object. i.e. |
||
<lang fortran> |
<lang fortran>FUNCTION FUNC3(FUNC1, FUNC2, x, y) |
||
REAL, EXTERNAL :: FUNC1, FUNC2 |
|||
REAL :: FUNC3 |
|||
REAL :: x, y |
|||
FUNC3 = FUNC1(x) * FUNC2(y) |
|||
END FUNCTION FUNC3</lang> |
|||
Another way is to put the functions you want to pass in a module: |
Another way is to put the functions you want to pass in a module: |
||
Line 489: | Line 478: | ||
A function is just a value that wants arguments: |
A function is just a value that wants arguments: |
||
<lang haskell>func1 f = f "a string" |
|||
func2 s = "func2 called with " ++ s |
|||
main = putStrLn $ func1 func2</lang> |
|||
Or, with an anonymous function: |
Or, with an anonymous function: |
||
<lang haskell>func f = f 1 2 |
|||
main = print $ func (\x y -> x+y) |
|||
-- output: 3</lang> |
|||
Note that <tt>func (\x y -> x+y)</tt> is equivalent to <tt>func (+)</tt>. (Operators are functions too.) |
Note that <tt>func (\x y -> x+y)</tt> is equivalent to <tt>func (+)</tt>. (Operators are functions too.) |
||
=={{header|Icon}}== |
=={{header|Icon}}== |
||
procedure main() |
<lang icon> procedure main() |
||
local lst |
|||
lst := [10, 20, 30, 40] |
|||
myfun(callback, lst) |
|||
end |
|||
procedure myfun(fun, lst) |
|||
every fun(!lst) |
|||
end |
|||
procedure callback(arg) |
|||
write("->", arg) |
|||
end</lang> |
|||
=={{header|J}}== |
=={{header|J}}== |
||
Line 519: | Line 508: | ||
''Adverbs'' take a single verb or noun argument and ''conjunctions'' take two. For example,<tt> / </tt>(insert)<tt> \ </tt>(prefix) and<tt> \. </tt>(suffix) are adverbs and<tt> ^: </tt>(power) is a conjunction. The following expressions illustrate their workings. |
''Adverbs'' take a single verb or noun argument and ''conjunctions'' take two. For example,<tt> / </tt>(insert)<tt> \ </tt>(prefix) and<tt> \. </tt>(suffix) are adverbs and<tt> ^: </tt>(power) is a conjunction. The following expressions illustrate their workings. |
||
+ / 3 1 4 1 5 9 NB. sum |
<lang j> + / 3 1 4 1 5 9 NB. sum |
||
23 |
|||
>./ 3 1 4 1 5 9 NB. max |
|||
9 |
|||
*./ 3 1 4 1 5 9 NB. lcm |
|||
180 |
|||
+/\ 3 1 4 1 5 9 NB. sum prefix (partial sums) |
|||
3 4 8 9 14 23 |
|||
+/\. 3 1 4 1 5 9 NB. sum suffix |
|||
23 20 19 15 14 9 |
|||
f=: -:@(+ 2&%) NB. one Newton iteration |
|||
f 1 |
|||
1.5 |
|||
f f 1 |
|||
1.41667 |
|||
f^:(i.5) 1 NB. first 5 Newton iterations |
|||
1 1.5 1.41667 1.41422 1.41421 |
|||
f^:(i.5) 1x NB. rational approximations to sqrt 2 |
|||
1 3r2 17r12 577r408 665857r470832</lang> |
|||
=={{header|Java}}== |
=={{header|Java}}== |
||
Line 547: | Line 536: | ||
There is no real callback in Java like in C or C++, but we can do the same as swing does for executing an event. We need to create an interface that has the method we want to call or create one that will call the method we want to call. The following example uses the second way. |
There is no real callback in Java like in C or C++, but we can do the same as swing does for executing an event. We need to create an interface that has the method we want to call or create one that will call the method we want to call. The following example uses the second way. |
||
<lang java> |
<lang java>public class NewClass { |
||
public NewClass() { |
|||
first(new AnEventOrCallback() { |
|||
public void call() { |
|||
second(); |
|||
} |
|||
}); |
|||
} |
|||
public void first(AnEventOrCallback obj) { |
|||
obj.call(); |
|||
} |
|||
public void second() { |
|||
System.out.println("Second"); |
|||
} |
|||
public static void main(String[] args) { |
|||
new NewClass(); |
|||
} |
|||
} |
|||
interface AnEventOrCallback { |
|||
public void call(); |
|||
}</lang> |
|||
=={{header|JavaScript}}== |
=={{header|JavaScript}}== |
||
Line 622: | Line 611: | ||
This example is taken from V. |
This example is taken from V. |
||
Define first as multiplying two numbers on the stack. |
Define first as multiplying two numbers on the stack. |
||
<lang joy> |
<lang joy>DEFINE first == *.</lang> |
||
DEFINE first == *. |
|||
</lang> |
|||
There will be a warning about overwriting builtin first. |
There will be a warning about overwriting builtin first. |
||
Define second as interpreting the passed quotation on the stack. |
Define second as interpreting the passed quotation on the stack. |
||
<lang joy> |
<lang joy>DEFINE second == i.</lang> |
||
DEFINE second == i. |
|||
</lang> |
|||
Pass first enclosed in quotes to second which applies it on the stack. |
Pass first enclosed in quotes to second which applies it on the stack. |
||
<lang joy> |
<lang joy>2 3 [first] second.</lang> |
||
2 3 [first] second. |
|||
</lang> |
|||
The program prints 6. |
The program prints 6. |
||
=={{header|Logo}}== |
=={{header|Logo}}== |
||
You can pass the quoted symbol for the function and invoke it with RUN. |
You can pass the quoted symbol for the function and invoke it with RUN. |
||
<lang logo>to printstuff |
|||
print "stuff |
|||
end |
|||
to runstuff :proc |
|||
run :proc |
|||
end |
|||
runstuff "printstuff ; stuff |
|||
runstuff [print [also stuff]] ; also stuff</lang> |
|||
=={{header|Mathematica}}== |
=={{header|Mathematica}}== |
||
Passing 3 arguments and a value (could be a number, variable, graphic or a function as well, actually it could be ''anything''), and composing them in an unusual way: |
Passing 3 arguments and a value (could be a number, variable, graphic or a function as well, actually it could be ''anything''), and composing them in an unusual way: |
||
<lang Mathematica> |
<lang Mathematica>PassFunc[f_, g_, h_, x_] := f[g[x]*h[x]] |
||
PassFunc[Tan, Cos, Sin, x] |
|||
% /. x -> 0.12 |
|||
PassFunc[Tan, Cos, Sin, x] |
|||
PassFunc[Tan, Cos, Sin, 0.12]</lang> |
|||
% /. x -> 0.12 |
|||
PassFunc[Tan, Cos, Sin, 0.12] |
|||
</lang> |
|||
gives back: |
gives back: |
||
<lang Mathematica> |
<lang Mathematica>Tan[Cos[x] Sin[x]] |
||
0.119414 |
|||
Tan[Cos[x] Sin[x]] |
|||
0.119414</lang> |
|||
0.119414 |
|||
</lang> |
|||
=={{header|MAXScript}}== |
=={{header|MAXScript}}== |
||
<lang maxscript>fn second = |
|||
( |
|||
print "Second" |
|||
) |
|||
fn first func = |
|||
( |
|||
func() |
|||
) |
|||
first second</lang> |
|||
=={{header|Metafont}}== |
=={{header|Metafont}}== |
||
Line 709: | Line 688: | ||
A function is just a value that wants arguments: |
A function is just a value that wants arguments: |
||
<lang ocaml> |
<lang ocaml># let func1 f = f "a string";; |
||
# let func1 f = f "a string";; |
|||
val func1 : (string -> 'a) -> 'a = <fun> |
val func1 : (string -> 'a) -> 'a = <fun> |
||
# let func2 s = "func2 called with " ^ s;; |
# let func2 s = "func2 called with " ^ s;; |
||
Line 717: | Line 695: | ||
# print_endline (func1 func2);; |
# print_endline (func1 func2);; |
||
func2 called with a string |
func2 called with a string |
||
- : unit = () |
- : unit = ()</lang> |
||
</lang> |
|||
Or, with an anonymous function: |
Or, with an anonymous function: |
||
<lang ocaml> |
<lang ocaml># let func f = f 1 2;; |
||
# let func f = f 1 2;; |
|||
val func : (int -> int -> 'a) -> 'a = <fun> |
val func : (int -> int -> 'a) -> 'a = <fun> |
||
# Printf.printf "%d\n" (func (fun x y -> x + y));; |
# Printf.printf "%d\n" (func (fun x y -> x + y));; |
||
3 |
3 |
||
- : unit = () |
- : unit = ()</lang> |
||
</lang> |
|||
Note that <tt>func (fun x y -> x + y)</tt> is equivalent to <tt>func (+)</tt>. (Operators are functions too.) |
Note that <tt>func (fun x y -> x + y)</tt> is equivalent to <tt>func (+)</tt>. (Operators are functions too.) |
||
Line 752: | Line 727: | ||
=={{header|Pascal}}== |
=={{header|Pascal}}== |
||
Standard Pascal (will not work with Turbo Pascal): |
Standard Pascal (will not work with Turbo Pascal): |
||
<lang pascal> |
<lang pascal>program example(output); |
||
function first(function f(x: real): real): real; |
|||
begin |
|||
first := f(1.0) + 2.0; |
|||
end; |
|||
function second(x: real): real; |
|||
begin |
|||
second := x/2.0; |
|||
end; |
|||
begin |
begin |
||
first := f(1.0) + 2.0; |
|||
end |
end; |
||
function second(x: real): real; |
|||
begin |
|||
second := x/2.0; |
|||
end; |
|||
begin |
|||
writeln(first(second)); |
|||
end.</lang> |
|||
[[Turbo Pascal]] (will not work with Standard Pascal): |
[[Turbo Pascal]] (will not work with Standard Pascal): |
||
<lang pascal> |
<lang pascal>program example; |
||
type |
|||
FnType = function(x: real): real; |
|||
function first(f: FnType): real; |
|||
begin |
|||
first := f(1.0) + 2.0; |
|||
end; |
|||
function second(x: real): real; |
|||
begin |
|||
second := x/2.0; |
|||
end; |
|||
begin |
begin |
||
first := f(1.0) + 2.0; |
|||
end |
end; |
||
function second(x: real): real; |
|||
begin |
|||
second := x/2.0; |
|||
end; |
|||
begin |
|||
writeln(first(second)); |
|||
end.</lang> |
|||
=={{header|Perl}}== |
=={{header|Perl}}== |
||
<lang perl> |
<lang perl>sub another { |
||
# take a function and a value |
|||
my $func = shift; |
|||
my $val = shift; |
|||
# call the function with the value as argument |
|||
return $func->($val); |
|||
}; |
|||
sub reverser { |
|||
return scalar reverse shift; |
|||
}; |
|||
# pass named coderef |
|||
print another \&reverser, 'data'; |
|||
# pass anonymous coderef |
|||
print another sub {return scalar reverse shift}, 'data'; |
|||
# if all you have is a string and you want to act on that, |
|||
# set up a dispatch table |
|||
my %dispatch = ( |
|||
square => sub {return shift() ** 2}, |
|||
cube => sub {return shift() ** 3}, |
|||
rev => \&reverser, |
|||
); |
|||
print another $dispatch{$_}, 123 for qw(square cube rev);</lang> |
|||
<lang perl>sub apply (&@) { # use & as the first item in a prototype to take bare blocks like map and grep |
<lang perl>sub apply (&@) { # use & as the first item in a prototype to take bare blocks like map and grep |
||
Line 839: | Line 814: | ||
=={{header|PHP}}== |
=={{header|PHP}}== |
||
<lang php> |
<lang php>function first($func) { |
||
return $func(); |
|||
} |
|||
function second() { |
|||
return 'second'; |
|||
} |
|||
$result = first('second');</lang> |
|||
=={{header|Pop11}}== |
=={{header|Pop11}}== |
||
<lang pop11>;;; Define a function |
|||
define x_times_three_minus_1(x); |
|||
return(3*x-1); |
|||
enddefine; |
|||
;;; Pass it as argument to built-in function map and print the result |
|||
mapdata({0 1 2 3 4}, x_times_three_minus_1) =></lang> |
|||
Line 862: | Line 837: | ||
{{works with|Python|2.5}} |
{{works with|Python|2.5}} |
||
<lang python> |
<lang python>def first(function): |
||
return function() |
|||
def second(): |
|||
return "second" |
|||
result = first(second)</lang> |
|||
or |
or |
||
Line 886: | Line 861: | ||
=={{header|Ruby}}== |
=={{header|Ruby}}== |
||
With a proc (procedure): |
With a proc (procedure): |
||
<lang ruby> |
<lang ruby>succ = proc{|x| x+1} |
||
def to2(&f) |
|||
f[2] |
|||
end |
|||
to2(&succ) #=> 3 |
|||
to2{|x| x+1} #=> 3</lang> |
|||
With a method: |
With a method: |
||
<lang ruby> |
<lang ruby>def succ(n) |
||
n+1 |
|||
end |
|||
def to2(m) |
|||
m[2] |
|||
end |
|||
meth = method(:succ) |
|||
to2(meth) #=> 3</lang> |
|||
=={{header|Scala}}== |
=={{header|Scala}}== |
||
<lang scala>def functionWithAFunctionArgument(x : int, y : int, f : (int, int) => int) = f(x,y)</lang> |
|||
Call: |
Call: |
||
<lang scala>functionWithAFunctionArgument(3, 5, {(x, y) => x + y}) // returns 8</lang> |
|||
=={{header|Scheme}}== |
=={{header|Scheme}}== |
||
A function is just a value that wants arguments: |
A function is just a value that wants arguments: |
||
<lang scheme> |
<lang scheme>> (define (func1 f) (f "a string")) |
||
> (define (func1 f) (f "a string")) |
|||
> (define (func2 s) (string-append "func2 called with " s)) |
> (define (func2 s) (string-append "func2 called with " s)) |
||
> (begin (display (func1 func2)) (newline)) |
> (begin (display (func1 func2)) (newline)) |
||
func2 called with a string |
func2 called with a string</lang> |
||
</lang> |
|||
Or, with an anonymous function: |
Or, with an anonymous function: |
||
<lang scheme> |
<lang scheme>> (define (func f) (f 1 2)) |
||
> (define (func f) (f 1 2)) |
|||
> (begin (display (func (lambda (x y) (+ x y)))) (newline)) |
> (begin (display (func (lambda (x y) (+ x y)))) (newline)) |
||
3</lang> |
|||
3 |
|||
</lang> |
|||
Note that <tt>(func (lambda (x y) (+ x y)))</tt> is equivalent to <tt>(func +)</tt>. (Operators are functions too.) |
Note that <tt>(func (lambda (x y) (+ x y)))</tt> is equivalent to <tt>(func +)</tt>. (Operators are functions too.) |
||
=={{header|Slate}}== |
=={{header|Slate}}== |
||
Methods and blocks can both be passed as arguments to functions (other methods and blocks): |
Methods and blocks can both be passed as arguments to functions (other methods and blocks): |
||
<lang slate> |
<lang slate>define: #function -> [| :x | x * 3 - 1]. |
||
#(1 1 2 3 5 8) collect: function.</lang> |
|||
define: #function -> [| :x | x * 3 - 1]. |
|||
#(1 1 2 3 5 8) collect: function. |
|||
</lang> |
|||
=={{header|Standard ML}}== |
=={{header|Standard ML}}== |
||
<lang sml> |
<lang sml>- fun func1 f = f "a string"; |
||
- fun func1 f = f "a string"; |
|||
val func1 = fn : (string -> 'a) -> 'a |
val func1 = fn : (string -> 'a) -> 'a |
||
- fun func2 s = "func2 called with " ^ s; |
- fun func2 s = "func2 called with " ^ s; |
||
Line 945: | Line 913: | ||
- print (func1 func2 ^ "\n"); |
- print (func1 func2 ^ "\n"); |
||
func2 called with a string |
func2 called with a string |
||
val it = () : unit |
val it = () : unit</lang> |
||
</lang> |
|||
Or, with an anonymous function: |
Or, with an anonymous function: |
||
<lang sml> |
<lang sml>- fun func f = f (1, 2); |
||
- fun func f = f (1, 2); |
|||
val func = fn : (int * int -> 'a) -> 'a |
val func = fn : (int * int -> 'a) -> 'a |
||
- print (Int.toString (func (fn (x, y) => x + y)) ^ "\n"); |
- print (Int.toString (func (fn (x, y) => x + y)) ^ "\n"); |
||
3 |
3 |
||
val it = () : unit |
val it = () : unit</lang> |
||
</lang> |
|||
Note that <tt>func (fn (x, y) => x + y)</tt> is equivalent to <tt>func op+</tt>. (Operators are functions too.) |
Note that <tt>func (fn (x, y) => x + y)</tt> is equivalent to <tt>func op+</tt>. (Operators are functions too.) |
||
Line 993: | Line 958: | ||
The function name passed cannot be that of a local function, because the local function <code>map</code> does not see the local variables of the enclosing function. |
The function name passed cannot be that of a local function, because the local function <code>map</code> does not see the local variables of the enclosing function. |
||
< |
<lang ti89b>Local map |
||
Define map(f,l)=Func |
Define map(f,l)=Func |
||
Return seq(#f(l[i]),i,1,dim(l)) |
Return seq(#f(l[i]),i,1,dim(l)) |
||
EndFunc |
EndFunc |
||
Disp map("sin", {0, π/6, π/4, π/3, π/2}) |
Disp map("sin", {0, π/6, π/4, π/3, π/2})</lang> |
||
</pre> |
|||
=={{header|Toka}}== |
=={{header|Toka}}== |
||
Toka allows obtaining a function pointer via the '''`''' (''backtick'') word. The pointers are passed on the stack, just like all other data. |
Toka allows obtaining a function pointer via the '''`''' (''backtick'') word. The pointers are passed on the stack, just like all other data. |
||
<lang toka>[ ." First\n" ] is first |
|||
[ invoke ] is second |
|||
` first second</lang> |
|||
=={{header|Ursala}}== |
=={{header|Ursala}}== |
||
Line 1,025: | Line 989: | ||
=={{header|V}}== |
=={{header|V}}== |
||
Define first as multiplying two numbers on stack |
Define first as multiplying two numbers on stack |
||
<lang v>[first *].</lang> |
|||
Define second as applying the passed quote on stack |
Define second as applying the passed quote on stack |
||
<lang v>[second i].</lang> |
|||
Pass the first enclosed in quote to second which applies it on stack. |
Pass the first enclosed in quote to second which applies it on stack. |
||
<lang v>2 3 [first] second</lang> |
|||
=6 |
=6 |
Revision as of 15:08, 20 November 2009
You are encouraged to solve this task according to the task description, using any language you may know.
Pass a function as an argument to another function.
ActionScript
<lang actionscript>package {
public class MyClass {
public function first(func:Function):String { return func.call(); } public function second():String { return "second"; } public static function main():void { var result:String = first(second); trace(result); result = first(function() { return "third"; }); trace(result); } }
}</lang>
Ada
Simple Example
<lang ada>with Ada.Text_Io; use Ada.Text_Io;
procedure Subprogram_As_Argument is
type Proc_Access is access procedure; procedure Second is begin Put_Line("Second Procedure"); end Second; procedure First(Proc : Proc_Access) is begin Proc.all; end First;
begin
First(Second'Access);
end Subprogram_As_Argument;</lang>
Complex Example
<lang ada>with Ada.Text_Io; use Ada.Text_Io;
procedure Subprogram_As_Argument_2 is
-- Definition of an access to long_float
type Lf_Access is access Long_Float; -- Definition of a function returning Lf_Access taking an -- integer as a parameter
function Func_To_Be_Passed(Item : Integer) return Lf_Access is Result : Lf_Access := new Long_Float; begin Result.All := 3.14159 * Long_Float(Item); return Result; end Func_To_Be_Passed; -- Definition of an access to function type matching the function -- signature above
type Func_Access is access function(Item : Integer) return Lf_Access; -- Definition of an integer access type
type Int_Access is access Integer; -- Define a function taking an instance of Func_Access as its -- parameter and returning an integer access type
function Complex_Func(Item : Func_Access; Parm2 : Integer) return Int_Access is Result : Int_Access := new Integer; begin Result.All := Integer(Item(Parm2).all / 3.14149); return Result; end Complex_Func; -- Declare an access variable to hold the access to the function
F_Ptr : Func_Access := Func_To_Be_Passed'access; -- Declare an access to integer variable to hold the result
Int_Ptr : Int_Access;
begin
-- Call the function using the access variable
Int_Ptr := Complex_Func(F_Ptr, 3); Put_Line(Integer'Image(Int_Ptr.All));
end Subprogram_As_Argument_2;</lang>
ALGOL 68
<lang algol68>PROC first = (PROC(LONG REAL)LONG REAL f) LONG REAL: (
f(1) + 2
);
PROC second = (LONG REAL x)LONG REAL: (
x/2
);
main: (
printf(($xg(5,2)l$,first(second)))
)</lang> Output: <lang algol68>+2.50</lang>
AmigaE
The {} takes the pointer to an object (code/functions, variables and so on); Amiga E does not distinguish nor check anything, so it is up to the programmer to use the pointer properly. For this reason, a warning is always raised when a variable (func, holding a pointer to a real function in our case) is used like a function. <lang amigae>PROC compute(func, val)
DEF s[10] : STRING WriteF('\s\n', RealF(s,func(val),4))
ENDPROC
PROC sin_wrap(val) IS Fsin(val) PROC cos_wrap(val) IS Fcos(val)
PROC main()
compute({sin_wrap}, 0.0) compute({cos_wrap}, 3.1415)
ENDPROC</lang>
AutoHotkey
<lang AutoHotkey>func = round msgbox % %func%(4.5)</lang>
C
Simple example
The pointer to the function to be passed as an argument is the only involved pointer.
Definition of a function whose only parameter is a pointer to a function with no parameters and no return value:
<lang c>void myFuncSimple( void (*funcParameter)(void) ) {
/* ... */ (*funcParameter)(); /* Call the passed function. */ funcParameter(); /* Same as above with slight different syntax. */
/* ... */
}</lang>
Note that you can't call the passed function by " *funcParameter() ", since that would mean "call funcParameter and than apply the * operator on the returned value".
Call:
<lang c>void funcToBePassed(void);
/* ... */
myFuncSimple(&funcToBePassed);</lang>
Complex example
Definition of a function whose return value is a pointer to int and whose only parameter is a pointer to a function, whose (in turn) return value is a pointer to double and whose only parameter is a pointer to long.
<lang c>int* myFuncComplex( double* (*funcParameter)(long* parameter) ) {
long* inLong; double* outDouble;
/* ... */
outDouble = (*funcParameter)(inLong); /* Call the passed function and store returned pointer. */ outDouble = funcParameter(inLong); /* Same as above with slight different syntax. */
/* ... */
}</lang> Call:
<lang c>double* funcToBePassed(long* parameter);
/* ... */
int* outInt;
outInt = myFuncComplex(&funcToBePassed);</lang>
Pointer
Finally, declaration of a pointer variable of the proper type to hold such a function as myFunc:
<lang c>int* (*funcPointer)( double* (*funcParameter)(long* parameter) );
/* ... */
funcPointer = myFuncComplex;</lang>
Of course, in a real project you shouldn't write such a convoluted code, but use some typedef instead, in order to break complexity into steps.
C++
Function Pointer
Same as C.
Template
<lang cpp>#include <iostream>
template<class Func> void first(Func func) {
func();
}
void second() {
std::cout << "second" << std::endl;
}
int main() {
first(second); return 0;
}</lang>
Template and Inheritance
<lang cpp>#include <iostream>
- include <functional>
template<class Func> typename Func::result_type first(Func func, typename Func::argument_type arg) {
return func(arg);
}
class second : public std::unary_function<int, int> { public:
result_type operator()(argument_type arg) { return arg * arg; }
};
int main() {
std::cout << first(second(), 2) << std::endl; return 0;
}</lang>
Clean
Take a function as an argument and apply it to all elements in a list: <lang clean>map f [x:xs] = [f x:map f xs] map f [] = []</lang> Pass a function as an argument: <lang clean>incr x = x + 1
Start = map incr [1..10]</lang> Do the same using a anonymous function: <lang clean>Start = map (\x -> x + 1) [1..10]</lang> Do the same using currying: <lang clean>Start = map ((+) 1) [1..10]</lang>
Groovy
As closures: <lang groovy>first = { func -> func() } second = { println "second" }
first(second)</lang>
As functions: <lang groovy>def first(func) { func() } def second() { println "second" }
first(this.&second)</lang>
Common Lisp
In Common Lisp, functions are first class objects, so you can pass function objects as arguments to other functions:
<lang lisp>CL-USER> (defun add (a b) (+ a b)) ADD CL-USER> (add 1 2) 3 CL-USER> (defun call-it (fn x y)
(funcall fn x y))
CALL-IT CL-USER> (call-it #'add 1 2) 3</lang>
D
D's function/delegate will be investigated by passing each type of function/delegate to _test_ as argument. <lang d>module functest ; import std.stdio ;
// test the function argument string test(U)(string scopes, U func) {
string typeStr = typeid(typeof(func)).toString ; string isFunc = (typeStr[$-1] == '*') ? "function" : "delegate" ; writefln("Hi, %-13s : scope: %-8s (%s) : %s", func(), scopes, isFunc, typeStr ) ; return scopes ;
}
// normal module level function string aFunction(){ return "Function" ; }
// In-Function-Template-Instantiation(IFTI) Function T tmpFunc(T)() { return "IFTI.function" ; }
// Member in a template template tmpGroup(T) {
T t0(){ return "Tmp.member.0" ; } T t1(){ return "Tmp.member.1" ; } T t2(){ return "Tmp.member.2" ; }
}
// used for implementing member function at class & struct template Impl() {
static string aStatic() { return "Static Method" ; } string aMethod(){ return "Method" ; }
} class C { mixin Impl!() ; } struct S { mixin Impl!() ; }
void main() {
// nested function string aNested(){ return "Nested" ; }
// bind to a variable auto variableF = function string() { return "variable.F"; } ; auto variableD = delegate string() { return "variable.D"; } ;
C c = new C ; S s ;
"Global".test(&aFunction) ; "Nested".test(&aNested) ; "Class".test(&C.aStatic) .test(&c.aMethod) ; "Struct".test(&S.aStatic) .test(&s.aMethod) ; "Template".test(&tmpFunc!(string)) .test(&tmpGroup!(string).t2) ; "Binding".test(variableF) .test(variableD) ; // leteral function/delegate "Literal".test(function string() { return "literal.F"; }) .test(delegate string() { return "literal.D"; }) ;
}</lang>
E
<lang e>def map(f, list) {
var out := [] for x in list { out with= f(x) } return out
}
? map(fn x { x + x }, [1, "two"])
- value: [2, "twotwo"]
? map(1.add, [5, 10, 20])
- value: [6, 11, 21]
? def foo(x) { return -(x.size()) } > map(foo, ["", "a", "bc"])
- value: [0, -1, -2]</lang>
Erlang
Erlang functions are atoms, and they're considered different functions if their arity (the number of arguments they take) is different. As such, an Erlang function must be passed as fun Function/Arity
, but can be used as any other variable:
<lang erlang>-module(test).
-export([first/1, second/0]).
first(F) -> F(). second() -> hello.</lang> Testing it: <lang erlang>1> c(tests). {ok, tests} 2> tests:first(fun tests:second/0). hello 3> tests:first(fun() -> anonymous_function end). anonymous_function</lang>
FALSE
Anonymous code blocks are the basis of FALSE control flow and function definition. These blocks may be passed on the stack as with any other parameter. <lang false>[f:[$0>][@@\f;!\1-]#%]r: { reduce n stack items using the given basis and binary function }
1 2 3 4 0 4[+]r;!." " { 10 } 1 2 3 4 1 4[*]r;!." " { 24 } 1 2 3 4 0 4[$*+]r;!. { 30 }</lang>
Forth
Forth words can be referenced on the stack via their execution token or XT. An XT is obtained from a word via the quote operator, and invoked via EXECUTE. Anonymous functions may be defined via :NONAME (returning an XT) instead of a standard colon definition.
<lang forth>: square dup * ;
- cube dup dup * * ;
- map. ( xt addr len -- )
0 do 2dup i cells + @ swap execute . loop 2drop ;
create array 1 , 2 , 3 , 4 , 5 , ' square array 5 map. cr \ 1 4 9 16 25 ' cube array 5 map. cr \ 1 8 27 64 125
- noname 2* 1+ ; array 5 map. cr \ 3 5 7 9 11</lang>
Fortran
use the EXTERNAL attribute to show the dummy argument is another function rather than a data object. i.e. <lang fortran>FUNCTION FUNC3(FUNC1, FUNC2, x, y)
REAL, EXTERNAL :: FUNC1, FUNC2 REAL :: FUNC3 REAL :: x, y
FUNC3 = FUNC1(x) * FUNC2(y)
END FUNCTION FUNC3</lang>
Another way is to put the functions you want to pass in a module:
<lang fortran>module FuncContainer
implicit none
contains
function func1(x) real :: func1 real, intent(in) :: x
func1 = x**2.0 end function func1
function func2(x) real :: func2 real, intent(in) :: x
func2 = x**2.05 end function func2
end module FuncContainer
program FuncArg
use FuncContainer implicit none
print *, "Func1" call asubroutine(func1)
print *, "Func2" call asubroutine(func2)
contains
subroutine asubroutine(f) ! the following interface is redundant: can be omitted interface function f(x) real, intent(in) :: x real :: f end function f end interface real :: px
px = 0.0 do while( px < 10.0 ) print *, px, f(px) px = px + 1.0 end do end subroutine asubroutine
end program FuncArg</lang>
Haskell
A function is just a value that wants arguments: <lang haskell>func1 f = f "a string" func2 s = "func2 called with " ++ s
main = putStrLn $ func1 func2</lang> Or, with an anonymous function: <lang haskell>func f = f 1 2
main = print $ func (\x y -> x+y) -- output: 3</lang> Note that func (\x y -> x+y) is equivalent to func (+). (Operators are functions too.)
Icon
<lang icon> procedure main()
local lst lst := [10, 20, 30, 40] myfun(callback, lst)
end
procedure myfun(fun, lst)
every fun(!lst)
end
procedure callback(arg)
write("->", arg)
end</lang>
J
Adverbs take a single verb or noun argument and conjunctions take two. For example, / (insert) \ (prefix) and \. (suffix) are adverbs and ^: (power) is a conjunction. The following expressions illustrate their workings.
<lang j> + / 3 1 4 1 5 9 NB. sum 23
>./ 3 1 4 1 5 9 NB. max
9
*./ 3 1 4 1 5 9 NB. lcm
180
+/\ 3 1 4 1 5 9 NB. sum prefix (partial sums)
3 4 8 9 14 23
+/\. 3 1 4 1 5 9 NB. sum suffix
23 20 19 15 14 9
f=: -:@(+ 2&%) NB. one Newton iteration f 1
1.5
f f 1
1.41667
f^:(i.5) 1 NB. first 5 Newton iterations
1 1.5 1.41667 1.41422 1.41421
f^:(i.5) 1x NB. rational approximations to sqrt 2
1 3r2 17r12 577r408 665857r470832</lang>
Java
There is no real callback in Java like in C or C++, but we can do the same as swing does for executing an event. We need to create an interface that has the method we want to call or create one that will call the method we want to call. The following example uses the second way.
<lang java>public class NewClass {
public NewClass() { first(new AnEventOrCallback() { public void call() { second(); } }); } public void first(AnEventOrCallback obj) { obj.call(); } public void second() { System.out.println("Second"); } public static void main(String[] args) { new NewClass(); }
}
interface AnEventOrCallback {
public void call();
}</lang>
JavaScript
<lang javascript>function first (func) {
return func();
}
function second () {
return "second";
}
var result = first(second); result = first(function () { return "third"; });</lang>
An example with anonymous functions and uses in the core library
for methods filter
and map
.
<lang javascript>>>> var array = [2, 4, 5, 13, 18, 24, 34, 97]; >>> array [2, 4, 5, 13, 18, 24, 34, 97]
// return all elements less than 10 >>> array.filter(function (x) { return x < 10 }); [2, 4, 5]
// return all elements less than 30 >>> array.filter(function (x) { return x < 30 }); [2, 4, 5, 13, 18, 24]
// return all elements less than 100 >>> array.filter(function (x) { return x < 100 }); [2, 4, 5, 13, 18, 24, 34, 97]
// multiply each element by 2 and return the new array >>> array.map(function (x) { return x * 2 }); [4, 8, 10, 26, 36, 48, 68, 194]
// sort the array from smallest to largest >>> array.sort(function (a, b) { return a > b }); [2, 4, 5, 13, 18, 24, 34, 97]
// sort the array from largest to smallest >>> array.sort(function (a, b) { return a < b }); [97, 34, 24, 18, 13, 5, 4, 2]</lang>
Joy
This example is taken from V. Define first as multiplying two numbers on the stack. <lang joy>DEFINE first == *.</lang> There will be a warning about overwriting builtin first. Define second as interpreting the passed quotation on the stack. <lang joy>DEFINE second == i.</lang> Pass first enclosed in quotes to second which applies it on the stack. <lang joy>2 3 [first] second.</lang> The program prints 6.
Logo
You can pass the quoted symbol for the function and invoke it with RUN. <lang logo>to printstuff
print "stuff
end to runstuff :proc
run :proc
end runstuff "printstuff ; stuff runstuff [print [also stuff]] ; also stuff</lang>
Mathematica
Passing 3 arguments and a value (could be a number, variable, graphic or a function as well, actually it could be anything), and composing them in an unusual way: <lang Mathematica>PassFunc[f_, g_, h_, x_] := f[g[x]*h[x]] PassFunc[Tan, Cos, Sin, x] % /. x -> 0.12 PassFunc[Tan, Cos, Sin, 0.12]</lang> gives back: <lang Mathematica>Tan[Cos[x] Sin[x]] 0.119414 0.119414</lang>
MAXScript
<lang maxscript>fn second = (
print "Second"
)
fn first func = (
func()
)
first second</lang>
Metafont
We can simulate this by using scantokens
, which digests a string as if it would be a source input.
<lang metafont>def calcit(expr v, s) = scantokens(s & decimal v) enddef;
t := calcit(100.4, "sind"); show t; end</lang>
Modula-3
<lang modula3>MODULE Proc EXPORTS Main;
IMPORT IO;
TYPE Proc = PROCEDURE();
PROCEDURE Second() =
BEGIN IO.Put("Second procedure.\n"); END Second;
PROCEDURE First(proc: Proc) =
BEGIN proc(); END First;
BEGIN
First(Second);
END Proc.</lang>
OCaml
A function is just a value that wants arguments: <lang ocaml># let func1 f = f "a string";; val func1 : (string -> 'a) -> 'a = <fun>
- let func2 s = "func2 called with " ^ s;;
val func2 : string -> string = <fun>
- print_endline (func1 func2);;
func2 called with a string - : unit = ()</lang>
Or, with an anonymous function: <lang ocaml># let func f = f 1 2;; val func : (int -> int -> 'a) -> 'a = <fun>
- Printf.printf "%d\n" (func (fun x y -> x + y));;
3 - : unit = ()</lang> Note that func (fun x y -> x + y) is equivalent to func (+). (Operators are functions too.)
Octave
We can pass a function handle (@function_name
)
<lang octave>function r = computeit(f, g, v)
r = f(g(v));
endfunction
computeit(@exp, @sin, pi/3) computeit(@log, @cos, pi/6)</lang>
Or pass the string name of the function and use the feval
primitive.
<lang octave>function r = computeit2(f, g, v)
r = f(feval(g, v));
endfunction
computeit2(@exp, "sin", pi/3)</lang>
Pascal
Standard Pascal (will not work with Turbo Pascal): <lang pascal>program example(output);
function first(function f(x: real): real): real;
begin first := f(1.0) + 2.0; end;
function second(x: real): real;
begin second := x/2.0; end;
begin
writeln(first(second));
end.</lang>
Turbo Pascal (will not work with Standard Pascal):
<lang pascal>program example;
type
FnType = function(x: real): real;
function first(f: FnType): real;
begin first := f(1.0) + 2.0; end;
function second(x: real): real;
begin second := x/2.0; end;
begin
writeln(first(second));
end.</lang>
Perl
<lang perl>sub another {
# take a function and a value my $func = shift; my $val = shift;
# call the function with the value as argument return $func->($val);
};
sub reverser {
return scalar reverse shift;
};
- pass named coderef
print another \&reverser, 'data';
- pass anonymous coderef
print another sub {return scalar reverse shift}, 'data';
- if all you have is a string and you want to act on that,
- set up a dispatch table
my %dispatch = (
square => sub {return shift() ** 2}, cube => sub {return shift() ** 3}, rev => \&reverser,
);
print another $dispatch{$_}, 123 for qw(square cube rev);</lang>
<lang perl>sub apply (&@) { # use & as the first item in a prototype to take bare blocks like map and grep
my ($sub, @ret) = @_; # this function applies a function that is expected to modify $_ to a list $sub->() for @ret; # it allows for simple inline application of the s/// and tr/// constructs @ret
}
print join ", " => apply {tr/aeiou/AEIOU/} qw/one two three four/;
- OnE, twO, thrEE, fOUr</lang>
<lang perl>sub first {shift->()}
sub second {'second'}
print first \&second;
print first sub{'sub'};</lang>
Perl 6
The best type to use for the parameter of a higher-order function is Callable
, a role common to all function-like objects. For an example of defining and calling a second-order function, see Functional Composition.
PHP
<lang php>function first($func) {
return $func();
}
function second() {
return 'second';
}
$result = first('second');</lang>
Pop11
<lang pop11>;;; Define a function define x_times_three_minus_1(x);
return(3*x-1);
enddefine;
- Pass it as argument to built-in function map and print the result
mapdata({0 1 2 3 4}, x_times_three_minus_1) =></lang>
Python
<lang python>def first(function):
return function()
def second():
return "second"
result = first(second)</lang>
or
<lang python> result = first(lambda: "second")</lang>
Functions are first class objects in Python. They can be bound to names ("assigned" to "variables"), associated with keys in dictionaries, and passed around like any other object references. Classes are also first class objects and every class in Python is, implicitly, a "factory" for creating (instantiating) objects of that class. The use of class references support metaprogramming.
R
<lang R>f <- function(f0) f0(pi) # calc. the function in pi tf <- function(x) x^pi # a func. just to test
print(f(sin)) print(f(cos)) print(f(tf))</lang>
Ruby
With a proc (procedure): <lang ruby>succ = proc{|x| x+1} def to2(&f)
f[2]
end
to2(&succ) #=> 3 to2{|x| x+1} #=> 3</lang>
With a method: <lang ruby>def succ(n)
n+1
end def to2(m)
m[2]
end
meth = method(:succ) to2(meth) #=> 3</lang>
Scala
<lang scala>def functionWithAFunctionArgument(x : int, y : int, f : (int, int) => int) = f(x,y)</lang> Call: <lang scala>functionWithAFunctionArgument(3, 5, {(x, y) => x + y}) // returns 8</lang>
Scheme
A function is just a value that wants arguments: <lang scheme>> (define (func1 f) (f "a string")) > (define (func2 s) (string-append "func2 called with " s)) > (begin (display (func1 func2)) (newline)) func2 called with a string</lang>
Or, with an anonymous function: <lang scheme>> (define (func f) (f 1 2)) > (begin (display (func (lambda (x y) (+ x y)))) (newline)) 3</lang> Note that (func (lambda (x y) (+ x y))) is equivalent to (func +). (Operators are functions too.)
Slate
Methods and blocks can both be passed as arguments to functions (other methods and blocks): <lang slate>define: #function -> [| :x | x * 3 - 1].
- (1 1 2 3 5 8) collect: function.</lang>
Standard ML
<lang sml>- fun func1 f = f "a string"; val func1 = fn : (string -> 'a) -> 'a - fun func2 s = "func2 called with " ^ s; val func2 = fn : string -> string
- print (func1 func2 ^ "\n"); func2 called with a string val it = () : unit</lang>
Or, with an anonymous function: <lang sml>- fun func f = f (1, 2); val func = fn : (int * int -> 'a) -> 'a
- print (Int.toString (func (fn (x, y) => x + y)) ^ "\n"); 3 val it = () : unit</lang> Note that func (fn (x, y) => x + y) is equivalent to func op+. (Operators are functions too.)
Tcl
<lang tcl># this procedure executes its argument: proc demo {function} {
$function
}
- for example:
demo bell</lang> It is more common to pass not just a function, but a command fragment or entire script. When used with the built-in list command (which introduces a very useful degree of quoting) this makes for a very common set of techniques when doing advanced Tcl programming. <lang tcl># This procedure executes its argument with an extra argument of "2" proc demoFrag {fragment} {
{*}$fragment 2
}
- This procedure executes its argument in the context of its caller, which is
- useful for scripts so they get the right variable resolution context
proc demoScript {script} {
uplevel 1 $script
}
- Examples...
set chan stderr demoFrag [list puts $chan] demoFrag {
apply {x {puts [string repeat ? $x]}}
} demoScript {
parray tcl_platform
}</lang>
TI-89 BASIC
TI-89 BASIC does not have first-class functions; while function definitions as stored in variables are fully dynamic, it is not possible to extract a function value from a variable rather than calling it. In this case, we use the indirection operator #
, which takes a string and returns the value of the named variable, to use the name of the function as something to be passed.
The function name passed cannot be that of a local function, because the local function map
does not see the local variables of the enclosing function.
<lang ti89b>Local map Define map(f,l)=Func
Return seq(#f(l[i]),i,1,dim(l))
EndFunc Disp map("sin", {0, π/6, π/4, π/3, π/2})</lang>
Toka
Toka allows obtaining a function pointer via the ` (backtick) word. The pointers are passed on the stack, just like all other data.
<lang toka>[ ." First\n" ] is first [ invoke ] is second ` first second</lang>
Ursala
Autocomposition is a user defined function that takes a function as an argument, and returns a function equivalent to the given functon composed with itself.
<lang Ursala>(autocomposition "f") "x" = "f" "f" "x"</lang> test program: <lang Ursala>#import flo
- cast %e
example = autocomposition(sqrt) 16.0</lang> output:
2.000000e+00
V
Define first as multiplying two numbers on stack <lang v>[first *].</lang> Define second as applying the passed quote on stack <lang v>[second i].</lang> Pass the first enclosed in quote to second which applies it on stack. <lang v>2 3 [first] second</lang>
=6