Higher-order functions: Difference between revisions

Content added Content deleted
m (syntax highlighting fixup automation)
Line 12: Line 12:
{{trans|Python}}
{{trans|Python}}


<lang 11l>F first(function)
<syntaxhighlight lang="11l">F first(function)
R function()
R function()


Line 19: Line 19:


V result = first(second)
V result = first(second)
print(result)</lang>
print(result)</syntaxhighlight>


{{out}}
{{out}}
Line 29: Line 29:


Code is called using the following macro, e.g. <code>PrintOutput #$FF,foo</code>. The printing routine is left unimplemented.
Code is called using the following macro, e.g. <code>PrintOutput #$FF,foo</code>. The printing routine is left unimplemented.
<lang 6502asm>macro PrintOutput,input,addr
<syntaxhighlight lang="6502asm">macro PrintOutput,input,addr
; input: desired function's input
; input: desired function's input
; addr: function you wish to call
; addr: function you wish to call
Line 38: Line 38:
LDA \input
LDA \input
JSR doPrintOutput
JSR doPrintOutput
endm</lang>
endm</syntaxhighlight>


<lang 6502asm>PrintOutput:
<syntaxhighlight lang="6502asm">PrintOutput:
; prints the output of the function "foo" to the screen.
; prints the output of the function "foo" to the screen.
; input:
; input:
Line 62: Line 62:
JSR PrintAccumulator
JSR PrintAccumulator


rts</lang>
rts</syntaxhighlight>
=={{header|68000 Assembly}}==
=={{header|68000 Assembly}}==
This trivial example shows a simple return spoof.
This trivial example shows a simple return spoof.
<lang 68000devpac>LEA foo,A0
<syntaxhighlight lang="68000devpac">LEA foo,A0
JSR bar
JSR bar


Line 75: Line 75:


foo:
foo:
RTS ;do nothing and return. This rts retuns execution just after "JSR bar" but before "JMP *".</lang>
RTS ;do nothing and return. This rts retuns execution just after "JSR bar" but before "JMP *".</syntaxhighlight>




=={{header|8th}}==
=={{header|8th}}==
<lang forth>
<syntaxhighlight lang="forth">
: pass-me
: pass-me
"I was passed\n" . ;
"I was passed\n" . ;
Line 86: Line 86:
\ pass 'pass-me' to 'passer'
\ pass 'pass-me' to 'passer'
' pass-me passer
' pass-me passer
</syntaxhighlight>
</lang>
{{out}}
{{out}}
I was passed
I was passed


=={{header|ActionScript}}==
=={{header|ActionScript}}==
<lang actionscript>package {
<syntaxhighlight lang="actionscript">package {
public class MyClass {
public class MyClass {


Line 109: Line 109:
}
}
}
}
}</lang>
}</syntaxhighlight>


=={{header|Ada}}==
=={{header|Ada}}==
===Simple Example===
===Simple Example===
<lang ada>with Ada.Text_Io; use Ada.Text_Io;
<syntaxhighlight lang="ada">with Ada.Text_Io; use Ada.Text_Io;


procedure Subprogram_As_Argument is
procedure Subprogram_As_Argument is
Line 129: Line 129:
begin
begin
First(Second'Access);
First(Second'Access);
end Subprogram_As_Argument;</lang>
end Subprogram_As_Argument;</syntaxhighlight>
===Complex Example===
===Complex Example===
<lang ada>with Ada.Text_Io; use Ada.Text_Io;
<syntaxhighlight lang="ada">with Ada.Text_Io; use Ada.Text_Io;


procedure Subprogram_As_Argument_2 is
procedure Subprogram_As_Argument_2 is
Line 182: Line 182:
Int_Ptr := Complex_Func(F_Ptr, 3);
Int_Ptr := Complex_Func(F_Ptr, 3);
Put_Line(Integer'Image(Int_Ptr.All));
Put_Line(Integer'Image(Int_Ptr.All));
end Subprogram_As_Argument_2;</lang>
end Subprogram_As_Argument_2;</syntaxhighlight>


=={{header|Aime}}==
=={{header|Aime}}==
<lang aime>integer
<syntaxhighlight lang="aime">integer
average(integer p, integer q)
average(integer p, integer q)
{
{
Line 209: Line 209:


return 0;
return 0;
}</lang>
}</syntaxhighlight>


=={{header|ALGOL 68}}==
=={{header|ALGOL 68}}==
Line 216: Line 216:
{{works with|ALGOL 68G|Any - tested with release [http://sourceforge.net/projects/algol68/files/algol68g/algol68g-1.18.0/algol68g-1.18.0-9h.tiny.el5.centos.fc11.i386.rpm/download 1.18.0-9h.tiny]}}
{{works with|ALGOL 68G|Any - tested with release [http://sourceforge.net/projects/algol68/files/algol68g/algol68g-1.18.0/algol68g-1.18.0-9h.tiny.el5.centos.fc11.i386.rpm/download 1.18.0-9h.tiny]}}
{{wont work with|ELLA ALGOL 68|Any (with appropriate job cards) - tested with release [http://sourceforge.net/projects/algol68/files/algol68toc/algol68toc-1.8.8d/algol68toc-1.8-8d.fc9.i386.rpm/download 1.8-8d] - due to extensive use of FORMATted transput}}
{{wont work with|ELLA ALGOL 68|Any (with appropriate job cards) - tested with release [http://sourceforge.net/projects/algol68/files/algol68toc/algol68toc-1.8.8d/algol68toc-1.8-8d.fc9.i386.rpm/download 1.8-8d] - due to extensive use of FORMATted transput}}
<lang algol68>PROC first = (PROC(LONG REAL)LONG REAL f) LONG REAL:
<syntaxhighlight lang="algol68">PROC first = (PROC(LONG REAL)LONG REAL f) LONG REAL:
(
(
f(1) + 2
f(1) + 2
Line 228: Line 228:
main: (
main: (
printf(($xg(5,2)l$,first(second)))
printf(($xg(5,2)l$,first(second)))
)</lang>
)</syntaxhighlight>
Output:
Output:
<pre>
<pre>
Line 236: Line 236:
=={{header|AmigaE}}==
=={{header|AmigaE}}==
The <tt>{}</tt> 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'' (<tt>func</tt>, holding a pointer to a real function in our case) is used like a function.
The <tt>{}</tt> 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'' (<tt>func</tt>, holding a pointer to a real function in our case) is used like a function.
<lang amigae>PROC compute(func, val)
<syntaxhighlight lang="amigae">PROC compute(func, val)
DEF s[10] : STRING
DEF s[10] : STRING
WriteF('\s\n', RealF(s,func(val),4))
WriteF('\s\n', RealF(s,func(val),4))
Line 247: Line 247:
compute({sin_wrap}, 0.0)
compute({sin_wrap}, 0.0)
compute({cos_wrap}, 3.1415)
compute({cos_wrap}, 3.1415)
ENDPROC</lang>
ENDPROC</syntaxhighlight>


=={{header|AntLang}}==
=={{header|AntLang}}==
<lang AntLang>twice:{x[x[y]]}
<syntaxhighlight lang="antlang">twice:{x[x[y]]}
echo twice "Hello!"</lang>
echo twice "Hello!"</syntaxhighlight>


=={{header|AppleScript}}==
=={{header|AppleScript}}==
<lang applescript>-- This handler takes a script object (singer)
<syntaxhighlight lang="applescript">-- This handler takes a script object (singer)
-- with another handler (call).
-- with another handler (call).
on sing about topic by singer
on sing about topic by singer
Line 278: Line 278:
end script
end script
end hire
end hire
sing about "closures" by (hire for "Pipe Organ")</lang>
sing about "closures" by (hire for "Pipe Organ")</syntaxhighlight>


As we can see above, AppleScript functions (referred to as 'handlers' in Apple's documentation) are not, in themselves, first class objects. They can only be applied within other functions, when passed as arguments, if wrapped in Script objects. If we abstract out this lifting of functions into objects by writing an '''mReturn''' or '''mInject''' function, we can then use it to write some higher-order functions which directly accept unadorned AppleScript handlers as arguments.
As we can see above, AppleScript functions (referred to as 'handlers' in Apple's documentation) are not, in themselves, first class objects. They can only be applied within other functions, when passed as arguments, if wrapped in Script objects. If we abstract out this lifting of functions into objects by writing an '''mReturn''' or '''mInject''' function, we can then use it to write some higher-order functions which directly accept unadorned AppleScript handlers as arguments.
Line 284: Line 284:
We could, for example, write '''map''', '''fold/reduce''' and '''filter''' functions for AppleScript as follows:
We could, for example, write '''map''', '''fold/reduce''' and '''filter''' functions for AppleScript as follows:


<lang applescript>on run
<syntaxhighlight lang="applescript">on run
-- PASSING FUNCTIONS AS ARGUMENTS TO
-- PASSING FUNCTIONS AS ARGUMENTS TO
-- MAP, FOLD/REDUCE, AND FILTER, ACROSS A LIST
-- MAP, FOLD/REDUCE, AND FILTER, ACROSS A LIST
Line 398: Line 398:
on isEven(x)
on isEven(x)
x mod 2 = 0
x mod 2 = 0
end isEven</lang>
end isEven</syntaxhighlight>
{{Out}}
{{Out}}
<lang applescript>{{0, 2, 4, 6, 8, 10, 12, 14, 16, 18, 20},
<syntaxhighlight lang="applescript">{{0, 2, 4, 6, 8, 10, 12, 14, 16, 18, 20},
{0, 1, 4, 9, 16, 25, 36, 49, 64, 81, 100},
{0, 1, 4, 9, 16, 25, 36, 49, 64, 81, 100},
{true, false, true, false, true, false, true, false, true, false, true}}</lang>
{true, false, true, false, true, false, true, false, true, false, true}}</syntaxhighlight>


===Alternative description===
===Alternative description===
Line 408: Line 408:
In plain English, one handler can be passed as a parameter to another either in a script object …
In plain English, one handler can be passed as a parameter to another either in a script object …


<lang applescript>script aScript
<syntaxhighlight lang="applescript">script aScript
on aHandler(aParameter)
on aHandler(aParameter)
say aParameter
say aParameter
Line 418: Line 418:
end receivingHandler
end receivingHandler


receivingHandler(aScript)</lang>
receivingHandler(aScript)</syntaxhighlight>


… or directly, with the passed pointer being assigned to a script object property upon receipt:
… or directly, with the passed pointer being assigned to a script object property upon receipt:


<lang applescript>on aHandler(aParameter)
<syntaxhighlight lang="applescript">on aHandler(aParameter)
say aParameter
say aParameter
end aHandler
end aHandler
Line 434: Line 434:
end receivingHandler
end receivingHandler


receivingHandler(aHandler)</lang>
receivingHandler(aHandler)</syntaxhighlight>


It's not often that handlers actually need to be passed as parameters, but passing them in script objects is usually more flexible as additional information on which they depend can then be included if required which the receiving handler doesn't need to know.
It's not often that handlers actually need to be passed as parameters, but passing them in script objects is usually more flexible as additional information on which they depend can then be included if required which the receiving handler doesn't need to know.
Line 441: Line 441:


=={{header|Arturo}}==
=={{header|Arturo}}==
<lang arturo>doSthWith: function [x y f][
<syntaxhighlight lang="arturo">doSthWith: function [x y f][
f x y
f x y
]
]


print [ "add:" doSthWith 2 3 $[x y][x+y] ]
print [ "add:" doSthWith 2 3 $[x y][x+y] ]
print [ "multiply:" doSthWith 2 3 $[x y][x*y] ]</lang>
print [ "multiply:" doSthWith 2 3 $[x y][x*y] ]</syntaxhighlight>
{{out}}
{{out}}
<pre>add: 5
<pre>add: 5
Line 452: Line 452:


=={{header|ATS}}==
=={{header|ATS}}==
<syntaxhighlight lang="ats">
<lang ATS>
#include
#include
"share/atspre_staload.hats"
"share/atspre_staload.hats"
Line 466: Line 466:
//
//
} (* end of [main0] *)
} (* end of [main0] *)
</syntaxhighlight>
</lang>


=={{header|AutoHotkey}}==
=={{header|AutoHotkey}}==
<syntaxhighlight lang="autohotkey">
<lang AutoHotkey>
f(x) {
f(x) {
return "This " . x
return "This " . x
Line 485: Line 485:
show("g") ; or just name the function
show("g") ; or just name the function
return
return
</syntaxhighlight>
</lang>


=={{header|BBC BASIC}}==
=={{header|BBC BASIC}}==
{{works with|BBC BASIC for Windows}}
{{works with|BBC BASIC for Windows}}
<lang bbcbasic> REM Test passing a function to a function:
<syntaxhighlight lang="bbcbasic"> REM Test passing a function to a function:
PRINT FNtwo(FNone(), 10, 11)
PRINT FNtwo(FNone(), 10, 11)
END
END
Line 497: Line 497:
REM Function taking a function as an argument:
REM Function taking a function as an argument:
DEF FNtwo(RETURN f%, x, y) = FN(^f%)(x, y)</lang>
DEF FNtwo(RETURN f%, x, y) = FN(^f%)(x, y)</syntaxhighlight>
'''Output:'''
'''Output:'''
<pre>
<pre>
Line 507: Line 507:


A function's name in lowercase can be used to pass it as a subject, rather than a function to be executed.
A function's name in lowercase can be used to pass it as a subject, rather than a function to be executed.
<lang bqn>Uniq ← ⍷
<syntaxhighlight lang="bqn">Uniq ← ⍷


•Show uniq {𝕎𝕩} 5‿6‿7‿5</lang><lang>⟨ 5 6 7 ⟩</lang>
•Show uniq {𝕎𝕩} 5‿6‿7‿5</syntaxhighlight><syntaxhighlight lang="text">⟨ 5 6 7 ⟩</syntaxhighlight>
[https://mlochbaum.github.io/BQN/try.html#code=VW5pcSDihpAg4o23CgrigKJTaG93IHVuaXEge/CdlY7wnZWpfSA14oC/NuKAvzfigL81 Try It!]
[https://mlochbaum.github.io/BQN/try.html#code=VW5pcSDihpAg4o23CgrigKJTaG93IHVuaXEge/CdlY7wnZWpfSA14oC/NuKAvzfigL81 Try It!]


=={{header|Bracmat}}==
=={{header|Bracmat}}==
<lang bracmat>( (plus=a b.!arg:(?a.?b)&!a+!b)
<syntaxhighlight lang="bracmat">( (plus=a b.!arg:(?a.?b)&!a+!b)
& ( print
& ( print
= text a b func
= text a b func
Line 526: Line 526:
. multiply
. multiply
)
)
);</lang>
);</syntaxhighlight>
Output:
Output:
<pre>add(3,7)=10
<pre>add(3,7)=10
Line 532: Line 532:


=={{header|Brat}}==
=={{header|Brat}}==
<lang brat>add = { a, b | a + b }
<syntaxhighlight lang="brat">add = { a, b | a + b }


doit = { f, a, b | f a, b }
doit = { f, a, b | f a, b }


p doit ->add 1 2 #prints 3</lang>
p doit ->add 1 2 #prints 3</syntaxhighlight>


=={{header|Burlesque}}==
=={{header|Burlesque}}==
Line 543: Line 543:
The function "m[" (map) takes a block (a 'function') as it's argument. Add 5 to every element in a list (like map (+5) [1,2,3,4] in haskell):
The function "m[" (map) takes a block (a 'function') as it's argument. Add 5 to every element in a list (like map (+5) [1,2,3,4] in haskell):


<lang burlesque>
<syntaxhighlight lang="burlesque">
blsq ) {1 2 3 4}{5.+}m[
blsq ) {1 2 3 4}{5.+}m[
{6 7 8 9}
{6 7 8 9}
</syntaxhighlight>
</lang>


=={{header|C}}==
=={{header|C}}==
Line 555: Line 555:
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>void myFuncSimple( void (*funcParameter)(void) )
<syntaxhighlight lang="c">void myFuncSimple( void (*funcParameter)(void) )
{
{
/* ... */
/* ... */
Line 563: Line 563:


/* ... */
/* ... */
}</lang>
}</syntaxhighlight>


Note that you ''can't'' call the passed function by " *funcParameter() ", since that would mean "call funcParameter and then 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 then apply the * operator on the returned value".
Line 569: Line 569:
Call:
Call:


<lang c>void funcToBePassed(void);
<syntaxhighlight lang="c">void funcToBePassed(void);


/* ... */
/* ... */


myFuncSimple(&funcToBePassed);</lang>
myFuncSimple(&funcToBePassed);</syntaxhighlight>


'''Complex example'''
'''Complex example'''
Line 579: Line 579:
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>int* myFuncComplex( double* (*funcParameter)(long* parameter) )
<syntaxhighlight lang="c">int* myFuncComplex( double* (*funcParameter)(long* parameter) )
{
{
long inLong;
long inLong;
Line 591: Line 591:


/* ... */
/* ... */
}</lang>
}</syntaxhighlight>
Call:
Call:


<lang c>double* funcToBePassed(long* parameter);
<syntaxhighlight lang="c">double* funcToBePassed(long* parameter);


/* ... */
/* ... */
Line 600: Line 600:
int* outInt;
int* outInt;


outInt = myFuncComplex(&funcToBePassed);</lang>
outInt = myFuncComplex(&funcToBePassed);</syntaxhighlight>


'''Pointer'''
'''Pointer'''
Line 606: Line 606:
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>int* (*funcPointer)( double* (*funcParameter)(long* parameter) );
<syntaxhighlight lang="c">int* (*funcPointer)( double* (*funcParameter)(long* parameter) );


/* ... */
/* ... */


funcPointer = &myFuncComplex;</lang>
funcPointer = &myFuncComplex;</syntaxhighlight>


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 628: Line 628:
This implementation works in all standard versions of C#.
This implementation works in all standard versions of C#.


<lang csharp>using System;
<syntaxhighlight lang="csharp">using System;


// A delegate declaration. Because delegates are types, they can exist directly in namespaces.
// A delegate declaration. Because delegates are types, they can exist directly in namespaces.
Line 670: Line 670:
Console.WriteLine("f=Div, f({0}, {1}) = {2}", a, b, Call(div, a, b));
Console.WriteLine("f=Div, f({0}, {1}) = {2}", a, b, Call(div, a, b));
}
}
}</lang>
}</syntaxhighlight>


===C# 2.0: Anonymous methods===
===C# 2.0: Anonymous methods===
Anonymous methods were added in C# 2.0. Parameter types must be specified. Anonymous methods must be "coerced" to a delegate type known at compile-time; they cannot be used with a target type of Object or to initialize implicitly typed variables.
Anonymous methods were added in C# 2.0. Parameter types must be specified. Anonymous methods must be "coerced" to a delegate type known at compile-time; they cannot be used with a target type of Object or to initialize implicitly typed variables.


<lang csharp>using System;
<syntaxhighlight lang="csharp">using System;


delegate int Func2(int a, int b);
delegate int Func2(int a, int b);
Line 695: Line 695:
Console.WriteLine("f=Div, f({0}, {1}) = {2}", a, b, Call(delegate(int x, int y) { return x / y; }, a, b));
Console.WriteLine("f=Div, f({0}, {1}) = {2}", a, b, Call(delegate(int x, int y) { return x / y; }, a, b));
}
}
}</lang>
}</syntaxhighlight>


==={{anchor|C#: Lambda expressions}}C# 3.0: Lambda expressions===
==={{anchor|C#: Lambda expressions}}C# 3.0: Lambda expressions===
Line 706: Line 706:
{{works with|C sharp|C#|3+}}
{{works with|C sharp|C#|3+}}


<lang csharp>using System;
<syntaxhighlight lang="csharp">using System;


class Program
class Program
Line 729: Line 729:
Console.WriteLine("f=Div, f({0}, {1}) = {2}", a, b, Call((x, y) => x / y, a, b));
Console.WriteLine("f=Div, f({0}, {1}) = {2}", a, b, Call((x, y) => x / y, a, b));
}
}
}</lang>
}</syntaxhighlight>


=={{header|C++}}==
=={{header|C++}}==
Line 746: Line 746:


{{works with|gcc|4.4}}
{{works with|gcc|4.4}}
<lang cpp>
<syntaxhighlight lang="cpp">
// Use <functional> for C++11
// Use <functional> for C++11
#include <tr1/functional>
#include <tr1/functional>
Line 768: Line 768:
first(second);
first(second);
}
}
</syntaxhighlight>
</lang>


===Template and Inheritance===
===Template and Inheritance===
Line 774: Line 774:
{{works with|Visual C++|2005}}
{{works with|Visual C++|2005}}


<lang cpp>#include <iostream>
<syntaxhighlight lang="cpp">#include <iostream>
#include <functional>
#include <functional>


Line 796: Line 796:
std::cout << first(second(), 2) << std::endl;
std::cout << first(second(), 2) << std::endl;
return 0;
return 0;
}</lang>
}</syntaxhighlight>


=={{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]
<syntaxhighlight lang="clean">map f [x:xs] = [f x:map f xs]
map f [] = []</lang>
map f [] = []</syntaxhighlight>
Pass a function as an argument:
Pass a function as an argument:
<lang clean>incr x = x + 1
<syntaxhighlight lang="clean">incr x = x + 1


Start = map incr [1..10]</lang>
Start = map incr [1..10]</syntaxhighlight>
Do the same using a anonymous function:
Do the same using a anonymous function:
<lang clean>Start = map (\x -> x + 1) [1..10]</lang>
<syntaxhighlight lang="clean">Start = map (\x -> x + 1) [1..10]</syntaxhighlight>
Do the same using currying:
Do the same using currying:
<lang clean>Start = map ((+) 1) [1..10]</lang>
<syntaxhighlight lang="clean">Start = map ((+) 1) [1..10]</syntaxhighlight>


=={{header|Clojure}}==
=={{header|Clojure}}==


<lang lisp>
<syntaxhighlight lang="lisp">
(defn append-hello [s]
(defn append-hello [s]
(str "Hello " s))
(str "Hello " s))
Line 821: Line 821:


(println (modify-string append-hello "World!"))
(println (modify-string append-hello "World!"))
</syntaxhighlight>
</lang>


=={{header|CLU}}==
=={{header|CLU}}==
<lang clu>% Functions can be passed to other functions using the 'proctype'
<syntaxhighlight lang="clu">% Functions can be passed to other functions using the 'proctype'
% type generator. The same works for iterators, using 'itertype'
% type generator. The same works for iterators, using 'itertype'


Line 847: Line 847:
do_calcs(1, 10, "Squares", square)
do_calcs(1, 10, "Squares", square)
do_calcs(1, 10, "Cubes", cube)
do_calcs(1, 10, "Cubes", cube)
end start_up</lang>
end start_up</syntaxhighlight>
{{out}}
{{out}}
<pre>Squares -> 1 4 9 16 25 36 49 64 81 100
<pre>Squares -> 1 4 9 16 25 36 49 64 81 100
Line 856: Line 856:
Passing an anonymous function to built-in map/reduce functions:
Passing an anonymous function to built-in map/reduce functions:


<lang coffeescript>double = [1,2,3].map (x) -> x*2</lang>
<syntaxhighlight lang="coffeescript">double = [1,2,3].map (x) -> x*2</syntaxhighlight>


Using a function stored in a variable:
Using a function stored in a variable:


<lang coffeescript>fn = -> return 8
<syntaxhighlight lang="coffeescript">fn = -> return 8
sum = (a, b) -> a() + b()
sum = (a, b) -> a() + b()
sum(fn, fn) # => 16
sum(fn, fn) # => 16
</syntaxhighlight>
</lang>


List comprehension with a function argument:
List comprehension with a function argument:


<lang coffeescript>bowl = ["Cheese", "Tomato"]
<syntaxhighlight lang="coffeescript">bowl = ["Cheese", "Tomato"]


smash = (ingredient) ->
smash = (ingredient) ->
Line 874: Line 874:
contents = smash ingredient for ingredient in bowl
contents = smash ingredient for ingredient in bowl
# => ["Smashed Cheese", "Smashed Tomato"]
# => ["Smashed Cheese", "Smashed Tomato"]
</syntaxhighlight>
</lang>


Nested function passing:
Nested function passing:


<lang coffeescript>double = (x) -> x*2
<syntaxhighlight lang="coffeescript">double = (x) -> x*2
triple = (x) -> x*3
triple = (x) -> x*3
addOne = (x) -> x+1
addOne = (x) -> x+1


addOne triple double 2 # same as addOne(triple(double(2)))</lang>
addOne triple double 2 # same as addOne(triple(double(2)))</syntaxhighlight>


A function that returns a function that returns a function that returns a function that returns 2, immediately executed:
A function that returns a function that returns a function that returns a function that returns 2, immediately executed:


<lang coffeescript>(-> -> -> -> 2 )()()()() # => 2</lang>
<syntaxhighlight lang="coffeescript">(-> -> -> -> 2 )()()()() # => 2</syntaxhighlight>


A function that takes a function that takes a function argument:
A function that takes a function that takes a function argument:


<lang coffeescript>((x)->
<syntaxhighlight lang="coffeescript">((x)->
2 + x(-> 5)
2 + x(-> 5)
)((y) -> y()+3)
)((y) -> y()+3)
# result: 10</lang>
# result: 10</syntaxhighlight>


=={{header|Common Lisp}}==
=={{header|Common Lisp}}==
In Common Lisp, functions are [[wp:First-class_object|first class objects]], so you can pass function objects as arguments to other functions:
In Common Lisp, functions are [[wp: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))
<syntaxhighlight lang="lisp">CL-USER> (defun add (a b) (+ a b))
ADD
ADD
CL-USER> (add 1 2)
CL-USER> (add 1 2)
Line 906: Line 906:
CALL-IT
CALL-IT
CL-USER> (call-it #'add 1 2)
CL-USER> (call-it #'add 1 2)
3</lang>
3</syntaxhighlight>
The Common Lisp library makes extensive use of higher-order functions:
The Common Lisp library makes extensive use of higher-order functions:
<pre>CL-USER> (funcall #'+ 1 2 3)
<pre>CL-USER> (funcall #'+ 1 2 3)
Line 921: Line 921:


=={{header|Cowgol}}==
=={{header|Cowgol}}==
<lang cowgol>include "cowgol.coh";
<syntaxhighlight lang="cowgol">include "cowgol.coh";


# In order to pass functions around, you must first define an interface.
# In order to pass functions around, you must first define an interface.
Line 973: Line 973:
end sub;
end sub;


showAll(&operators[0], 84, 42); # example</lang>
showAll(&operators[0], 84, 42); # example</syntaxhighlight>


{{out}}
{{out}}
Line 983: Line 983:


=={{header|D}}==
=={{header|D}}==
<lang d>int hof(int a, int b, int delegate(int, int) f) {
<syntaxhighlight lang="d">int hof(int a, int b, int delegate(int, int) f) {
return f(a, b);
return f(a, b);
}
}
Line 991: Line 991:
writeln("Add: ", hof(2, 3, (a, b) => a + b));
writeln("Add: ", hof(2, 3, (a, b) => a + b));
writeln("Multiply: ", hof(2, 3, (a, b) => a * b));
writeln("Multiply: ", hof(2, 3, (a, b) => a * b));
}</lang>
}</syntaxhighlight>
{{out}}
{{out}}
<pre>Add: 5
<pre>Add: 5
Multiply: 6</pre>
Multiply: 6</pre>
This longer and more systematic example shows D functions/delegates by passing each type of function/delegate to _test_ as argument.
This longer and more systematic example shows D functions/delegates by passing each type of function/delegate to _test_ as argument.
<lang d>import std.stdio;
<syntaxhighlight lang="d">import std.stdio;


// Test the function argument.
// Test the function argument.
Line 1,056: Line 1,056:
"Literal".test(function string() { return "literal.F"; })
"Literal".test(function string() { return "literal.F"; })
.test(delegate string() { return "literal.D"; });
.test(delegate string() { return "literal.D"; });
}</lang>
}</syntaxhighlight>
{{out}}}
{{out}}}
<pre>Hi, Function : scope: Global (function) : immutable(char)[]()*
<pre>Hi, Function : scope: Global (function) : immutable(char)[]()*
Line 1,075: Line 1,075:


=={{header|DWScript}}==
=={{header|DWScript}}==
<lang delphi>type TFnType = function(x : Float) : Float;
<syntaxhighlight lang="delphi">type TFnType = function(x : Float) : Float;
function First(f : TFnType) : Float;
function First(f : TFnType) : Float;
Line 1,087: Line 1,087:
end;
end;
PrintLn(First(Second));</lang>
PrintLn(First(Second));</syntaxhighlight>


=={{header|Dyalect}}==
=={{header|Dyalect}}==
Line 1,093: Line 1,093:
{{trans|C#}}
{{trans|C#}}


<lang Dyalect>func call(f, a, b) {
<syntaxhighlight lang="dyalect">func call(f, a, b) {
f(a, b)
f(a, b)
}
}
Line 1,102: Line 1,102:
print("f=add, f(\(a), \(b)) = \(call((x, y) => x + y, a, b))")
print("f=add, f(\(a), \(b)) = \(call((x, y) => x + y, a, b))")
print("f=mul, f(\(a), \(b)) = \(call((x, y) => x * y, a, b))")
print("f=mul, f(\(a), \(b)) = \(call((x, y) => x * y, a, b))")
print("f=div, f(\(a), \(b)) = \(call((x, y) => x / y, a, b))")</lang>
print("f=div, f(\(a), \(b)) = \(call((x, y) => x / y, a, b))")</syntaxhighlight>


{{out}}
{{out}}
Line 1,111: Line 1,111:


=={{header|Déjà Vu}}==
=={{header|Déjà Vu}}==
<lang dejavu>map f lst:
<syntaxhighlight lang="dejavu">map f lst:
]
]
for item in lst:
for item in lst:
Line 1,120: Line 1,120:
* 2
* 2


!. map @twice [ 1 2 5 ]</lang>
!. map @twice [ 1 2 5 ]</syntaxhighlight>
{{out}}
{{out}}
<pre>[ 2 4 10 ]</pre>
<pre>[ 2 4 10 ]</pre>


=={{header|Draco}}==
=={{header|Draco}}==
<lang draco>/* Example functions - there are no anonymous functions */
<syntaxhighlight lang="draco">/* Example functions - there are no anonymous functions */
proc nonrec square(word n) word: n*n corp
proc nonrec square(word n) word: n*n corp
proc nonrec cube(word n) word: n*n*n corp
proc nonrec cube(word n) word: n*n*n corp
Line 1,147: Line 1,147:
do_func(1, 10, square);
do_func(1, 10, square);
do_func(1, 10, cube)
do_func(1, 10, cube)
corp</lang>
corp</syntaxhighlight>
{{out}}
{{out}}
<pre> 1 4 9 16 25 36 49 64 81 100
<pre> 1 4 9 16 25 36 49 64 81 100
1 8 27 64 125 216 343 512 729 1000</pre>
1 8 27 64 125 216 343 512 729 1000</pre>
=={{header|E}}==
=={{header|E}}==
<lang e>def map(f, list) {
<syntaxhighlight lang="e">def map(f, list) {
var out := []
var out := []
for x in list {
for x in list {
Line 1,168: Line 1,168:
? def foo(x) { return -(x.size()) }
? def foo(x) { return -(x.size()) }
> map(foo, ["", "a", "bc"])
> map(foo, ["", "a", "bc"])
# value: [0, -1, -2]</lang>
# value: [0, -1, -2]</syntaxhighlight>


=={{header|ECL}}==
=={{header|ECL}}==
<lang>//a Function prototype:
<syntaxhighlight lang="text">//a Function prototype:
INTEGER actionPrototype(INTEGER v1, INTEGER v2) := 0;
INTEGER actionPrototype(INTEGER v1, INTEGER v2) := 0;


Line 1,221: Line 1,221:
OUTPUT(doMany(2, applyValue4, applyValue2,multiValues));
OUTPUT(doMany(2, applyValue4, applyValue2,multiValues));
// produces "24:12"</lang>
// produces "24:12"</syntaxhighlight>


=={{header|Efene}}==
=={{header|Efene}}==


<lang efene>first = fn (F) {
<syntaxhighlight lang="efene">first = fn (F) {
F()
F()
}
}
Line 1,248: Line 1,248:
first(F2)
first(F2)
}
}
</syntaxhighlight>
</lang>


=={{header|Elena}}==
=={{header|Elena}}==
{{trans|Smalltalk}}
{{trans|Smalltalk}}
ELENA 4.1 :
ELENA 4.1 :
<lang elena>import extensions;
<syntaxhighlight lang="elena">import extensions;
public program()
public program()
Line 1,260: Line 1,260:
var second := {"second"};
var second := {"second"};
console.printLine(first(second))
console.printLine(first(second))
}</lang>
}</syntaxhighlight>
{{out}}
{{out}}
<pre>second</pre>
<pre>second</pre>


=={{header|Elixir}}==
=={{header|Elixir}}==
<lang elixir>iex(1)> defmodule RC do
<syntaxhighlight lang="elixir">iex(1)> defmodule RC do
...(1)> def first(f), do: f.()
...(1)> def first(f), do: f.()
...(1)> def second, do: :hello
...(1)> def second, do: :hello
Line 1,281: Line 1,281:
#Function<20.54118792/0 in :erl_eval.expr/5>
#Function<20.54118792/0 in :erl_eval.expr/5>
iex(5)> RC.first(f)
iex(5)> RC.first(f)
:world</lang>
:world</syntaxhighlight>


=={{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>-module(test).
<syntaxhighlight lang="erlang">-module(test).
-export([first/1, second/0]).
-export([first/1, second/0]).


first(F) -> F().
first(F) -> F().
second() -> hello.</lang>
second() -> hello.</syntaxhighlight>
Testing it:
Testing it:
<lang erlang>1> c(tests).
<syntaxhighlight lang="erlang">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</lang>
anonymous_function</syntaxhighlight>


=={{header|ERRE}}==
=={{header|ERRE}}==
ERRE function are limited to one-line FUNCTION, but you can write:
ERRE function are limited to one-line FUNCTION, but you can write:
<syntaxhighlight lang="erre">
<lang ERRE>
PROGRAM FUNC_PASS
PROGRAM FUNC_PASS


Line 1,315: Line 1,315:
PRINT(TWO(10,11))
PRINT(TWO(10,11))
END PROGRAM
END PROGRAM
</syntaxhighlight>
</lang>
Answer is 442
Answer is 442


=={{header|Euler Math Toolbox}}==
=={{header|Euler Math Toolbox}}==


<syntaxhighlight lang="euler math toolbox">
<lang Euler Math Toolbox>
>function f(x,a) := x^a-a^x
>function f(x,a) := x^a-a^x
>function dof (f$:string,x) := f$(x,args());
>function dof (f$:string,x) := f$(x,args());
Line 1,326: Line 1,326:
[ -1 0 1 0 -7 ]
[ -1 0 1 0 -7 ]
>plot2d("f",1,5;2):
>plot2d("f",1,5;2):
</syntaxhighlight>
</lang>


=={{header|Euphoria}}==
=={{header|Euphoria}}==
<lang euphoria>procedure use(integer fi, integer a, integer b)
<syntaxhighlight lang="euphoria">procedure use(integer fi, integer a, integer b)
print(1,call_func(fi,{a,b}))
print(1,call_func(fi,{a,b}))
end procedure
end procedure
Line 1,337: Line 1,337:
end function
end function


use(routine_id("add"),23,45)</lang>
use(routine_id("add"),23,45)</syntaxhighlight>


=={{header|F Sharp|F#}}==
=={{header|F Sharp|F#}}==
We define a function that takes another function f as an argument and applies that function twice to the argument x:
We define a function that takes another function f as an argument and applies that function twice to the argument x:
<lang fsharp>> let twice f x = f (f x);;
<syntaxhighlight lang="fsharp">> let twice f x = f (f x);;


val twice : ('a -> 'a) -> 'a -> 'a
val twice : ('a -> 'a) -> 'a -> 'a


> twice System.Math.Sqrt 81.0;;
> twice System.Math.Sqrt 81.0;;
val it : float = 3.0</lang>
val it : float = 3.0</syntaxhighlight>


Another example, using an operator as a function:
Another example, using an operator as a function:
<lang fsharp>> List.map2 (+) [1;2;3] [3;2;1];;
<syntaxhighlight lang="fsharp">> List.map2 (+) [1;2;3] [3;2;1];;
val it : int list = [4; 4; 4]</lang>
val it : int list = [4; 4; 4]</syntaxhighlight>


=={{header|Factor}}==
=={{header|Factor}}==
Using words (factor's functions) :
Using words (factor's functions) :
<lang factor>USING: io ;
<syntaxhighlight lang="factor">USING: io ;
IN: rosetacode
IN: rosetacode
: argument-function1 ( -- ) "Hello World!" print ;
: argument-function1 ( -- ) "Hello World!" print ;
Line 1,367: Line 1,367:
! Stack effect has to be written for runtime computed values :
! Stack effect has to be written for runtime computed values :
: calling-function3 ( bool -- ) \ argument-function1 \ argument-function2 ? execute( -- ) ;
: calling-function3 ( bool -- ) \ argument-function1 \ argument-function2 ? execute( -- ) ;
</syntaxhighlight>
</lang>


( scratchpad )
( scratchpad )
Line 1,382: Line 1,382:
=={{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 }
<syntaxhighlight 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 0 4[+]r;!." " { 10 }
1 2 3 4 1 4[*]r;!." " { 24 }
1 2 3 4 1 4[*]r;!." " { 24 }
1 2 3 4 0 4[$*+]r;!. { 30 }</lang>
1 2 3 4 0 4[$*+]r;!. { 30 }</syntaxhighlight>


=={{header|Fantom}}==
=={{header|Fantom}}==


<lang fantom>
<syntaxhighlight lang="fantom">
class Main
class Main
{
{
Line 1,405: Line 1,405:
}
}
}
}
</syntaxhighlight>
</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 * ;
<syntaxhighlight lang="forth">: square dup * ;
: cube dup dup * * ;
: cube dup dup * * ;
: map. ( xt addr len -- )
: map. ( xt addr len -- )
Line 1,418: Line 1,418:
' square array 5 map. cr \ 1 4 9 16 25
' square array 5 map. cr \ 1 4 9 16 25
' cube array 5 map. cr \ 1 8 27 64 125
' cube array 5 map. cr \ 1 8 27 64 125
:noname 2* 1+ ; array 5 map. cr \ 3 5 7 9 11</lang>
:noname 2* 1+ ; array 5 map. cr \ 3 5 7 9 11</syntaxhighlight>


=={{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>FUNCTION FUNC3(FUNC1, FUNC2, x, y)
<syntaxhighlight lang="fortran">FUNCTION FUNC3(FUNC1, FUNC2, x, y)
REAL, EXTERNAL :: FUNC1, FUNC2
REAL, EXTERNAL :: FUNC1, FUNC2
REAL :: FUNC3
REAL :: FUNC3
Line 1,429: Line 1,429:


FUNC3 = FUNC1(x) * FUNC2(y)
FUNC3 = FUNC1(x) * FUNC2(y)
END FUNCTION FUNC3</lang>
END FUNCTION FUNC3</syntaxhighlight>


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:


<lang fortran>module FuncContainer
<syntaxhighlight lang="fortran">module FuncContainer
implicit none
implicit none
contains
contains
Line 1,482: Line 1,482:
end subroutine asubroutine
end subroutine asubroutine


end program FuncArg</lang>
end program FuncArg</syntaxhighlight>


=={{header|FreeBASIC}}==
=={{header|FreeBASIC}}==
<lang freebasic>' FB 1.05.0 Win64
<syntaxhighlight lang="freebasic">' FB 1.05.0 Win64


Function square(n As Integer) As Integer
Function square(n As Integer) As Integer
Line 1,507: Line 1,507:
Print
Print
Print "Press any key to quit"
Print "Press any key to quit"
Sleep</lang>
Sleep</syntaxhighlight>


{{out}}
{{out}}
Line 1,518: Line 1,518:
The following defines an anonymous function and passes it to another function. In this case, the anonymous function is a comparison function that sorts by string length.
The following defines an anonymous function and passes it to another function. In this case, the anonymous function is a comparison function that sorts by string length.


<lang frink>
<syntaxhighlight lang="frink">
cmpFunc = {|a,b| length[a] <=> length[b]}
cmpFunc = {|a,b| length[a] <=> length[b]}


a = ["tree", "apple", "bee", "monkey", "z"]
a = ["tree", "apple", "bee", "monkey", "z"]
sort[a, cmpFunc]
sort[a, cmpFunc]
</syntaxhighlight>
</lang>


You can also look up functions by name and number of arguments. The following is equivalent to the previous example.
You can also look up functions by name and number of arguments. The following is equivalent to the previous example.


<lang frink>
<syntaxhighlight lang="frink">
lengthCompare[a,b] := length[a] <=> length[b]
lengthCompare[a,b] := length[a] <=> length[b]


Line 1,533: Line 1,533:
a = ["tree", "apple", "bee", "monkey", "z"]
a = ["tree", "apple", "bee", "monkey", "z"]
sort[a, func]
sort[a, func]
</syntaxhighlight>
</lang>


=={{header|FutureBasic}}==
=={{header|FutureBasic}}==
<lang futurebasic>window 1
<syntaxhighlight lang="futurebasic">window 1


dim as pointer functionOneAddress
dim as pointer functionOneAddress
Line 1,547: Line 1,547:
print fn FunctionTwo( 12, 12 )
print fn FunctionTwo( 12, 12 )


HandleEvents</lang>
HandleEvents</syntaxhighlight>


Output:
Output:
Line 1,563: Line 1,563:


=={{header|GAP}}==
=={{header|GAP}}==
<lang gap>Eval := function(f, x)
<syntaxhighlight lang="gap">Eval := function(f, x)
return f(x);
return f(x);
end;
end;


Eval(x -> x^3, 7);
Eval(x -> x^3, 7);
# 343</lang>
# 343</syntaxhighlight>


=={{header|Go}}==
=={{header|Go}}==
<lang go>package main
<syntaxhighlight lang="go">package main
import "fmt"
import "fmt"


func func1(f func(string) string) string { return f("a string") }
func func1(f func(string) string) string { return f("a string") }
func func2(s string) string { return "func2 called with " + s }
func func2(s string) string { return "func2 called with " + s }
func main() { fmt.Println(func1(func2)) }</lang>
func main() { fmt.Println(func1(func2)) }</syntaxhighlight>


=={{header|Groovy}}==
=={{header|Groovy}}==
As [[closures]]:
As [[closures]]:
<lang groovy>first = { func -> func() }
<syntaxhighlight lang="groovy">first = { func -> func() }
second = { println "second" }
second = { println "second" }


first(second)</lang>
first(second)</syntaxhighlight>


As functions:
As functions:
<lang groovy>def first(func) { func() }
<syntaxhighlight lang="groovy">def first(func) { func() }
def second() { println "second" }
def second() { println "second" }


first(this.&second)</lang>
first(this.&second)</syntaxhighlight>


=={{header|Haskell}}==
=={{header|Haskell}}==
Line 1,595: Line 1,595:


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"
<syntaxhighlight lang="haskell">func1 f = f "a string"
func2 s = "func2 called with " ++ s
func2 s = "func2 called with " ++ s


main = putStrLn $ func1 func2</lang>
main = putStrLn $ func1 func2</syntaxhighlight>
Or, with an anonymous function:
Or, with an anonymous function:
<lang haskell>func f = f 1 2
<syntaxhighlight lang="haskell">func f = f 1 2


main = print $ func (\x y -> x+y)
main = print $ func (\x y -> x+y)
-- output: 3</lang>
-- output: 3</syntaxhighlight>
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}} and {{header|Unicon}}==
=={{header|Icon}} and {{header|Unicon}}==
<lang icon> procedure main()
<syntaxhighlight lang="icon"> procedure main()
local lst
local lst
lst := [10, 20, 30, 40]
lst := [10, 20, 30, 40]
Line 1,619: Line 1,619:
procedure callback(arg)
procedure callback(arg)
write("->", arg)
write("->", arg)
end</lang>
end</syntaxhighlight>


=={{header|Inform 6}}==
=={{header|Inform 6}}==
As in C, functions in Inform 6 are not first-class, but pointers to functions can be used.
As in C, functions in Inform 6 are not first-class, but pointers to functions can be used.
<lang Inform6>[ func;
<syntaxhighlight lang="inform6">[ func;
print "Hello^";
print "Hello^";
];
];
Line 1,633: Line 1,633:
[ Main;
[ Main;
call_func(func);
call_func(func);
];</lang>
];</syntaxhighlight>


=={{header|Inform 7}}==
=={{header|Inform 7}}==
Phrases usually aren't defined with names, only with invocation syntax. A phrase must be given a name (here, "addition" and "multiplication") in order to be passed as a phrase value.
Phrases usually aren't defined with names, only with invocation syntax. A phrase must be given a name (here, "addition" and "multiplication") in order to be passed as a phrase value.
<lang inform7>Higher Order Functions is a room.
<syntaxhighlight lang="inform7">Higher Order Functions is a room.


To decide which number is (N - number) added to (M - number) (this is addition):
To decide which number is (N - number) added to (M - number) (this is addition):
Line 1,651: Line 1,651:
demonstrate addition as "Add";
demonstrate addition as "Add";
demonstrate multiplication as "Mul";
demonstrate multiplication as "Mul";
end the story.</lang>
end the story.</syntaxhighlight>


=={{header|J}}==
=={{header|J}}==
Line 1,657: Line 1,657:
''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>(atop), <tt> & </tt>(bond or compose) and <tt> ^: </tt>(power) are conjunctions. 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>(atop), <tt> & </tt>(bond or compose) and <tt> ^: </tt>(power) are conjunctions. The following expressions illustrate their workings.


<lang j> + / 3 1 4 1 5 9 NB. sum
<syntaxhighlight lang="j"> + / 3 1 4 1 5 9 NB. sum
23
23
>./ 3 1 4 1 5 9 NB. max
>./ 3 1 4 1 5 9 NB. max
Line 1,687: Line 1,687:
1 1.5 1.41667 1.41422 1.41421
1 1.5 1.41667 1.41422 1.41421
f^:(i.5) 1x NB. rational approximations to sqrt 2
f^:(i.5) 1x NB. rational approximations to sqrt 2
1 3r2 17r12 577r408 665857r470832</lang>
1 3r2 17r12 577r408 665857r470832</syntaxhighlight>


Adverbs and conjunctions may also be user defined
Adverbs and conjunctions may also be user defined


<lang J> + conjunction def 'u' -
<syntaxhighlight lang="j"> + conjunction def 'u' -
+
+
+ conjunction def 'v' -
+ conjunction def 'v' -
Line 1,698: Line 1,698:
110
110
^ conjunction def '10 v 2 u y' * 11
^ conjunction def '10 v 2 u y' * 11
20480</lang>
20480</syntaxhighlight>


=={{header|Java}}==
=={{header|Java}}==
Line 1,704: Line 1,704:
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>public class NewClass {
<syntaxhighlight lang="java">public class NewClass {
public NewClass() {
public NewClass() {
Line 1,729: Line 1,729:
interface AnEventOrCallback {
interface AnEventOrCallback {
public void call();
public void call();
}</lang>
}</syntaxhighlight>


From Java 8, lambda expressions may be used. Example (from Oracle):
From Java 8, lambda expressions may be used. Example (from Oracle):
<lang java>public class ListenerTest {
<syntaxhighlight lang="java">public class ListenerTest {
public static void main(String[] args) {
public static void main(String[] args) {
JButton testButton = new JButton("Test Button");
JButton testButton = new JButton("Test Button");
Line 1,750: Line 1,750:
frame.setVisible(true);
frame.setVisible(true);
}
}
}</lang>
}</syntaxhighlight>


=={{header|JavaScript}}==
=={{header|JavaScript}}==


<lang javascript>function first (func) {
<syntaxhighlight lang="javascript">function first (func) {
return func();
return func();
}
}
Line 1,763: Line 1,763:


var result = first(second);
var result = first(second);
result = first(function () { return "third"; });</lang>
result = first(function () { return "third"; });</syntaxhighlight>


An example with anonymous functions and uses in the core library
An example with anonymous functions and uses in the core library
Line 1,769: Line 1,769:
{{works with|Firefox|1.5}} for methods <code>filter</code> and <code>map</code>.
{{works with|Firefox|1.5}} for methods <code>filter</code> and <code>map</code>.


<lang javascript>>>> var array = [2, 4, 5, 13, 18, 24, 34, 97];
<syntaxhighlight lang="javascript">>>> var array = [2, 4, 5, 13, 18, 24, 34, 97];
>>> array
>>> array
[2, 4, 5, 13, 18, 24, 34, 97]
[2, 4, 5, 13, 18, 24, 34, 97]
Line 1,795: Line 1,795:
// sort the array from largest to smallest
// sort the array from largest to smallest
>>> array.sort(function (a, b) { return a < b });
>>> array.sort(function (a, b) { return a < b });
[97, 34, 24, 18, 13, 5, 4, 2]</lang>
[97, 34, 24, 18, 13, 5, 4, 2]</syntaxhighlight>


=={{header|Joy}}==
=={{header|Joy}}==
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.
<syntaxhighlight lang=Joy>DEFINE first == *.</syntaxhighlight>
<syntaxhighlight lang="joy">DEFINE first == *.</syntaxhighlight>
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.
<syntaxhighlight lang=Joy>DEFINE second == i.</syntaxhighlight>
<syntaxhighlight lang="joy">DEFINE second == i.</syntaxhighlight>
Pass first enclosed in quotes to second.
Pass first enclosed in quotes to second.
<syntaxhighlight lang=Joy>2 3 [first] second.</syntaxhighlight>
<syntaxhighlight lang="joy">2 3 [first] second.</syntaxhighlight>
The program prints 6.
The program prints 6.


Line 1,818: Line 1,818:


====Example 1: "hello blue world"====
====Example 1: "hello blue world"====
<lang jq>def foo( filter ):
<syntaxhighlight lang="jq">def foo( filter ):
("world" | filter) as $str
("world" | filter) as $str
| "hello \($str)" ;
| "hello \($str)" ;
Line 1,826: Line 1,826:


foo( blue ) # prints "hello blue world"
foo( blue ) # prints "hello blue world"
</syntaxhighlight>
</lang>
====Example 2: g(add; 2; 3)====
====Example 2: g(add; 2; 3)====
<syntaxhighlight lang="jq">
<lang jq>
def g(f; x; y): [x,y] | f;
def g(f; x; y): [x,y] | f;


g(add; 2; 3) # => 5</lang>
g(add; 2; 3) # => 5</syntaxhighlight>
====Example: Built-in higher-order functions====
====Example: Built-in higher-order functions====
In the following sequence of interactions, we pass the function *is_even/0* to some built-in higher order functions. *is_even/0* is defined as follows:
In the following sequence of interactions, we pass the function *is_even/0* to some built-in higher order functions. *is_even/0* is defined as follows:
<lang jq>def is_even:
<syntaxhighlight lang="jq">def is_even:
if floor == . then (. % 2) == 0
if floor == . then (. % 2) == 0
else error("is_even expects its input to be an integer")
else error("is_even expects its input to be an integer")
end;</lang><lang jq>
end;</syntaxhighlight><syntaxhighlight lang="jq">
# Are all integers between 1 and 5 even?
# Are all integers between 1 and 5 even?
# For this example, we will use all/2 even
# For this example, we will use all/2 even
Line 1,863: Line 1,863:
false
false
true
true
false</lang>
false</syntaxhighlight>


=={{header|Julia}}==
=={{header|Julia}}==


<syntaxhighlight lang="julia">
<lang Julia>
function foo(x)
function foo(x)
str = x("world")
str = x("world")
Line 1,873: Line 1,873:
end
end
foo(y -> "blue $y") # prints "hello blue world"
foo(y -> "blue $y") # prints "hello blue world"
</syntaxhighlight>
</lang>


The above code snippet defines a named function, <tt>foo</tt>, which takes a single argument, which is a <tt>Function</tt>.
The above code snippet defines a named function, <tt>foo</tt>, which takes a single argument, which is a <tt>Function</tt>.
Line 1,879: Line 1,879:
In the final line, <tt>foo</tt> is called with an anonymous function that takes a string, and returns a that string with <tt>"blue "</tt> preppended to it.
In the final line, <tt>foo</tt> is called with an anonymous function that takes a string, and returns a that string with <tt>"blue "</tt> preppended to it.


<syntaxhighlight lang="julia">
<lang Julia>
function g(x,y,z)
function g(x,y,z)
x(y,z)
x(y,z)
end
end
println(g(+,2,3)) # prints 5
println(g(+,2,3)) # prints 5
</syntaxhighlight>
</lang>


This code snippet defines a named function <tt>g</tt> that takes three arguments: <tt>x</tt> is a function to call, and <tt>y</tt> and <tt>z</tt> are the values to call <tt>x</tt> on.
This code snippet defines a named function <tt>g</tt> that takes three arguments: <tt>x</tt> is a function to call, and <tt>y</tt> and <tt>z</tt> are the values to call <tt>x</tt> on.
Line 1,890: Line 1,890:


In the following interactive session, we pass the function iseven to a few higher order functions. The function iseven returns true if its argument is an even integer, false if it is an odd integer, and throws an error otherwise. The second argument to the functions is a range of integers, specifically the five integers between 1 and 5 included.
In the following interactive session, we pass the function iseven to a few higher order functions. The function iseven returns true if its argument is an even integer, false if it is an odd integer, and throws an error otherwise. The second argument to the functions is a range of integers, specifically the five integers between 1 and 5 included.
<lang julia>julia> all(iseven, 1:5) # not all integers between 1 and 5 are even.
<syntaxhighlight lang="julia">julia> all(iseven, 1:5) # not all integers between 1 and 5 are even.
false
false


Line 1,911: Line 1,911:
true
true
false
false
</syntaxhighlight>
</lang>


=={{header|Klingphix}}==
=={{header|Klingphix}}==
<lang Klingphix>:+2 + 2 + ;
<syntaxhighlight lang="klingphix">:+2 + 2 + ;
:*2 * 2 * ;
:*2 * 2 * ;
Line 1,922: Line 1,922:
8 4 @*2 apply print nl
8 4 @*2 apply print nl


" " input</lang>
" " input</syntaxhighlight>


=={{header|Kotlin}}==
=={{header|Kotlin}}==
Kotlin is a functional language. Example showing how the builtin map function is used to get the average value of a transformed list of numbers:
Kotlin is a functional language. Example showing how the builtin map function is used to get the average value of a transformed list of numbers:
<lang scala>fun main(args: Array<String>) {
<syntaxhighlight lang="scala">fun main(args: Array<String>) {
val list = listOf(1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0)
val list = listOf(1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0)
val a = list.map({ x -> x + 2 }).average()
val a = list.map({ x -> x + 2 }).average()
Line 1,932: Line 1,932:
val g = list.map({ x -> x * x * x }).average()
val g = list.map({ x -> x * x * x }).average()
println("A = %f G = %f H = %f".format(a, g, h))
println("A = %f G = %f H = %f".format(a, g, h))
}</lang>
}</syntaxhighlight>


Another example showing the syntactic sugar available to Kotlin developers which allows them to put the lambda expression out of the parenthesis whenever the function is the last argument of the higher order function. Notice the usage of the inline modifier, which inlines the bytecode of the argument function on the callsite, reducing the object creation overhead (an optimization for pre Java 8 JVM environments, like Android) (translation from Scala example):
Another example showing the syntactic sugar available to Kotlin developers which allows them to put the lambda expression out of the parenthesis whenever the function is the last argument of the higher order function. Notice the usage of the inline modifier, which inlines the bytecode of the argument function on the callsite, reducing the object creation overhead (an optimization for pre Java 8 JVM environments, like Android) (translation from Scala example):
<lang scala>inline fun higherOrderFunction(x: Int, y: Int, function: (Int, Int) -> Int) = function(x, y)
<syntaxhighlight lang="scala">inline fun higherOrderFunction(x: Int, y: Int, function: (Int, Int) -> Int) = function(x, y)


fun main(args: Array<String>) {
fun main(args: Array<String>) {
val result = higherOrderFunction(3, 5) { x, y -> x + y }
val result = higherOrderFunction(3, 5) { x, y -> x + y }
println(result)
println(result)
}</lang>
}</syntaxhighlight>


{{out}}
{{out}}
Line 1,946: Line 1,946:


=={{header|Lambdatalk}}==
=={{header|Lambdatalk}}==
<syntaxhighlight lang="scheme">
<lang Scheme>
{def add
{def add
{lambda {:f :g :x}
{lambda {:f :g :x}
Line 1,959: Line 1,959:
{S.reduce + {S.serie 1 10}}
{S.reduce + {S.serie 1 10}}
-> 55
-> 55
</syntaxhighlight>
</lang>


=={{header|Lily}}==
=={{header|Lily}}==
<lang lily>define square(x: Integer): Integer
<syntaxhighlight lang="lily">define square(x: Integer): Integer
{
{
return x * x
return x * x
Line 1,987: Line 1,987:


# Calling user-defined transformation.
# Calling user-defined transformation.
print(apply("123", String.parse_i)) # Some(123)</lang>
print(apply("123", String.parse_i)) # Some(123)</syntaxhighlight>


=={{header|Lingo}}==
=={{header|Lingo}}==
Lingo doesn't support first-class functions. But functions can be passed as "symbols", and then be called via Lingo's 'call' command. Global functions - i.e. either built-in functions or user-defined functions in movie scripts - are always methods of the core '_movie' object, for other object functions (methods) also the object has to be specified. Here as example an implementation of a generic "map" function:
Lingo doesn't support first-class functions. But functions can be passed as "symbols", and then be called via Lingo's 'call' command. Global functions - i.e. either built-in functions or user-defined functions in movie scripts - are always methods of the core '_movie' object, for other object functions (methods) also the object has to be specified. Here as example an implementation of a generic "map" function:


<lang lingo>-- in some movie script
<syntaxhighlight lang="lingo">-- in some movie script
----------------------------------------
----------------------------------------
-- Runs provided function (of some object) on all elements of the provided list, returns results as new list
-- Runs provided function (of some object) on all elements of the provided list, returns results as new list
Line 2,008: Line 2,008:
end repeat
end repeat
return res
return res
end</lang>
end</syntaxhighlight>


<lang lingo>l = [1, 2, 3]
<syntaxhighlight lang="lingo">l = [1, 2, 3]


-- passes the built-in function 'sin' (which is a method of the _movie object) as argument to map
-- passes the built-in function 'sin' (which is a method of the _movie object) as argument to map
Line 2,016: Line 2,016:


put res
put res
-- [0.8415, 0.9093, 0.1411]</lang>
-- [0.8415, 0.9093, 0.1411]</syntaxhighlight>


=={{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
<syntaxhighlight lang="logo">to printstuff
print "stuff
print "stuff
end
end
Line 2,027: Line 2,027:
end
end
runstuff "printstuff ; stuff
runstuff "printstuff ; stuff
runstuff [print [also stuff]] ; also stuff</lang>
runstuff [print [also stuff]] ; also stuff</syntaxhighlight>


=={{header|Lua}}==
=={{header|Lua}}==
Lua functions are first-class:
Lua functions are first-class:
<lang lua>a = function() return 1 end
<syntaxhighlight lang="lua">a = function() return 1 end
b = function(r) print( r() ) end
b = function(r) print( r() ) end
b(a)</lang>
b(a)</syntaxhighlight>


=={{header|Luck}}==
=={{header|Luck}}==
Higher-order functions can be used to implement conditional expressions:
Higher-order functions can be used to implement conditional expressions:
<lang luck>function lambda_true(x: 'a)(y: 'a): 'a = x;;
<syntaxhighlight lang="luck">function lambda_true(x: 'a)(y: 'a): 'a = x;;
function lambda_false(x: 'a)(y: 'a): 'a = y;;
function lambda_false(x: 'a)(y: 'a): 'a = y;;
function lambda_if(c:'a -> 'a -> 'a )(t: 'a)(f: 'a): 'a = c(t)(f);;
function lambda_if(c:'a -> 'a -> 'a )(t: 'a)(f: 'a): 'a = c(t)(f);;


print( lambda_if(lambda_true)("condition was true")("condition was false") );;</lang>
print( lambda_if(lambda_true)("condition was true")("condition was false") );;</syntaxhighlight>


=={{header|M2000 Interpreter}}==
=={{header|M2000 Interpreter}}==
We can pass by reference a standard function, or we can pass by value a lambda function (also we can pass by reference as reference to lambda function)
We can pass by reference a standard function, or we can pass by value a lambda function (also we can pass by reference as reference to lambda function)
<syntaxhighlight lang="m2000 interpreter">
<lang M2000 Interpreter>
Function Foo (x) {
Function Foo (x) {
=x**2
=x**2
Line 2,062: Line 2,062:
Print Bar(&K.MulZ(), 20)=200
Print Bar(&K.MulZ(), 20)=200
Print K.Z=11
Print K.Z=11
</syntaxhighlight>
</lang>


Example using lambda function
Example using lambda function


<syntaxhighlight lang="m2000 interpreter">
<lang M2000 Interpreter>
Foo = Lambda k=1 (x)-> {
Foo = Lambda k=1 (x)-> {
k+=2
k+=2
Line 2,094: Line 2,094:
Print Bar2(&NewFoo, 20)=409
Print Bar2(&NewFoo, 20)=409


</syntaxhighlight>
</lang>


=={{header|Mathematica}} / {{header|Wolfram Language}}==
=={{header|Mathematica}} / {{header|Wolfram Language}}==
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>PassFunc[f_, g_, h_, x_] := f[g[x]*h[x]]
<syntaxhighlight lang="mathematica">PassFunc[f_, g_, h_, x_] := f[g[x]*h[x]]
PassFunc[Tan, Cos, Sin, x]
PassFunc[Tan, Cos, Sin, x]
% /. x -> 0.12
% /. x -> 0.12
PassFunc[Tan, Cos, Sin, 0.12]</lang>
PassFunc[Tan, Cos, Sin, 0.12]</syntaxhighlight>
gives back:
gives back:
<lang Mathematica>Tan[Cos[x] Sin[x]]
<syntaxhighlight lang="mathematica">Tan[Cos[x] Sin[x]]
0.119414
0.119414
0.119414</lang>
0.119414</syntaxhighlight>


=={{header|MATLAB}} / {{header|Octave}}==
=={{header|MATLAB}} / {{header|Octave}}==
<lang MATLAB> F1=@sin; % F1 refers to function sin()
<syntaxhighlight lang="matlab"> F1=@sin; % F1 refers to function sin()
F2=@cos; % F2 refers to function cos()
F2=@cos; % F2 refers to function cos()


Line 2,125: Line 2,125:
F4 = 'cos';
F4 = 'cos';
feval(F3,pi/4)
feval(F3,pi/4)
feval(F4,pi/4)</lang>
feval(F4,pi/4)</syntaxhighlight>


=={{header|Maxima}}==
=={{header|Maxima}}==
<lang maxima>callee(n) := (print(sconcat("called with ", n)), n + 1)$
<syntaxhighlight lang="maxima">callee(n) := (print(sconcat("called with ", n)), n + 1)$
caller(f, n) := sum(f(i), i, 1, n)$
caller(f, n) := sum(f(i), i, 1, n)$
caller(callee, 3);
caller(callee, 3);
"called with 1"
"called with 1"
"called with 2"
"called with 2"
"called with 3"</lang>
"called with 3"</syntaxhighlight>


=={{header|MAXScript}}==
=={{header|MAXScript}}==
<lang maxscript>fn second =
<syntaxhighlight lang="maxscript">fn second =
(
(
print "Second"
print "Second"
Line 2,146: Line 2,146:
)
)


first second</lang>
first second</syntaxhighlight>


=={{header|Metafont}}==
=={{header|Metafont}}==
Line 2,152: Line 2,152:
We can simulate this by using <code>scantokens</code>, which ''digests'' a string as if it would be a source input.
We can simulate this by using <code>scantokens</code>, which ''digests'' a string as if it would be a source input.


<lang metafont>def calcit(expr v, s) = scantokens(s & decimal v) enddef;
<syntaxhighlight lang="metafont">def calcit(expr v, s) = scantokens(s & decimal v) enddef;


t := calcit(100.4, "sind");
t := calcit(100.4, "sind");
show t;
show t;
end</lang>
end</syntaxhighlight>


=={{header|МК-61/52}}==
=={{header|МК-61/52}}==
<lang>6 ПП 04
<syntaxhighlight lang="text">6 ПП 04
П7 КПП7 В/О
П7 КПП7 В/О
1 В/О</lang>
1 В/О</syntaxhighlight>


''Note'': as the receiver of argument used register ''Р7''; the result is "1" on the indicator.
''Note'': as the receiver of argument used register ''Р7''; the result is "1" on the indicator.


=={{header|Modula-3}}==
=={{header|Modula-3}}==
<lang modula3>MODULE Proc EXPORTS Main;
<syntaxhighlight lang="modula3">MODULE Proc EXPORTS Main;


IMPORT IO;
IMPORT IO;
Line 2,184: Line 2,184:
BEGIN
BEGIN
First(Second);
First(Second);
END Proc.</lang>
END Proc.</syntaxhighlight>


=={{header|Morfa}}==
=={{header|Morfa}}==
{{trans|D}}
{{trans|D}}
<lang morfa>
<syntaxhighlight lang="morfa">
func g(a: int, b: int, f: func(int,int): int): int
func g(a: int, b: int, f: func(int,int): int): int
{
{
Line 2,201: Line 2,201:
println("Multiply: ", g(2, 3, func(a: int, b: int) { return a * b; }));
println("Multiply: ", g(2, 3, func(a: int, b: int) { return a * b; }));
}
}
</syntaxhighlight>
</lang>


=={{header|Nanoquery}}==
=={{header|Nanoquery}}==
{{trans|Python}}
{{trans|Python}}
<lang nanoquery>def first(function)
<syntaxhighlight lang="nanoquery">def first(function)
return function()
return function()
end
end
Line 2,214: Line 2,214:


result = first(second)
result = first(second)
println result</lang>
println result</syntaxhighlight>
{{out}}
{{out}}
<pre>second</pre>
<pre>second</pre>
Line 2,220: Line 2,220:
=={{header|Nemerle}}==
=={{header|Nemerle}}==
Functions must declare the types of their parameters in Nemerle. Function types in Nemerle are written ''params type'' -> ''return type'', as seen in the simple example below.
Functions must declare the types of their parameters in Nemerle. Function types in Nemerle are written ''params type'' -> ''return type'', as seen in the simple example below.
<lang Nemerle>Twice[T] (f : T -> T, x : T) : T { f(f(x)) }</lang>
<syntaxhighlight lang="nemerle">Twice[T] (f : T -> T, x : T) : T { f(f(x)) }</syntaxhighlight>


=={{header|NewLISP}}==
=={{header|NewLISP}}==
<lang NewLISP>> (define (my-multiply a b) (* a b))
<syntaxhighlight lang="newlisp">> (define (my-multiply a b) (* a b))
(lambda (a b) (* a b))
(lambda (a b) (* a b))
> (define (call-it f x y) (f x y))
> (define (call-it f x y) (f x y))
Line 2,229: Line 2,229:
> (call-it my-multiply 2 3)
> (call-it my-multiply 2 3)
6
6
</syntaxhighlight>
</lang>


=={{header|Nim}}==
=={{header|Nim}}==
<lang nim>proc first(fn: proc): auto =
<syntaxhighlight lang="nim">proc first(fn: proc): auto =
return fn()
return fn()


Line 2,238: Line 2,238:
return "second"
return "second"


echo first(second)</lang>
echo first(second)</syntaxhighlight>


=={{header|Oberon-2}}==
=={{header|Oberon-2}}==
Works with oo2c version 2
Works with oo2c version 2
<lang oberon2>
<syntaxhighlight lang="oberon2">
MODULE HOFuns;
MODULE HOFuns;
IMPORT
IMPORT
Line 2,277: Line 2,277:
PrintWords(words,Tools.AdjustRight)
PrintWords(words,Tools.AdjustRight)
END HOFuns.
END HOFuns.
</syntaxhighlight>
</lang>


=={{header|Objeck}}==
=={{header|Objeck}}==
<lang objeck>
<syntaxhighlight lang="objeck">
bundle Default {
bundle Default {
class HighOrder {
class HighOrder {
Line 2,297: Line 2,297:
}
}
}
}
</syntaxhighlight>
</lang>


=={{header|OCaml}}==
=={{header|OCaml}}==


A function is just a value that wants arguments:
A function is just a value that wants arguments:
<lang ocaml># let func1 f = f "a string";;
<syntaxhighlight lang="ocaml"># 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 2,309: Line 2,309:
# print_endline (func1 func2);;
# print_endline (func1 func2);;
func2 called with a string
func2 called with a string
- : unit = ()</lang>
- : unit = ()</syntaxhighlight>


Or, with an anonymous function:
Or, with an anonymous function:
<lang ocaml># let func f = f 1 2;;
<syntaxhighlight lang="ocaml"># 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 = ()</lang>
- : unit = ()</syntaxhighlight>
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 2,324: Line 2,324:
We can pass a function handle (<code>@function_name</code>)
We can pass a function handle (<code>@function_name</code>)


<lang octave>function r = computeit(f, g, v)
<syntaxhighlight lang="octave">function r = computeit(f, g, v)
r = f(g(v));
r = f(g(v));
endfunction
endfunction


computeit(@exp, @sin, pi/3)
computeit(@exp, @sin, pi/3)
computeit(@log, @cos, pi/6)</lang>
computeit(@log, @cos, pi/6)</syntaxhighlight>


Or pass the string name of the function and use the <code>feval</code> primitive.
Or pass the string name of the function and use the <code>feval</code> primitive.


<lang octave>function r = computeit2(f, g, v)
<syntaxhighlight lang="octave">function r = computeit2(f, g, v)
r = f(feval(g, v));
r = f(feval(g, v));
endfunction
endfunction


computeit2(@exp, "sin", pi/3)</lang>
computeit2(@exp, "sin", pi/3)</syntaxhighlight>


=={{header|Oforth}}==
=={{header|Oforth}}==
Line 2,343: Line 2,343:
If you add # before a function or method name you push the function object on the stack (instead of performing the function). This allows to pass functions to other functions, as for any other object.
If you add # before a function or method name you push the function object on the stack (instead of performing the function). This allows to pass functions to other functions, as for any other object.
Here we pass #1+ to map :
Here we pass #1+ to map :
<lang Oforth>[1, 2, 3, 4, 5 ] map(#1+)</lang>
<syntaxhighlight lang="oforth">[1, 2, 3, 4, 5 ] map(#1+)</syntaxhighlight>


=={{header|Ol}}==
=={{header|Ol}}==
<lang scheme>
<syntaxhighlight lang="scheme">
; typical use:
; typical use:
(for-each display '(1 2 "ss" '(3 4) 8))
(for-each display '(1 2 "ss" '(3 4) 8))
Line 2,356: Line 2,356:
(do print 12345)
(do print 12345)
; ==> 12345
; ==> 12345
</syntaxhighlight>
</lang>


=={{header|ooRexx}}==
=={{header|ooRexx}}==
routines are first class ooRexx objects that can be passed to other routines or methods and invoked.
routines are first class ooRexx objects that can be passed to other routines or methods and invoked.
<lang ooRexx>say callit(.routines~fib, 10)
<syntaxhighlight lang="oorexx">say callit(.routines~fib, 10)
say callit(.routines~fact, 6)
say callit(.routines~fact, 6)
say callit(.routines~square, 13)
say callit(.routines~square, 13)
Line 2,415: Line 2,415:
next = current
next = current
end
end
return current</lang>
return current</syntaxhighlight>
{{out}}
{{out}}
<pre>55
<pre>55
Line 2,429: Line 2,429:
Functions in Order can accept any other named function, local variable, or anonymous function as arguments:
Functions in Order can accept any other named function, local variable, or anonymous function as arguments:


<syntaxhighlight lang="c">
<lang C>
#include <order/interpreter.h>
#include <order/interpreter.h>


Line 2,458: Line 2,458:
)
)
// -> 16
// -> 16
</syntaxhighlight>
</lang>


The only difference between toplevel function definitions, and variables or literals, is that variables and anonymous functions must be called using the <code>8ap</code> syntactic form rather than direct argument application syntax. This is a limitation of the C preprocessor.
The only difference between toplevel function definitions, and variables or literals, is that variables and anonymous functions must be called using the <code>8ap</code> syntactic form rather than direct argument application syntax. This is a limitation of the C preprocessor.


=={{header|OxygenBasic}}==
=={{header|OxygenBasic}}==
<lang oxygenbasic>
<syntaxhighlight lang="oxygenbasic">
'FUNCTION TO BE PASSED
'FUNCTION TO BE PASSED
'=====================
'=====================
Line 2,492: Line 2,492:
print g(@f#double#double) 'result '42'
print g(@f#double#double) 'result '42'


</syntaxhighlight>
</lang>


=={{header|Oz}}==
=={{header|Oz}}==
Functions are just regular values in Oz.
Functions are just regular values in Oz.
<lang oz>declare
<syntaxhighlight lang="oz">declare
fun {Twice Function X}
fun {Twice Function X}
{Function {Function X}}
{Function {Function X}}
end
end
in
in
{Show {Twice Sqrt 81.0}} %% prints 3.0</lang>
{Show {Twice Sqrt 81.0}} %% prints 3.0</syntaxhighlight>


=={{header|PARI/GP}}==
=={{header|PARI/GP}}==
{{works with|PARI/GP|2.4.2 and above}} <!-- requires closures -->
{{works with|PARI/GP|2.4.2 and above}} <!-- requires closures -->
<lang parigp>secant_root(ff,a,b)={
<syntaxhighlight lang="parigp">secant_root(ff,a,b)={
e = eps() * 2;
e = eps() * 2;
aval=ff(a);
aval=ff(a);
Line 2,523: Line 2,523:
precision(2. >> (32 * ceil(default(realprecision) * 38539962 / 371253907)), 9)
precision(2. >> (32 * ceil(default(realprecision) * 38539962 / 371253907)), 9)
};
};
addhelp(eps,"Returns machine epsilon for the current precision.");</lang>
addhelp(eps,"Returns machine epsilon for the current precision.");</syntaxhighlight>


=={{header|Pascal}}==
=={{header|Pascal}}==
Standard Pascal (will not work with Turbo Pascal):
Standard Pascal (will not work with Turbo Pascal):
<lang pascal>program example(output);
<syntaxhighlight lang="pascal">program example(output);


function first(function f(x: real): real): real;
function first(function f(x: real): real): real;
Line 2,541: Line 2,541:
begin
begin
writeln(first(second));
writeln(first(second));
end.</lang>
end.</syntaxhighlight>


[[Turbo Pascal]] (will not work with Standard Pascal):
[[Turbo Pascal]] (will not work with Standard Pascal):


<lang pascal>program example;
<syntaxhighlight lang="pascal">program example;


type
type
Line 2,564: Line 2,564:
begin
begin
writeln(first(second));
writeln(first(second));
end.</lang>
end.</syntaxhighlight>


=== using FreePascal : Higher-order function MAP / REDUCE ( FOLDL / FOLDR ) / FILTER ===
=== using FreePascal : Higher-order function MAP / REDUCE ( FOLDL / FOLDR ) / FILTER ===
{{works with|Free Pascal|3.2.0 }}
{{works with|Free Pascal|3.2.0 }}
<syntaxhighlight lang="pascal">
<lang Pascal>
UNIT MRF;
UNIT MRF;
{$mode Delphi} {$H+} {$J-} {$R+} (*) https://www.freepascal.org/docs-html/prog/progch1.html (*)
{$mode Delphi} {$H+} {$J-} {$R+} (*) https://www.freepascal.org/docs-html/prog/progch1.html (*)
Line 3,291: Line 3,291:




</lang>JPD 2021/07/10
</syntaxhighlight>JPD 2021/07/10


Output:
Output:
Line 3,298: Line 3,298:


=={{header|Perl}}==
=={{header|Perl}}==
<lang perl>sub another {
<syntaxhighlight lang="perl">sub another {
# take a function and a value
# take a function and a value
my $func = shift;
my $func = shift;
Line 3,324: Line 3,324:
);
);


print another $dispatch{$_}, 123 for qw(square cube rev);</lang>
print another $dispatch{$_}, 123 for qw(square cube rev);</syntaxhighlight>


<lang perl>sub apply (&@) { # use & as the first item in a prototype to take bare blocks like map and grep
<syntaxhighlight 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
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
$sub->() for @ret; # it allows for simple inline application of the s/// and tr/// constructs
Line 3,333: Line 3,333:


print join ", " => apply {tr/aeiou/AEIOU/} qw/one two three four/;
print join ", " => apply {tr/aeiou/AEIOU/} qw/one two three four/;
# OnE, twO, thrEE, fOUr</lang>
# OnE, twO, thrEE, fOUr</syntaxhighlight>


<lang perl>sub first {shift->()}
<syntaxhighlight lang="perl">sub first {shift->()}


sub second {'second'}
sub second {'second'}
Line 3,341: Line 3,341:
print first \&second;
print first \&second;


print first sub{'sub'};</lang>
print first sub{'sub'};</syntaxhighlight>


=={{header|Phix}}==
=={{header|Phix}}==
{{libheader|Phix/basics}}
{{libheader|Phix/basics}}
<!--<lang Phix>(phixonline)-->
<!--<syntaxhighlight lang="phix">(phixonline)-->
<span style="color: #008080;">procedure</span> <span style="color: #000000;">use</span><span style="color: #0000FF;">(</span><span style="color: #004080;">integer</span> <span style="color: #000000;">fi</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">a</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">b</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">procedure</span> <span style="color: #000000;">use</span><span style="color: #0000FF;">(</span><span style="color: #004080;">integer</span> <span style="color: #000000;">fi</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">a</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">b</span><span style="color: #0000FF;">)</span>
<span style="color: #0000FF;">?</span><span style="color: #000000;">fi</span><span style="color: #0000FF;">(</span><span style="color: #000000;">a</span><span style="color: #0000FF;">,</span><span style="color: #000000;">b</span><span style="color: #0000FF;">)</span>
<span style="color: #0000FF;">?</span><span style="color: #000000;">fi</span><span style="color: #0000FF;">(</span><span style="color: #000000;">a</span><span style="color: #0000FF;">,</span><span style="color: #000000;">b</span><span style="color: #0000FF;">)</span>
Line 3,355: Line 3,355:
<span style="color: #000000;">use</span><span style="color: #0000FF;">(</span><span style="color: #000000;">add</span><span style="color: #0000FF;">,</span><span style="color: #000000;">23</span><span style="color: #0000FF;">,</span><span style="color: #000000;">45</span><span style="color: #0000FF;">)</span>
<span style="color: #000000;">use</span><span style="color: #0000FF;">(</span><span style="color: #000000;">add</span><span style="color: #0000FF;">,</span><span style="color: #000000;">23</span><span style="color: #0000FF;">,</span><span style="color: #000000;">45</span><span style="color: #0000FF;">)</span>
<!--</lang>-->
<!--</syntaxhighlight>-->
{{out}}
{{out}}
<pre>
<pre>
Line 3,364: Line 3,364:
The plain add, without a trailing '(' to make it a direct invocation, resolves to a symbol table index.<br>
The plain add, without a trailing '(' to make it a direct invocation, resolves to a symbol table index.<br>
Obviously you can use (an otherwise pointless) user defined type (of any name you like) instead of integer if preferred, eg
Obviously you can use (an otherwise pointless) user defined type (of any name you like) instead of integer if preferred, eg
<!--<lang Phix>-->
<!--<syntaxhighlight lang="phix">-->
<span style="color: #008080;">type</span> <span style="color: #000000;">rid</span><span style="color: #0000FF;">(</span><span style="color: #004080;">integer</span> <span style="color: #000080;font-style:italic;">/*r*/</span><span style="color: #0000FF;">)</span> <span style="color: #008080;">return</span> <span style="color: #004600;">true</span> <span style="color: #008080;">end</span> <span style="color: #008080;">type</span>
<span style="color: #008080;">type</span> <span style="color: #000000;">rid</span><span style="color: #0000FF;">(</span><span style="color: #004080;">integer</span> <span style="color: #000080;font-style:italic;">/*r*/</span><span style="color: #0000FF;">)</span> <span style="color: #008080;">return</span> <span style="color: #004600;">true</span> <span style="color: #008080;">end</span> <span style="color: #008080;">type</span>
<span style="color: #008080;">procedure</span> <span style="color: #000000;">use</span><span style="color: #0000FF;">(</span><span style="color: #000000;">rid</span> <span style="color: #000000;">fi</span><span style="color: #0000FF;">,</span> <span style="color: #004080;">integer</span> <span style="color: #000000;">a</span><span style="color: #0000FF;">,</span><span style="color: #000000;">b</span><span style="color: #0000FF;">)...</span>
<span style="color: #008080;">procedure</span> <span style="color: #000000;">use</span><span style="color: #0000FF;">(</span><span style="color: #000000;">rid</span> <span style="color: #000000;">fi</span><span style="color: #0000FF;">,</span> <span style="color: #004080;">integer</span> <span style="color: #000000;">a</span><span style="color: #0000FF;">,</span><span style="color: #000000;">b</span><span style="color: #0000FF;">)...</span>
<!--</lang>-->
<!--</syntaxhighlight>-->


=={{header|Phixmonti}}==
=={{header|Phixmonti}}==
<lang Phixmonti>def suma + enddef
<syntaxhighlight lang="phixmonti">def suma + enddef


def apply exec enddef
def apply exec enddef


23 45 getid suma apply print
23 45 getid suma apply print
</syntaxhighlight>
</lang>


=={{header|PHP}}==
=={{header|PHP}}==
<lang php>function first($func) {
<syntaxhighlight lang="php">function first($func) {
return $func();
return $func();
}
}
Line 3,387: Line 3,387:
}
}


$result = first('second');</lang>
$result = first('second');</syntaxhighlight>
Or, with an anonymous function in PHP 5.3+:
Or, with an anonymous function in PHP 5.3+:
<lang php>function first($func) {
<syntaxhighlight lang="php">function first($func) {
return $func();
return $func();
}
}


$result = first(function() { return 'second'; });</lang>
$result = first(function() { return 'second'; });</syntaxhighlight>


=={{header|Picat}}==
=={{header|Picat}}==
Here are some different approaches.
Here are some different approaches.
The following variables and functions are assumed to be defined:
The following variables and functions are assumed to be defined:
<lang Picat>go =>
<syntaxhighlight lang="picat">go =>
% ...
% ...
L = 1..10,
L = 1..10,
Line 3,418: Line 3,418:
% sort on length
% sort on length
sortf(F1,F2) =>
sortf(F1,F2) =>
F1.length < F2.length.</lang>
F1.length < F2.length.</syntaxhighlight>


===Using map===
===Using map===
<lang Picat> % ...
<syntaxhighlight lang="picat"> % ...
println(map(f1,L)),
println(map(f1,L)),
println(map($f2(3),L)),
println(map($f2(3),L)),
println(map(f2,L,map(f1,L))).</lang>
println(map(f2,L,map(f1,L))).</syntaxhighlight>


===List comprehension===
===List comprehension===
In general the recommended approach.
In general the recommended approach.
<syntaxhighlight lang="picat"> %
<lang Picat> %
println([f1(I) : I in L]),
println([f1(I) : I in L]),
println([[I,J,f2(I,J)] : I in L, J in L2]).</lang>
println([[I,J,f2(I,J)] : I in L, J in L2]).</syntaxhighlight>
===Apply===
===Apply===
<lang Picat> % ...
<syntaxhighlight lang="picat"> % ...
println(apply(+,1,2)),
println(apply(+,1,2)),
println(apply(f2,10,22)).</lang>
println(apply(f2,10,22)).</syntaxhighlight>


===Sort function===
===Sort function===
Here is an example how to sort on length.
Here is an example how to sort on length.
<lang Picat> % ...
<syntaxhighlight lang="picat"> % ...
S = [
S = [
"rosetta code",
"rosetta code",
Line 3,452: Line 3,452:
],
],
println(map(len,S)),
println(map(len,S)),
println(S.qsort(sortf)).</lang>
println(S.qsort(sortf)).</syntaxhighlight>


{{out}}
{{out}}
Line 3,466: Line 3,466:


=={{header|PicoLisp}}==
=={{header|PicoLisp}}==
<lang PicoLisp>: (de first (Fun)
<syntaxhighlight lang="picolisp">: (de first (Fun)
(Fun) )
(Fun) )
-> first
-> first
Line 3,498: Line 3,498:


: (mapcar add (1 2 3) (4 5 6))
: (mapcar add (1 2 3) (4 5 6))
-> (5 7 9)</lang>
-> (5 7 9)</syntaxhighlight>


=={{header|PL/I}}==
=={{header|PL/I}}==
<syntaxhighlight lang="pl/i">
<lang PL/I>
f: procedure (g) returns (float);
f: procedure (g) returns (float);
declare g entry (float);
declare g entry (float);
Line 3,510: Line 3,510:


x = f(p); /* where "p" is the name of a function. */
x = f(p); /* where "p" is the name of a function. */
</syntaxhighlight>
</lang>


=={{header|Pop11}}==
=={{header|Pop11}}==
<lang pop11>;;; Define a function
<syntaxhighlight lang="pop11">;;; Define a function
define x_times_three_minus_1(x);
define x_times_three_minus_1(x);
return(3*x-1);
return(3*x-1);
Line 3,519: Line 3,519:


;;; Pass it as argument to built-in function map and print the result
;;; 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>
mapdata({0 1 2 3 4}, x_times_three_minus_1) =></syntaxhighlight>


=={{header|PostScript}}==
=={{header|PostScript}}==
Postscript functions are either built-in operators or executable arrays (procedures). Both can take either as arguments.
Postscript functions are either built-in operators or executable arrays (procedures). Both can take either as arguments.
<lang>
<syntaxhighlight lang="text">
% operator example
% operator example
% 'ifelse' is passed a boolean and two procedures
% 'ifelse' is passed a boolean and two procedures
Line 3,534: Line 3,534:
/bar { (Hello, world!) } def
/bar { (Hello, world!) } def
/bar load foo ==
/bar load foo ==
</syntaxhighlight>
</lang>


=={{header|PowerShell}}==
=={{header|PowerShell}}==
{{works with|PowerShell|4.0}}
{{works with|PowerShell|4.0}}
<syntaxhighlight lang="powershell">
<lang PowerShell>
function f ($y) {
function f ($y) {
$y*$y
$y*$y
Line 3,545: Line 3,545:
(f $y)
(f $y)
}
}
</syntaxhighlight>
</lang>


You can implement a function inside a function.
You can implement a function inside a function.


<syntaxhighlight lang="powershell">
<lang PowerShell>
function g2($y) {
function g2($y) {
function f2($y) {
function f2($y) {
Line 3,556: Line 3,556:
(f2 $y)
(f2 $y)
}
}
</syntaxhighlight>
</lang>
<b>Calling:</b>
<b>Calling:</b>
<syntaxhighlight lang="powershell">
<lang PowerShell>
g f 5
g f 5
g2 9
g2 9
</syntaxhighlight>
</lang>
<b>Output:</b>
<b>Output:</b>
<pre>
<pre>
Line 3,569: Line 3,569:


=={{header|Prolog}}==
=={{header|Prolog}}==
<lang prolog>
<syntaxhighlight lang="prolog">
first(Predicate) :- call(Predicate).
first(Predicate) :- call(Predicate).
second(Argument) :- write(Argument).
second(Argument) :- write(Argument).


:-first(second('Hello World!')).
:-first(second('Hello World!')).
</syntaxhighlight>
</lang>


=={{header|PureBasic}}==
=={{header|PureBasic}}==
<lang PureBasic>Prototype.d func(*text$)
<syntaxhighlight lang="purebasic">Prototype.d func(*text$)


Procedure NumberTwo(arg$)
Procedure NumberTwo(arg$)
Line 3,588: Line 3,588:
EndProcedure
EndProcedure


NumberOne(@NumberTwo(),"Hello Worldy!")</lang>
NumberOne(@NumberTwo(),"Hello Worldy!")</syntaxhighlight>


=={{header|Python}}==
=={{header|Python}}==
{{works with|Python|2.5}}
{{works with|Python|2.5}}


<lang python>def first(function):
<syntaxhighlight lang="python">def first(function):
return function()
return function()


Line 3,599: Line 3,599:
return "second"
return "second"


result = first(second)</lang>
result = first(second)</syntaxhighlight>


or
or


<lang python> result = first(lambda: "second")</lang>
<syntaxhighlight lang="python"> result = first(lambda: "second")</syntaxhighlight>


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.
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.
Line 3,611: Line 3,611:
Its helpful to remember that in Q, when parameters aren't named in the function declaration, <tt>x</tt> is assumed to be the first parameter.
Its helpful to remember that in Q, when parameters aren't named in the function declaration, <tt>x</tt> is assumed to be the first parameter.


<syntaxhighlight lang="q">
<lang Q>
q)sayHi:{-1"Hello ",x;}
q)sayHi:{-1"Hello ",x;}
q)callFuncWithParam:{x["Peter"]}
q)callFuncWithParam:{x["Peter"]}
Line 3,617: Line 3,617:
Hello Peter
Hello Peter
q)callFuncWithParam[sayHi]
q)callFuncWithParam[sayHi]
Hello Peter</lang>
Hello Peter</syntaxhighlight>


=={{header|Quackery}}==
=={{header|Quackery}}==
Line 3,682: Line 3,682:


=={{header|R}}==
=={{header|R}}==
<lang R>f <- function(f0) f0(pi) # calc. the function in pi
<syntaxhighlight lang="r">f <- function(f0) f0(pi) # calc. the function in pi
tf <- function(x) x^pi # a func. just to test
tf <- function(x) x^pi # a func. just to test


print(f(sin))
print(f(sin))
print(f(cos))
print(f(cos))
print(f(tf))</lang>
print(f(tf))</syntaxhighlight>


=={{header|Racket}}==
=={{header|Racket}}==
<syntaxhighlight lang="racket">
<lang Racket>
#lang racket/base
#lang racket/base
(define (add f g x)
(define (add f g x)
(+ (f x) (g x)))
(+ (f x) (g x)))
(add sin cos 10)
(add sin cos 10)
</syntaxhighlight>
</lang>


=={{header|Raku}}==
=={{header|Raku}}==
Line 3,705: Line 3,705:
either a bare block, or a parametrized block introduced with <tt>-></tt>, which serves as a "lambda":
either a bare block, or a parametrized block introduced with <tt>-></tt>, which serves as a "lambda":


<lang perl6>sub twice(&todo) {
<syntaxhighlight lang="raku" line>sub twice(&todo) {
todo(); todo(); # declaring &todo also defines bare function
todo(); todo(); # declaring &todo also defines bare function
}
}
Line 3,721: Line 3,721:
# output:
# output:
# 1: Hello!
# 1: Hello!
# 2: Hello!</lang>
# 2: Hello!</syntaxhighlight>


=={{header|Raven}}==
=={{header|Raven}}==
This is not strictly passing a function, but the string representing the function name.
This is not strictly passing a function, but the string representing the function name.
<lang Raven>define doit use $v1
<syntaxhighlight lang="raven">define doit use $v1
"doit called with " print $v1 print "\n" print
"doit called with " print $v1 print "\n" print


Line 3,732: Line 3,732:
$v2 call
$v2 call


23.54 "doit" callit</lang>
23.54 "doit" callit</syntaxhighlight>
{{out}}
{{out}}
<pre>callit called with doit
<pre>callit called with doit
Line 3,739: Line 3,739:


=={{header|REBOL}}==
=={{header|REBOL}}==
<lang REBOL>REBOL [
<syntaxhighlight lang="rebol">REBOL [
Title: "Function Argument"
Title: "Function Argument"
URL: http://rosettacode.org/wiki/Function_as_an_Argument
URL: http://rosettacode.org/wiki/Function_as_an_Argument
Line 3,768: Line 3,768:
print ["Squared:" mold map :square x]
print ["Squared:" mold map :square x]
print ["Cubed: " mold map :cube x]
print ["Cubed: " mold map :cube x]
print ["Unnamed:" mold map func [i][i * 2 + 1] x]</lang>
print ["Unnamed:" mold map func [i][i * 2 + 1] x]</syntaxhighlight>


Output:
Output:
Line 3,778: Line 3,778:


=={{header|Retro}}==
=={{header|Retro}}==
<lang Retro>:disp (nq-) call n:put ;
<syntaxhighlight lang="retro">:disp (nq-) call n:put ;


#31 [ (n-n) #100 * ] disp
#31 [ (n-n) #100 * ] disp
</syntaxhighlight>
</lang>


=={{header|REXX}}==
=={{header|REXX}}==
<lang rexx>/*REXX program demonstrates the passing of a name of a function to another function. */
<syntaxhighlight lang="rexx">/*REXX program demonstrates the passing of a name of a function to another function. */
call function 'fact' , 6; say right( 'fact{'$"} = ", 30) result
call function 'fact' , 6; say right( 'fact{'$"} = ", 30) result
call function 'square' , 13; say right( 'square{'$"} = ", 30) result
call function 'square' , 13; say right( 'square{'$"} = ", 30) result
Line 3,795: Line 3,795:
function: arg ?.; parse arg ,$; signal value (?.)
function: arg ?.; parse arg ,$; signal value (?.)
reverse: return 'REVERSE'($)
reverse: return 'REVERSE'($)
square: return $**2</lang>
square: return $**2</syntaxhighlight>
{{out|output|text=&nbsp; when using the default input:}}
{{out|output|text=&nbsp; when using the default input:}}
<pre>
<pre>
Line 3,805: Line 3,805:


=={{header|Ring}}==
=={{header|Ring}}==
<lang ring>
<syntaxhighlight lang="ring">
# Project : Higher-order functions
# Project : Higher-order functions


Line 3,824: Line 3,824:
next
next
see nl
see nl
</syntaxhighlight>
</lang>
Output:
Output:
<pre>
<pre>
Line 3,854: Line 3,854:
=={{header|Ruby}}==
=={{header|Ruby}}==
With a proc (procedure):
With a proc (procedure):
<lang ruby>succ = proc{|x| x+1}
<syntaxhighlight lang="ruby">succ = proc{|x| x+1}
def to2(&f)
def to2(&f)
f[2]
f[2]
Line 3,860: Line 3,860:


to2(&succ) #=> 3
to2(&succ) #=> 3
to2{|x| x+1} #=> 3</lang>
to2{|x| x+1} #=> 3</syntaxhighlight>
With a method:
With a method:
<lang ruby>def succ(n)
<syntaxhighlight lang="ruby">def succ(n)
n+1
n+1
end
end
Line 3,871: Line 3,871:


meth = method(:succ)
meth = method(:succ)
to2(meth) #=> 3</lang>
to2(meth) #=> 3</syntaxhighlight>


=={{header|Rust}}==
=={{header|Rust}}==
Functions are first class values and identified in the type system by implementing the FnOnce, FnMut or the Fn trait which happens implicitly for functions and closures.
Functions are first class values and identified in the type system by implementing the FnOnce, FnMut or the Fn trait which happens implicitly for functions and closures.
<lang rust>fn execute_with_10<F: Fn(u64) -> u64> (f: F) -> u64 {
<syntaxhighlight lang="rust">fn execute_with_10<F: Fn(u64) -> u64> (f: F) -> u64 {
f(10)
f(10)
}
}
Line 3,886: Line 3,886:
println!("{}", execute_with_10(|n| n*n )); // closure
println!("{}", execute_with_10(|n| n*n )); // closure
println!("{}", execute_with_10(square)); // function
println!("{}", execute_with_10(square)); // function
}</lang>
}</syntaxhighlight>
{{out}}
{{out}}
<pre>100
<pre>100
Line 3,892: Line 3,892:


=={{header|Scala}}==
=={{header|Scala}}==
<lang scala>def functionWithAFunctionArgument(x : int, y : int, f : (int, int) => int) = f(x,y)</lang>
<syntaxhighlight lang="scala">def functionWithAFunctionArgument(x : int, y : int, f : (int, int) => int) = f(x,y)</syntaxhighlight>
Call:
Call:
<lang scala>functionWithAFunctionArgument(3, 5, {(x, y) => x + y}) // returns 8</lang>
<syntaxhighlight lang="scala">functionWithAFunctionArgument(3, 5, {(x, y) => x + y}) // returns 8</syntaxhighlight>


=={{header|Scheme}}==
=={{header|Scheme}}==


A function is just a value that wants arguments:
A function is just a value that wants arguments:
<lang scheme>> (define (func1 f) (f "a string"))
<syntaxhighlight lang="scheme">> (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</lang>
func2 called with a string</syntaxhighlight>


Or, with an anonymous function:
Or, with an anonymous function:
<lang scheme>> (define (func f) (f 1 2))
<syntaxhighlight lang="scheme">> (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</syntaxhighlight>
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|SenseTalk}}==
=={{header|SenseTalk}}==
<lang sensetalk>function Map oldlist, func
<syntaxhighlight lang="sensetalk">function Map oldlist, func
put () into newlist
put () into newlist
repeat with each item of oldlist
repeat with each item of oldlist
Line 3,917: Line 3,917:
end repeat
end repeat
return newlist
return newlist
end Map</lang>
end Map</syntaxhighlight>


<lang sensetalk>put ("tomato", "aubergine", "courgette") into fruits
<syntaxhighlight lang="sensetalk">put ("tomato", "aubergine", "courgette") into fruits
put Map(fruits, Uppercase)
put Map(fruits, Uppercase)
</syntaxhighlight>
</lang>


=={{header|Sidef}}==
=={{header|Sidef}}==
<lang ruby>func first(f) {
<syntaxhighlight lang="ruby">func first(f) {
return f();
return f();
}
}
Line 3,933: Line 3,933:


say first(second); # => "second"
say first(second); # => "second"
say first(func { "third" }); # => "third"</lang>
say first(func { "third" }); # => "third"</syntaxhighlight>


=={{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>define: #function -> [| :x | x * 3 - 1].
<syntaxhighlight lang="slate">define: #function -> [| :x | x * 3 - 1].
#(1 1 2 3 5 8) collect: function.</lang>
#(1 1 2 3 5 8) collect: function.</syntaxhighlight>


=={{header|Smalltalk}}==
=={{header|Smalltalk}}==


<lang Smalltalk>first := [ :f | f value ].
<syntaxhighlight lang="smalltalk">first := [ :f | f value ].
second := [ 'second' ].
second := [ 'second' ].
Transcript show: (first value: second).</lang>
Transcript show: (first value: second).</syntaxhighlight>
<lang Smalltalk>function := [:x | x * 3 - 1].
<syntaxhighlight lang="smalltalk">function := [:x | x * 3 - 1].
#(1 1 2 3 5 8) collect: function.</lang>
#(1 1 2 3 5 8) collect: function.</syntaxhighlight>


=={{header|Sparkling}}==
=={{header|Sparkling}}==
<lang sparkling>function call_me(func, arg) {
<syntaxhighlight lang="sparkling">function call_me(func, arg) {
return func(arg);
return func(arg);
}
}


let answer = call_me(function(x) { return 6 * x; }, 7);
let answer = call_me(function(x) { return 6 * x; }, 7);
print(answer);</lang>
print(answer);</syntaxhighlight>


=={{header|Standard ML}}==
=={{header|Standard ML}}==


<lang sml>- fun func1 f = f "a string";
<syntaxhighlight lang="sml">- 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 3,965: Line 3,965:
- print (func1 func2 ^ "\n");
- print (func1 func2 ^ "\n");
func2 called with a string
func2 called with a string
val it = () : unit</lang>
val it = () : unit</syntaxhighlight>


Or, with an anonymous function:
Or, with an anonymous function:
<lang sml>- fun func f = f (1, 2);
<syntaxhighlight lang="sml">- 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</lang>
val it = () : unit</syntaxhighlight>
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.)


=={{header|SuperCollider}}==
=={{header|SuperCollider}}==
<lang SuperCollider>f = { |x, y| x.(y) }; // a function that takes a function and calls it with an argument
<syntaxhighlight lang="supercollider">f = { |x, y| x.(y) }; // a function that takes a function and calls it with an argument
f.({ |x| x + 1 }, 5); // returns 5</lang>
f.({ |x| x + 1 }, 5); // returns 5</syntaxhighlight>


=={{header|Swift}}==
=={{header|Swift}}==
<lang swift>func func1(f: String->String) -> String { return f("a string") }
<syntaxhighlight lang="swift">func func1(f: String->String) -> String { return f("a string") }
func func2(s: String) -> String { return "func2 called with " + s }
func func2(s: String) -> String { return "func2 called with " + s }
println(func1(func2)) // prints "func2 called with a string"</lang>
println(func1(func2)) // prints "func2 called with a string"</syntaxhighlight>


Or, with an anonymous function:
Or, with an anonymous function:
<lang swift>func func3<T>(f: (Int,Int)->T) -> T { return f(1, 2) }
<syntaxhighlight lang="swift">func func3<T>(f: (Int,Int)->T) -> T { return f(1, 2) }
println(func3 {(x, y) in x + y}) // prints "3"</lang>
println(func3 {(x, y) in x + y}) // prints "3"</syntaxhighlight>
Note that <tt>{(x, y) in x + y}</tt> can also be written as <tt>{$0 + $1}</tt> or just <tt>+</tt>.
Note that <tt>{(x, y) in x + y}</tt> can also be written as <tt>{$0 + $1}</tt> or just <tt>+</tt>.


=={{header|Tcl}}==
=={{header|Tcl}}==
<lang tcl># this procedure executes its argument:
<syntaxhighlight lang="tcl"># this procedure executes its argument:
proc demo {function} {
proc demo {function} {
$function
$function
}
}
# for example:
# for example:
demo bell</lang>
demo bell</syntaxhighlight>
It is more common to pass not just a function, but a command fragment or entire script. When used with the built-in <tt>list</tt> command (which introduces a very useful degree of quoting) this makes for a very common set of techniques when doing advanced Tcl programming.
It is more common to pass not just a function, but a command fragment or entire script. When used with the built-in <tt>list</tt> 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"
<syntaxhighlight lang="tcl"># This procedure executes its argument with an extra argument of "2"
proc demoFrag {fragment} {
proc demoFrag {fragment} {
{*}$fragment 2
{*}$fragment 2
Line 4,016: Line 4,016:
demoScript {
demoScript {
parray tcl_platform
parray tcl_platform
}</lang>
}</syntaxhighlight>


=={{header|TI-89 BASIC}}==
=={{header|TI-89 BASIC}}==
Line 4,024: Line 4,024:
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
<syntaxhighlight 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})</lang>
Disp map("sin", {0, π/6, π/4, π/3, π/2})</syntaxhighlight>


=={{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
<syntaxhighlight lang="toka">[ ." First\n" ] is first
[ invoke ] is second
[ invoke ] is second
` first second</lang>
` first second</syntaxhighlight>


=={{header|Trith}}==
=={{header|Trith}}==
Due to the homoiconic program representation and the [[concatenative]] nature of the language, higher-order functions are as simple as:
Due to the homoiconic program representation and the [[concatenative]] nature of the language, higher-order functions are as simple as:
<lang trith>: twice 2 times ;
<syntaxhighlight lang="trith">: twice 2 times ;
: hello "Hello, world!" print ;
: hello "Hello, world!" print ;
[hello] twice</lang>
[hello] twice</syntaxhighlight>


=={{header|TXR}}==
=={{header|TXR}}==
Line 4,047: Line 4,047:
<code>lambda</code> passed to <code>mapcar</code> with environment capture:
<code>lambda</code> passed to <code>mapcar</code> with environment capture:


<lang txr>@(bind a @(let ((counter 0))
<syntaxhighlight lang="txr">@(bind a @(let ((counter 0))
(mapcar (lambda (x y) (list (inc counter) x y))
(mapcar (lambda (x y) (list (inc counter) x y))
'(a b c) '(t r s))))
'(a b c) '(t r s))))
Line 4,054: Line 4,054:
@ (rep)@a:@(last)@a@(end)
@ (rep)@a:@(last)@a@(end)
@ (end)
@ (end)
@(end)</lang>
@(end)</syntaxhighlight>


<pre>1:a:t
<pre>1:a:t
Line 4,062: Line 4,062:
=={{header|uBasic/4tH}}==
=={{header|uBasic/4tH}}==
{{trans|BBC BASIC}}
{{trans|BBC BASIC}}
<lang>' Test passing a function to a function:
<syntaxhighlight lang="text">' Test passing a function to a function:
Print FUNC(_FNtwo(_FNone, 10, 11))
Print FUNC(_FNtwo(_FNone, 10, 11))
End
End
Line 4,070: Line 4,070:


' Function taking a function as an argument:
' Function taking a function as an argument:
_FNtwo Param (3) : Return (FUNC(a@ (b@, c@)))</lang>
_FNtwo Param (3) : Return (FUNC(a@ (b@, c@)))</syntaxhighlight>
{{out}}
{{out}}
<pre>441
<pre>441
Line 4,078: Line 4,078:
{{trans|Python}}
{{trans|Python}}
Functions are first-class objects in Ursa.
Functions are first-class objects in Ursa.
<lang ursa>def first (function f)
<syntaxhighlight lang="ursa">def first (function f)
return (f)
return (f)
end
end
Line 4,087: Line 4,087:


out (first second) endl console
out (first second) endl console
# "second" is output to the console</lang>
# "second" is output to the console</syntaxhighlight>


=={{header|Ursala}}==
=={{header|Ursala}}==
Line 4,095: Line 4,095:
equivalent to the given functon composed with itself.
equivalent to the given functon composed with itself.


<lang Ursala>(autocomposition "f") "x" = "f" "f" "x"</lang>
<syntaxhighlight lang="ursala">(autocomposition "f") "x" = "f" "f" "x"</syntaxhighlight>
test program:
test program:
<lang Ursala>#import flo
<syntaxhighlight lang="ursala">#import flo
#cast %e
#cast %e


example = autocomposition(sqrt) 16.0</lang>
example = autocomposition(sqrt) 16.0</syntaxhighlight>
output:
output:
<pre>2.000000e+00</pre>
<pre>2.000000e+00</pre>
Line 4,106: Line 4,106:
=={{header|V}}==
=={{header|V}}==
Define first as multiplying two numbers on stack
Define first as multiplying two numbers on stack
<lang v>[first *].</lang>
<syntaxhighlight lang="v">[first *].</syntaxhighlight>
Define second as applying the passed quote on stack
Define second as applying the passed quote on stack
<lang v>[second i].</lang>
<syntaxhighlight lang="v">[second i].</syntaxhighlight>
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>
<syntaxhighlight lang="v">2 3 [first] second</syntaxhighlight>
=6
=6


=={{header|VBA}}==
=={{header|VBA}}==
Based on the Pascal solution
Based on the Pascal solution
<lang pascal>Sub HigherOrder()
<syntaxhighlight lang="pascal">Sub HigherOrder()
Dim result As Single
Dim result As Single
result = first("second")
result = first("second")
Line 4,125: Line 4,125:
Function second(x As Single) As Single
Function second(x As Single) As Single
second = x / 2
second = x / 2
End Function</lang>
End Function</syntaxhighlight>


=={{header|Visual Basic .NET}}==
=={{header|Visual Basic .NET}}==
Line 4,139: Line 4,139:
===Named methods===
===Named methods===
{{trans|C#: Named methods}}
{{trans|C#: Named methods}}
<lang vbnet>' Delegate declaration is similar to C#.
<syntaxhighlight lang="vbnet">' Delegate declaration is similar to C#.
Delegate Function Func2(a As Integer, b As Integer) As Integer
Delegate Function Func2(a As Integer, b As Integer) As Integer


Line 4,177: Line 4,177:
Console.WriteLine("f=Div, f({0}, {1}) = {2}", a, b, [Call](div, a, b))
Console.WriteLine("f=Div, f({0}, {1}) = {2}", a, b, [Call](div, a, b))
End Sub
End Sub
End Module</lang>
End Module</syntaxhighlight>


===Lambda expressions===
===Lambda expressions===
{{trans|C#: Lambda expressions}}
{{trans|C#: Lambda expressions}}
Lambda expressions in VB.NET are similar to those in C#, except they can also explicitly specify a return type and exist as standalone "anonymous delegates". An anonymous delegate is created when a lambda expression is assigned to an implicitly typed variable (in which case the variable receives the type of the anonymous delegate) or when the target type given by context (at compile-time) is MulticastDelegate, Delegate, or Object. Anonymous delegates are derived from MulticastDelegate and are implicitly convertible to all compatible delegate types. A formal definition of delegate compatibility can be found in the language specification.
Lambda expressions in VB.NET are similar to those in C#, except they can also explicitly specify a return type and exist as standalone "anonymous delegates". An anonymous delegate is created when a lambda expression is assigned to an implicitly typed variable (in which case the variable receives the type of the anonymous delegate) or when the target type given by context (at compile-time) is MulticastDelegate, Delegate, or Object. Anonymous delegates are derived from MulticastDelegate and are implicitly convertible to all compatible delegate types. A formal definition of delegate compatibility can be found in the language specification.
<lang vbnet>Module Program
<syntaxhighlight lang="vbnet">Module Program
' Uses the System generic delegate; see C# entry for details.
' Uses the System generic delegate; see C# entry for details.
Function [Call](f As Func(Of Integer, Integer, Integer), a As Integer, b As Integer) As Integer
Function [Call](f As Func(Of Integer, Integer, Integer), a As Integer, b As Integer) As Integer
Line 4,210: Line 4,210:
Console.WriteLine("f=Div, f({0}, {1}) = {2}", a, b, [Call](anon, a, b))
Console.WriteLine("f=Div, f({0}, {1}) = {2}", a, b, [Call](anon, a, b))
End Sub
End Sub
End Module</lang>
End Module</syntaxhighlight>


=={{header|Visual Prolog}}==
=={{header|Visual Prolog}}==


<syntaxhighlight lang="prolog">
<lang Prolog>
domains
domains
intFunction = (integer In) -> integer Out procedure (i).
intFunction = (integer In) -> integer Out procedure (i).
Line 4,231: Line 4,231:
write(dotwice(addone,2)),
write(dotwice(addone,2)),
succeed().
succeed().
</syntaxhighlight>
</lang>


=={{header|Wren}}==
=={{header|Wren}}==
<lang ecmascript>var first = Fn.new { |f|
<syntaxhighlight lang="ecmascript">var first = Fn.new { |f|
System.print("first function called")
System.print("first function called")
f.call()
f.call()
Line 4,241: Line 4,241:
var second = Fn.new { System.print("second function called") }
var second = Fn.new { System.print("second function called") }


first.call(second)</lang>
first.call(second)</syntaxhighlight>


{{out}}
{{out}}
Line 4,257: Line 4,257:
In fact, it is <b>mandatory</b> to pass the IRQ handler by value on the Game Boy if your game uses hardware sprites, as during direct memory access the CPU loses the ability to access the cartridge, including code execution! Therefore, the code that initiates direct memory access must be copied to RAM from the cartridge ROM and executed from RAM. Since interrupt vectors are in ROM, the vBlank interrupt vector will immediately jump to RAM. Interrupts are disabled immediately after powering on, so we've got all the time we need to copy the interrupt handler to RAM. Once we enable IRQs, the code we copied must remain there or else the game will crash.
In fact, it is <b>mandatory</b> to pass the IRQ handler by value on the Game Boy if your game uses hardware sprites, as during direct memory access the CPU loses the ability to access the cartridge, including code execution! Therefore, the code that initiates direct memory access must be copied to RAM from the cartridge ROM and executed from RAM. Since interrupt vectors are in ROM, the vBlank interrupt vector will immediately jump to RAM. Interrupts are disabled immediately after powering on, so we've got all the time we need to copy the interrupt handler to RAM. Once we enable IRQs, the code we copied must remain there or else the game will crash.


<lang z80>org &0040 ;Game Boy's vblank IRQ goes here.
<syntaxhighlight lang="z80">org &0040 ;Game Boy's vblank IRQ goes here.
;This is not part of the standard Z80 vector table - interrupts work differently on the Game Boy.
;This is not part of the standard Z80 vector table - interrupts work differently on the Game Boy.
jp &ff80
jp &ff80
Line 4,287: Line 4,287:
pop af
pop af
reti
reti
DMACopyEnd:</lang>
DMACopyEnd:</syntaxhighlight>




Line 4,294: Line 4,294:
=={{header|zkl}}==
=={{header|zkl}}==
Everything is a first class object so
Everything is a first class object so
<lang zkl>fcn f(g){ g() } fcn g{ "Hello World!".println() }</lang>
<syntaxhighlight lang="zkl">fcn f(g){ g() } fcn g{ "Hello World!".println() }</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 4,301: Line 4,301:
</pre>
</pre>
or
or
<lang zkl>fcn f(g){ g() }
<syntaxhighlight lang="zkl">fcn f(g){ g() }
fcn(g){ g() }(fcn{ "Hello World!".println() } )</lang>
fcn(g){ g() }(fcn{ "Hello World!".println() } )</syntaxhighlight>


=={{header|ZX Spectrum Basic}}==
=={{header|ZX Spectrum Basic}}==
{{trans|BBC_BASIC}}
{{trans|BBC_BASIC}}
Input "FN " token first, then enclose it in double quotation marks.
Input "FN " token first, then enclose it in double quotation marks.
<lang zxbasic>10 DEF FN f(f$,x,y)=VAL ("FN "+f$+"("+STR$ (x)+","+STR$ (y)+")")
<syntaxhighlight lang="zxbasic">10 DEF FN f(f$,x,y)=VAL ("FN "+f$+"("+STR$ (x)+","+STR$ (y)+")")
20 DEF FN n(x,y)=(x+y)^2
20 DEF FN n(x,y)=(x+y)^2
30 PRINT FN f("n",10,11)</lang>
30 PRINT FN f("n",10,11)</syntaxhighlight>


{{omit from|GUISS}}
{{omit from|GUISS}}