Higher-order functions: Difference between revisions
(113 intermediate revisions by 40 users not shown) | |||
Line 2: | Line 2: | ||
;Task: |
;Task: |
||
Pass a function ''as an argument'' to another function. |
Pass a function ''as an argument'' to another function. |
||
Line 8: | Line 8: | ||
* [[First-class functions]] |
* [[First-class functions]] |
||
<br><br> |
<br><br> |
||
=={{header|11l}}== |
|||
{{trans|Python}} |
|||
<syntaxhighlight lang="11l">F first(function) |
|||
R function() |
|||
F second() |
|||
R ‘second’ |
|||
V result = first(second) |
|||
print(result)</syntaxhighlight> |
|||
{{out}} |
|||
<pre> |
|||
second |
|||
</pre> |
|||
=={{header|6502 Assembly}}== |
|||
For the most part, it's easier to call two functions back to back. However passing functions as arguments can still be done. |
|||
Code is called using the following macro, e.g. <code>PrintOutput #$FF,foo</code>. The printing routine is left unimplemented. |
|||
<syntaxhighlight lang="6502asm">macro PrintOutput,input,addr |
|||
; input: desired function's input |
|||
; addr: function you wish to call |
|||
LDA #<\addr ;#< represents this number's low byte |
|||
STA z_L |
|||
LDA #>\addr ;#> represents this number's high byte |
|||
STA z_H |
|||
LDA \input |
|||
JSR doPrintOutput |
|||
endm</syntaxhighlight> |
|||
<syntaxhighlight lang="6502asm">PrintOutput: |
|||
; prints the output of the function "foo" to the screen. |
|||
; input: |
|||
; A = input for the function "foo". |
|||
; z_L = contains the low byte of the memory address of "foo" |
|||
; z_H = contains the high byte of the memory address of "foo" |
|||
pha |
|||
LDA z_L |
|||
STA smc+1 ;store in the low byte of the operand |
|||
LDA z_H |
|||
STA smc+2 ;store in the high byte of the operand |
|||
pla |
|||
smc: |
|||
JSR $1234 |
|||
;uses self-modifying code to overwrite the destination with the address of the passed function. |
|||
;assuming that function ends in an RTS, execution will return to this line after the function is done. |
|||
JSR PrintAccumulator |
|||
rts</syntaxhighlight> |
|||
=={{header|68000 Assembly}}== |
|||
This trivial example shows a simple return spoof. |
|||
<syntaxhighlight lang="68000devpac">LEA foo,A0 |
|||
JSR bar |
|||
JMP * ;HALT |
|||
bar: |
|||
MOVE.L A0,-(SP) |
|||
RTS ;JMP foo |
|||
foo: |
|||
RTS ;do nothing and return. This rts retuns execution just after "JSR bar" but before "JMP *".</syntaxhighlight> |
|||
=={{header|8th}}== |
=={{header|8th}}== |
||
< |
<syntaxhighlight lang="forth"> |
||
: pass-me |
: pass-me |
||
"I was passed\n" . ; |
"I was passed\n" . ; |
||
Line 17: | 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}}== |
||
< |
<syntaxhighlight lang="actionscript">package { |
||
public class MyClass { |
public class MyClass { |
||
Line 39: | Line 109: | ||
} |
} |
||
} |
} |
||
}</ |
}</syntaxhighlight> |
||
=={{header|Ada}}== |
=={{header|Ada}}== |
||
===Simple Example=== |
===Simple Example=== |
||
< |
<syntaxhighlight lang="ada">with Ada.Text_Io; use Ada.Text_Io; |
||
procedure Subprogram_As_Argument is |
procedure Subprogram_As_Argument is |
||
Line 59: | Line 129: | ||
begin |
begin |
||
First(Second'Access); |
First(Second'Access); |
||
end Subprogram_As_Argument;</ |
end Subprogram_As_Argument;</syntaxhighlight> |
||
===Complex Example=== |
===Complex Example=== |
||
< |
<syntaxhighlight lang="ada">with Ada.Text_Io; use Ada.Text_Io; |
||
procedure Subprogram_As_Argument_2 is |
procedure Subprogram_As_Argument_2 is |
||
Line 112: | 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;</ |
end Subprogram_As_Argument_2;</syntaxhighlight> |
||
=={{header|Aime}}== |
=={{header|Aime}}== |
||
< |
<syntaxhighlight lang="aime">integer |
||
average(integer p, integer q) |
average(integer p, integer q) |
||
{ |
{ |
||
Line 139: | Line 209: | ||
return 0; |
return 0; |
||
}</ |
}</syntaxhighlight> |
||
=={{header|AntLang}}== |
|||
<lang AntLang>twice:{x[x[y]]} |
|||
echo twice "Hello!"</lang> |
|||
=={{header|ALGOL 68}}== |
=={{header|ALGOL 68}}== |
||
Line 150: | 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}} |
||
< |
<syntaxhighlight lang="algol68">PROC first = (PROC(LONG REAL)LONG REAL f) LONG REAL: |
||
( |
( |
||
f(1) + 2 |
f(1) + 2 |
||
Line 162: | Line 228: | ||
main: ( |
main: ( |
||
printf(($xg(5,2)l$,first(second))) |
printf(($xg(5,2)l$,first(second))) |
||
)</ |
)</syntaxhighlight> |
||
Output: |
Output: |
||
<pre> |
<pre> |
||
Line 170: | 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. |
||
< |
<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 181: | Line 247: | ||
compute({sin_wrap}, 0.0) |
compute({sin_wrap}, 0.0) |
||
compute({cos_wrap}, 3.1415) |
compute({cos_wrap}, 3.1415) |
||
ENDPROC</ |
ENDPROC</syntaxhighlight> |
||
=={{header|AntLang}}== |
|||
<syntaxhighlight lang="antlang">twice:{x[x[y]]} |
|||
echo twice "Hello!"</syntaxhighlight> |
|||
=={{header|AppleScript}}== |
=={{header|AppleScript}}== |
||
< |
<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 207: | Line 278: | ||
end script |
end script |
||
end hire |
end hire |
||
sing about "closures" by (hire for "Pipe Organ")</ |
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 213: | 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: |
||
< |
<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 254: | Line 325: | ||
set lst to {} |
set lst to {} |
||
repeat with i from 1 to lng |
repeat with i from 1 to lng |
||
set end of lst to |
set end of lst to |λ|(item i of xs, i, xs) |
||
end repeat |
end repeat |
||
return lst |
return lst |
||
Line 273: | Line 344: | ||
set lng to length of xs |
set lng to length of xs |
||
repeat with i from 1 to lng |
repeat with i from 1 to lng |
||
set v to |
set v to |λ|(v, item i of xs, i, xs) |
||
end repeat |
end repeat |
||
return v |
return v |
||
Line 282: | Line 353: | ||
-- Sublist of those elements for which the predicate |
-- Sublist of those elements for which the predicate |
||
-- function returns true |
-- function returns true |
||
-- filter :: (a -> Bool) -> [a] -> [a] |
|||
-- filter :: (a -> Bool) -> [a] -> [a] |
-- filter :: (a -> Bool) -> [a] -> [a] |
||
on filter(f, xs) |
on filter(f, xs) |
||
Line 290: | Line 360: | ||
repeat with i from 1 to lng |
repeat with i from 1 to lng |
||
set v to item i of xs |
set v to item i of xs |
||
if |
if |λ|(v, i, xs) then set end of lst to v |
||
end repeat |
end repeat |
||
return lst |
return lst |
||
Line 303: | Line 373: | ||
else |
else |
||
script |
script |
||
property |
property |λ| : f |
||
end script |
end script |
||
end if |
end if |
||
Line 328: | Line 398: | ||
on isEven(x) |
on isEven(x) |
||
x mod 2 = 0 |
x mod 2 = 0 |
||
end isEven</ |
end isEven</syntaxhighlight> |
||
{{Out}} |
{{Out}} |
||
< |
<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}}</ |
{true, false, true, false, true, false, true, false, true, false, true}}</syntaxhighlight> |
||
===Alternative description=== |
|||
In plain English, one handler can be passed as a parameter to another either in a script object … |
|||
<syntaxhighlight lang="applescript">script aScript |
|||
on aHandler(aParameter) |
|||
say aParameter |
|||
end aHandler |
|||
end script |
|||
on receivingHandler(passedScript) |
|||
passedScript's aHandler("Hello") |
|||
end receivingHandler |
|||
receivingHandler(aScript)</syntaxhighlight> |
|||
… or directly, with the passed pointer being assigned to a script object property upon receipt: |
|||
<syntaxhighlight lang="applescript">on aHandler(aParameter) |
|||
say aParameter |
|||
end aHandler |
|||
on receivingHandler(passedHandler) |
|||
script o |
|||
property h : passedHandler |
|||
end script |
|||
o's h("Hello") |
|||
end receivingHandler |
|||
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. |
|||
An alternative to the script object property in the second case would be a global or property of the main script (the one containing the receiving handler), but this isn't recommended owing to the possibilities for conflict. |
|||
=={{header|Arturo}}== |
|||
<syntaxhighlight lang="arturo">doSthWith: function [x y f][ |
|||
f x y |
|||
] |
|||
print [ "add:" doSthWith 2 3 $[x y][x+y] ] |
|||
print [ "multiply:" doSthWith 2 3 $[x y][x*y] ]</syntaxhighlight> |
|||
{{out}} |
|||
<pre>add: 5 |
|||
multiply: 6</pre> |
|||
=={{header|ATS}}== |
=={{header|ATS}}== |
||
<syntaxhighlight lang="ats"> |
|||
<lang ATS> |
|||
#include |
#include |
||
"share/atspre_staload.hats" |
"share/atspre_staload.hats" |
||
Line 350: | 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 369: | 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}} |
||
< |
<syntaxhighlight lang="bbcbasic"> REM Test passing a function to a function: |
||
PRINT FNtwo(FNone(), 10, 11) |
PRINT FNtwo(FNone(), 10, 11) |
||
END |
END |
||
Line 381: | 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)</ |
DEF FNtwo(RETURN f%, x, y) = FN(^f%)(x, y)</syntaxhighlight> |
||
'''Output:''' |
'''Output:''' |
||
<pre> |
<pre> |
||
441 |
441 |
||
</pre> |
</pre> |
||
=={{header|Binary Lambda Calculus}}== |
|||
Every BLC program uses higher order functions, since the parsed lambda term is applied to the remainder of input, which is, like everything in lambda calculus, itself a function. For example, the empty input is nil = <code>\x\y.y</code>. So the following minimal 4-bit BLC program passes nil to the identity function: |
|||
<pre>0010</pre> |
|||
=={{header|BQN}}== |
|||
BQN has built-in support for higher order functions. |
|||
A function's name in lowercase can be used to pass it as a subject, rather than a function to be executed. |
|||
<syntaxhighlight lang="bqn">Uniq ← ⍷ |
|||
•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!] |
|||
=={{header|Bracmat}}== |
=={{header|Bracmat}}== |
||
< |
<syntaxhighlight lang="bracmat">( (plus=a b.!arg:(?a.?b)&!a+!b) |
||
& ( print |
& ( print |
||
= text a b func |
= text a b func |
||
Line 401: | Line 531: | ||
. multiply |
. multiply |
||
) |
) |
||
);</ |
);</syntaxhighlight> |
||
Output: |
Output: |
||
<pre>add(3,7)=10 |
<pre>add(3,7)=10 |
||
Line 407: | Line 537: | ||
=={{header|Brat}}== |
=={{header|Brat}}== |
||
< |
<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</ |
p doit ->add 1 2 #prints 3</syntaxhighlight> |
||
=={{header|Bruijn}}== |
|||
Everything in bruijn is a function (including strings and numbers), so even <syntaxhighlight lang="bruijn">main [0]</syntaxhighlight> would be a valid solution since the argument of <code>main</code> is already a functional encoding of stdin. |
|||
A more obvious example: |
|||
<syntaxhighlight lang="bruijn"> |
|||
first [0 [[0]]] |
|||
second [first [[1]]] |
|||
:test (second) ([[[[0]]]]) |
|||
</syntaxhighlight> |
|||
=={{header|Burlesque}}== |
=={{header|Burlesque}}== |
||
Line 418: | Line 560: | ||
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): |
||
< |
<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 431: | Line 572: | ||
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: |
||
< |
<syntaxhighlight lang="c">void myFuncSimple( void (*funcParameter)(void) ) |
||
{ |
{ |
||
/* ... */ |
/* ... */ |
||
Line 439: | Line 580: | ||
/* ... */ |
/* ... */ |
||
}</ |
}</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 445: | Line 586: | ||
Call: |
Call: |
||
< |
<syntaxhighlight lang="c">void funcToBePassed(void); |
||
/* ... */ |
/* ... */ |
||
myFuncSimple(&funcToBePassed);</ |
myFuncSimple(&funcToBePassed);</syntaxhighlight> |
||
'''Complex example''' |
'''Complex example''' |
||
Line 455: | Line 596: | ||
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. |
||
< |
<syntaxhighlight lang="c">int* myFuncComplex( double* (*funcParameter)(long* parameter) ) |
||
{ |
{ |
||
long inLong; |
long inLong; |
||
Line 467: | Line 608: | ||
/* ... */ |
/* ... */ |
||
}</ |
}</syntaxhighlight> |
||
Call: |
Call: |
||
< |
<syntaxhighlight lang="c">double* funcToBePassed(long* parameter); |
||
/* ... */ |
/* ... */ |
||
Line 476: | Line 617: | ||
int* outInt; |
int* outInt; |
||
outInt = myFuncComplex(&funcToBePassed);</ |
outInt = myFuncComplex(&funcToBePassed);</syntaxhighlight> |
||
'''Pointer''' |
'''Pointer''' |
||
Line 482: | Line 623: | ||
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: |
||
< |
<syntaxhighlight lang="c">int* (*funcPointer)( double* (*funcParameter)(long* parameter) ); |
||
/* ... */ |
/* ... */ |
||
funcPointer = &myFuncComplex;</ |
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. |
||
=={{header|C |
=={{header|C sharp}}== |
||
===Function Pointer=== |
|||
{{works with|g++|3.4.2 (mingw-special)}} |
|||
C++ can pass function pointers in the same manner as C. |
|||
===Function class template=== |
|||
Using the std::tr1::function class template allows more powerful usage. function<> can be used to pass around arbitrary function objects. This permits them to be used as closures. |
|||
For C++11 this is now std::function. |
|||
{{works with|gcc|4.4}} |
|||
<lang cpp> |
|||
// Use <functional> for C++11 |
|||
#include <tr1/functional> |
|||
#include <iostream> |
|||
using namespace std; |
|||
using namespace std::tr1; |
|||
void first(function<void()> f) |
|||
{ |
|||
f(); |
|||
} |
|||
void second() |
|||
{ |
|||
cout << "second\n"; |
|||
} |
|||
int main() |
|||
{ |
|||
first(second); |
|||
} |
|||
</lang> |
|||
===Template and Inheritance=== |
|||
{{works with|Visual C++|2005}} |
|||
Each example below performs the same task and utilizes .NET delegates, which are objects that refer to a static method or to an instance method of a particular object instance. |
|||
<lang cpp>#include <iostream> |
|||
#include <functional> |
|||
template<class Func> |
|||
typename Func::result_type first(Func func, typename Func::argument_type arg) |
|||
{ |
|||
return func(arg); |
|||
} |
|||
class second : public std::unary_function<int, int> |
|||
{ |
|||
public: |
|||
result_type operator()(argument_type arg) const |
|||
{ |
|||
return arg * arg; |
|||
} |
|||
}; |
|||
int main() |
|||
{ |
|||
std::cout << first(second(), 2) << std::endl; |
|||
return 0; |
|||
}</lang> |
|||
=={{header|C sharp}}== |
|||
{{out|note=for each example}} |
|||
Each example below does the same thing and has the same output: |
|||
<pre> |
<pre> |
||
f=Add, f(6, 2) = 8 |
f=Add, f(6, 2) = 8 |
||
Line 566: | Line 642: | ||
</pre> |
</pre> |
||
=== |
==={{anchor|C#: Named methods}}Named methods=== |
||
This works |
This implementation works in all standard versions of C#. |
||
< |
<syntaxhighlight lang="csharp">using System; |
||
// A delegate declaration. Because delegates are types, they can exist directly in namespaces. |
|||
delegate int Func2(int a, int b); |
delegate int Func2(int a, int b); |
||
class Program |
class Program |
||
{ |
{ |
||
Line 590: | Line 669: | ||
static int Call(Func2 f, int a, int b) |
static int Call(Func2 f, int a, int b) |
||
{ |
{ |
||
// Invoking a delegate like a method is syntax sugar; this compiles down to f.Invoke(a, b); |
|||
return f(a, b); |
return f(a, b); |
||
} |
} |
||
Line 597: | Line 677: | ||
int a = 6; |
int a = 6; |
||
int b = 2; |
int b = 2; |
||
// Delegates must be created using the "constructor" syntax in C# 1.0; in C# 2.0 and above, only the name of the method is required (when a target type exists, such as in an assignment to a variable with a delegate type or usage in a function call with a parameter of a delegate type; initializers of implicitly typed variables must use the constructor syntax as a raw method has no delegate type). Overload resolution is performed using the parameter types of the target delegate type. |
|||
Func2 add = new Func2(Add); |
Func2 add = new Func2(Add); |
||
Func2 mul = new Func2(Mul); |
Func2 mul = new Func2(Mul); |
||
Line 606: | Line 687: | ||
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)); |
||
} |
} |
||
}</ |
}</syntaxhighlight> |
||
=== |
===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 functions added closures to C#. |
|||
<syntaxhighlight lang="csharp">using System; |
|||
{{works with|C sharp|C#|2+}} |
|||
<lang csharp>using System; |
|||
delegate int Func2(int a, int b); |
delegate int Func2(int a, int b); |
||
class Program |
class Program |
||
{ |
{ |
||
Line 626: | Line 707: | ||
int a = 6; |
int a = 6; |
||
int b = 2; |
int b = 2; |
||
Console.WriteLine("f=Add, f({0}, {1}) = {2}", a, b, Call(delegate(int x, int y) { return x + y; }, a, b)); |
Console.WriteLine("f=Add, f({0}, {1}) = {2}", a, b, Call(delegate(int x, int y) { return x + y; }, a, b)); |
||
Console.WriteLine("f=Mul, f({0}, {1}) = {2}", a, b, Call(delegate(int x, int y) { return x * y; }, a, b)); |
Console.WriteLine("f=Mul, 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)); |
Console.WriteLine("f=Div, f({0}, {1}) = {2}", a, b, Call(delegate(int x, int y) { return x / y; }, a, b)); |
||
} |
} |
||
}</ |
}</syntaxhighlight> |
||
==={{anchor|C#: Lambda expressions}}C# 3.0: Lambda expressions=== |
|||
===Lambdas=== |
|||
Lambda expressions were added in C# 3.0 as a more concise replacement to anonymous methods. The target delegate type must also be known at compile-time. |
|||
Lambda functions are syntactic sugar for anonymous functions. The <code>System</code> namespace also gained some common delegates, such as <code>Func<T0, T1, T2></code>, which refers to a function that returns a value of type <code>T2</code> and has two parameters of types <code>T0</code> and <code>T1</code>. |
|||
With .NET Framework 3.5, the System namespace also gained the Func and Action "families" of generic delegate types. Action delegates are void-returning, while Func delegates return a value of a specified type. In both families, a separate type exists for every function arity from zero to sixteen, as .NET does not have variadic generics. |
|||
For instance, the <code>Action</code> delegate has no parameters, <code>Action<T></code>, has one parameter of type T, <code>Action<T1, T2></code> has two parameters of types T1 and T2, and so on. Similarly, <code>Func<TResult></code> has no parameters and a return type of TResult, <code>Func<T1, TResult></code> additionally has one parameter of type T, and so on. |
|||
{{works with|C sharp|C#|3+}} |
{{works with|C sharp|C#|3+}} |
||
< |
<syntaxhighlight lang="csharp">using System; |
||
class Program |
class Program |
||
{ |
{ |
||
Line 651: | Line 737: | ||
int b = 2; |
int b = 2; |
||
// No lengthy delegate keyword. |
|||
Console.WriteLine("f=Add, f({0}, {1}) = {2}", a, b, Call((x, y) => x + y, a, b)); |
|||
Console.WriteLine("f= |
Console.WriteLine("f=Add, f({0}, {1}) = {2}", a, b, Call((int x, int y) => { return x + y; }, a, b)); |
||
// Parameter types can be inferred. |
|||
Console.WriteLine("f=Mul, f({0}, {1}) = {2}", a, b, Call((x, y) => { return x * y; }, a, b)); |
|||
// Expression lambdas are even shorter (and are most idiomatic). |
|||
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)); |
||
} |
} |
||
}</ |
}</syntaxhighlight> |
||
=={{header|C++}}== |
|||
===Function Pointer=== |
|||
{{works with|g++|3.4.2 (mingw-special)}} |
|||
C++ can pass function pointers in the same manner as C. |
|||
===Function class template=== |
|||
Using the std::tr1::function class template allows more powerful usage. function<> can be used to pass around arbitrary function objects. This permits them to be used as closures. |
|||
For C++11 this is now std::function. |
|||
{{works with|gcc|4.4}} |
|||
<syntaxhighlight lang="cpp"> |
|||
// Use <functional> for C++11 |
|||
#include <tr1/functional> |
|||
#include <iostream> |
|||
using namespace std; |
|||
using namespace std::tr1; |
|||
void first(function<void()> f) |
|||
{ |
|||
f(); |
|||
} |
|||
void second() |
|||
{ |
|||
cout << "second\n"; |
|||
} |
|||
int main() |
|||
{ |
|||
first(second); |
|||
} |
|||
</syntaxhighlight> |
|||
===Template and Inheritance=== |
|||
{{works with|Visual C++|2005}} |
|||
<syntaxhighlight lang="cpp">#include <iostream> |
|||
#include <functional> |
|||
template<class Func> |
|||
typename Func::result_type first(Func func, typename Func::argument_type arg) |
|||
{ |
|||
return func(arg); |
|||
} |
|||
class second : public std::unary_function<int, int> |
|||
{ |
|||
public: |
|||
result_type operator()(argument_type arg) const |
|||
{ |
|||
return arg * arg; |
|||
} |
|||
}; |
|||
int main() |
|||
{ |
|||
std::cout << first(second(), 2) << std::endl; |
|||
return 0; |
|||
}</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: |
||
< |
<syntaxhighlight lang="clean">map f [x:xs] = [f x:map f xs] |
||
map f [] = []</ |
map f [] = []</syntaxhighlight> |
||
Pass a function as an argument: |
Pass a function as an argument: |
||
< |
<syntaxhighlight lang="clean">incr x = x + 1 |
||
Start = map incr [1..10]</ |
Start = map incr [1..10]</syntaxhighlight> |
||
Do the same using a anonymous function: |
Do the same using a anonymous function: |
||
< |
<syntaxhighlight lang="clean">Start = map (\x -> x + 1) [1..10]</syntaxhighlight> |
||
Do the same using currying: |
Do the same using currying: |
||
< |
<syntaxhighlight lang="clean">Start = map ((+) 1) [1..10]</syntaxhighlight> |
||
=={{header|Clojure}}== |
=={{header|Clojure}}== |
||
< |
<syntaxhighlight lang="lisp"> |
||
(defn append-hello [s] |
(defn append-hello [s] |
||
(str "Hello " s)) |
(str "Hello " s)) |
||
Line 680: | Line 838: | ||
(println (modify-string append-hello "World!")) |
(println (modify-string append-hello "World!")) |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|CLU}}== |
|||
<syntaxhighlight lang="clu">% Functions can be passed to other functions using the 'proctype' |
|||
% type generator. The same works for iterators, using 'itertype' |
|||
% Here are two functions |
|||
square = proc (n: int) returns (int) return (n*n) end square |
|||
cube = proc (n: int) returns (int) return (n*n*n) end cube |
|||
% Here is a function that takes another function |
|||
do_calcs = proc (from, to: int, title: string, |
|||
fn: proctype (int) returns (int)) |
|||
po: stream := stream$primary_output() |
|||
stream$putleft(po, title, 8) |
|||
stream$puts(po, " -> ") |
|||
for i: int in int$from_to(from,to) do |
|||
stream$putright(po, int$unparse(fn(i)), 5) |
|||
end |
|||
stream$putc(po, '\n') |
|||
end do_calcs |
|||
start_up = proc () |
|||
do_calcs(1, 10, "Squares", square) |
|||
do_calcs(1, 10, "Cubes", cube) |
|||
end start_up</syntaxhighlight> |
|||
{{out}} |
|||
<pre>Squares -> 1 4 9 16 25 36 49 64 81 100 |
|||
Cubes -> 1 8 27 64 125 216 343 512 729 1000</pre> |
|||
=={{header|CoffeeScript}}== |
=={{header|CoffeeScript}}== |
||
Line 686: | Line 873: | ||
Passing an anonymous function to built-in map/reduce functions: |
Passing an anonymous function to built-in map/reduce functions: |
||
< |
<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: |
||
< |
<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: |
||
< |
<syntaxhighlight lang="coffeescript">bowl = ["Cheese", "Tomato"] |
||
smash = (ingredient) -> |
smash = (ingredient) -> |
||
Line 704: | Line 891: | ||
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: |
||
< |
<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)))</ |
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: |
||
< |
<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: |
||
< |
<syntaxhighlight lang="coffeescript">((x)-> |
||
2 + x(-> 5) |
2 + x(-> 5) |
||
)((y) -> y()+3) |
)((y) -> y()+3) |
||
# result: 10</ |
# 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: |
||
< |
<syntaxhighlight lang="lisp">CL-USER> (defun add (a b) (+ a b)) |
||
ADD |
ADD |
||
CL-USER> (add 1 2) |
CL-USER> (add 1 2) |
||
Line 736: | Line 923: | ||
CALL-IT |
CALL-IT |
||
CL-USER> (call-it #'add 1 2) |
CL-USER> (call-it #'add 1 2) |
||
3</ |
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 749: | Line 936: | ||
(1 2 4 8 16 32) |
(1 2 4 8 16 32) |
||
CL-USER> </pre> |
CL-USER> </pre> |
||
=={{header|Cowgol}}== |
|||
<syntaxhighlight lang="cowgol">include "cowgol.coh"; |
|||
# In order to pass functions around, you must first define an interface. |
|||
# This is similar to a delegate in C#; it becomes a function pointer type. |
|||
# This interface takes two integers and returns one. |
|||
interface Dyadic(x: int32, y: int32): (r: int32); |
|||
# For a function to be able to be passed around, it must explicitly implement |
|||
# an interface. Then it has the same type as that interface. |
|||
# The interface replaces the method's parameter list entirely. |
|||
sub Add implements Dyadic is |
|||
r := x + y; |
|||
end sub; |
|||
# Here are the other basic operators. |
|||
sub Sub implements Dyadic is r := x - y; end sub; |
|||
sub Mul implements Dyadic is r := x * y; end sub; |
|||
sub Div implements Dyadic is r := x / y; end sub; |
|||
# An interface is just like any other type, and the functions that implement |
|||
# it are first-class values. For example, this code maps the operator |
|||
# characters to their functions. |
|||
record Operator is |
|||
char: uint8; |
|||
func: Dyadic; |
|||
end record; |
|||
var operators: Operator[] := { |
|||
{'+', Add}, {'-', Sub}, {'*', Mul}, {'/', Div}, |
|||
{0, Dyadic} |
|||
}; |
|||
# This is a function that applies such a function to two values |
|||
sub apply(f: Dyadic, x: int32, y: int32): (r: int32) is |
|||
r := f(x,y); # the function can be called as normal |
|||
end sub; |
|||
# And this is a function that applies all the above operators to two values |
|||
sub showAll(ops: [Operator], x: int32, y: int32) is |
|||
while ops.char != 0 loop |
|||
print_i32(x as uint32); |
|||
print_char(' '); |
|||
print_char(ops.char); |
|||
print_char(' '); |
|||
print_i32(y as uint32); |
|||
print(" = "); |
|||
print_i32(apply(ops.func, x, y) as uint32); |
|||
print_nl(); |
|||
ops := @next ops; |
|||
end loop; |
|||
end sub; |
|||
showAll(&operators[0], 84, 42); # example</syntaxhighlight> |
|||
{{out}} |
|||
<pre>84 + 42 = 126 |
|||
84 - 42 = 42 |
|||
84 * 42 = 3528 |
|||
84 / 42 = 2</pre> |
|||
=={{header|D}}== |
=={{header|D}}== |
||
< |
<syntaxhighlight lang="d">int hof(int a, int b, int delegate(int, int) f) { |
||
return f(a, b); |
return f(a, b); |
||
} |
} |
||
Line 759: | Line 1,008: | ||
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)); |
||
}</ |
}</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. |
||
< |
<syntaxhighlight lang="d">import std.stdio; |
||
// Test the function argument. |
// Test the function argument. |
||
Line 824: | Line 1,073: | ||
"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"; }); |
||
}</ |
}</syntaxhighlight> |
||
{{out}}} |
{{out}}} |
||
<pre>Hi, Function : scope: Global (function) : immutable(char)[]()* |
<pre>Hi, Function : scope: Global (function) : immutable(char)[]()* |
||
Line 841: | Line 1,090: | ||
=={{header|Delphi}}== |
=={{header|Delphi}}== |
||
:''See [[#Pascal|Pascal]]'' |
:''See [[#Pascal|Pascal]]'' |
||
=={{header|Déjà Vu}}== |
|||
<lang dejavu>map f lst: |
|||
] |
|||
for item in lst: |
|||
f item |
|||
[ |
|||
twice: |
|||
* 2 |
|||
!. map @twice [ 1 2 5 ]</lang> |
|||
{{out}} |
|||
<pre>[ 2 4 10 ]</pre> |
|||
=={{header|DWScript}}== |
=={{header|DWScript}}== |
||
< |
<syntaxhighlight lang="delphi">type TFnType = function(x : Float) : Float; |
||
function First(f : TFnType) : Float; |
function First(f : TFnType) : Float; |
||
Line 868: | Line 1,104: | ||
end; |
end; |
||
PrintLn(First(Second));</ |
PrintLn(First(Second));</syntaxhighlight> |
||
=={{header|Dyalect}}== |
|||
{{trans|C#}} |
|||
<syntaxhighlight lang="dyalect">func call(f, a, b) { |
|||
f(a, b) |
|||
} |
|||
let a = 6 |
|||
let b = 2 |
|||
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=div, f(\(a), \(b)) = \(call((x, y) => x / y, a, b))")</syntaxhighlight> |
|||
{{out}} |
|||
<pre>f=add, f(6, 2) = 8 |
|||
f=mul, f(6, 2) = 12 |
|||
f=div, f(6, 2) = 3</pre> |
|||
=={{header|Déjà Vu}}== |
|||
<syntaxhighlight lang="dejavu">map f lst: |
|||
] |
|||
for item in lst: |
|||
f item |
|||
[ |
|||
twice: |
|||
* 2 |
|||
!. map @twice [ 1 2 5 ]</syntaxhighlight> |
|||
{{out}} |
|||
<pre>[ 2 4 10 ]</pre> |
|||
=={{header|Draco}}== |
|||
<syntaxhighlight lang="draco">/* Example functions - there are no anonymous functions */ |
|||
proc nonrec square(word n) word: n*n corp |
|||
proc nonrec cube(word n) word: n*n*n corp |
|||
/* A function that takes another function. |
|||
* Note how a function is defined as: |
|||
* proc name(arguments) returntype: [code here] corp |
|||
* But a function variable is instead defined as: |
|||
* proc(arguments) returntype name |
|||
*/ |
|||
proc nonrec do_func(word start, stop; proc(word n) word fn) void: |
|||
word n; |
|||
for n from start upto stop do |
|||
write(fn(n):8) |
|||
od; |
|||
writeln() |
|||
corp |
|||
/* We can then just pass the name of a function as an argument */ |
|||
proc main() void: |
|||
do_func(1, 10, square); |
|||
do_func(1, 10, cube) |
|||
corp</syntaxhighlight> |
|||
{{out}} |
|||
<pre> 1 4 9 16 25 36 49 64 81 100 |
|||
1 8 27 64 125 216 343 512 729 1000</pre> |
|||
=={{header|E}}== |
=={{header|E}}== |
||
< |
<syntaxhighlight lang="e">def map(f, list) { |
||
var out := [] |
var out := [] |
||
for x in list { |
for x in list { |
||
Line 887: | Line 1,185: | ||
? def foo(x) { return -(x.size()) } |
? def foo(x) { return -(x.size()) } |
||
> map(foo, ["", "a", "bc"]) |
> map(foo, ["", "a", "bc"]) |
||
# value: [0, -1, -2]</ |
# 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 941: | Line 1,238: | ||
OUTPUT(doMany(2, applyValue4, applyValue2,multiValues)); |
OUTPUT(doMany(2, applyValue4, applyValue2,multiValues)); |
||
// produces "24:12"</ |
// produces "24:12"</syntaxhighlight> |
||
=={{header|Efene}}== |
=={{header|Efene}}== |
||
< |
<syntaxhighlight lang="efene">first = fn (F) { |
||
F() |
F() |
||
} |
} |
||
Line 968: | Line 1,265: | ||
first(F2) |
first(F2) |
||
} |
} |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|Elena}}== |
|||
{{trans|Smalltalk}} |
|||
ELENA 6.x : |
|||
<syntaxhighlight lang="elena">import extensions; |
|||
public program() |
|||
{ |
|||
var first := (f => f()); |
|||
var second := { ^ "second" }; |
|||
console.printLine(first(second)) |
|||
}</syntaxhighlight> |
|||
{{out}} |
|||
<pre>second</pre> |
|||
=={{header|Elixir}}== |
=={{header|Elixir}}== |
||
< |
<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 987: | Line 1,298: | ||
#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</ |
: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: |
||
< |
<syntaxhighlight lang="erlang">-module(test). |
||
-export([first/1, second/0]). |
-export([first/1, second/0]). |
||
first(F) -> F(). |
first(F) -> F(). |
||
second() -> hello.</ |
second() -> hello.</syntaxhighlight> |
||
Testing it: |
Testing it: |
||
< |
<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</ |
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,021: | Line 1,332: | ||
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,032: | Line 1,343: | ||
[ -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}}== |
||
< |
<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,043: | Line 1,354: | ||
end function |
end function |
||
use(routine_id("add"),23,45)</ |
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: |
||
< |
<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</ |
val it : float = 3.0</syntaxhighlight> |
||
Another example, using an operator as a function: |
Another example, using an operator as a function: |
||
< |
<syntaxhighlight lang="fsharp">> List.map2 (+) [1;2;3] [3;2;1];; |
||
val it : int list = [4; 4; 4]</ |
val it : int list = [4; 4; 4]</syntaxhighlight> |
||
=={{header|Factor}}== |
=={{header|Factor}}== |
||
Using words (factor's functions) : |
Using words (factor's functions) : |
||
< |
<syntaxhighlight lang="factor">USING: io ; |
||
IN: rosetacode |
IN: rosetacode |
||
: argument-function1 ( -- ) "Hello World!" print ; |
: argument-function1 ( -- ) "Hello World!" print ; |
||
Line 1,073: | Line 1,384: | ||
! 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,088: | Line 1,399: | ||
=={{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. |
||
< |
<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 }</ |
1 2 3 4 0 4[$*+]r;!. { 30 }</syntaxhighlight> |
||
=={{header|Fantom}}== |
=={{header|Fantom}}== |
||
< |
<syntaxhighlight lang="fantom"> |
||
class Main |
class Main |
||
{ |
{ |
||
Line 1,111: | Line 1,422: | ||
} |
} |
||
} |
} |
||
</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. |
||
< |
<syntaxhighlight lang="forth">: square dup * ; |
||
: cube dup dup * * ; |
: cube dup dup * * ; |
||
: map. ( xt addr len -- ) |
: map. ( xt addr len -- ) |
||
Line 1,124: | Line 1,435: | ||
' 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</ |
: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. |
||
< |
<syntaxhighlight lang="fortran">FUNCTION FUNC3(FUNC1, FUNC2, x, y) |
||
REAL, EXTERNAL :: FUNC1, FUNC2 |
REAL, EXTERNAL :: FUNC1, FUNC2 |
||
REAL :: FUNC3 |
REAL :: FUNC3 |
||
Line 1,135: | Line 1,446: | ||
FUNC3 = FUNC1(x) * FUNC2(y) |
FUNC3 = FUNC1(x) * FUNC2(y) |
||
END FUNCTION FUNC3</ |
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: |
||
< |
<syntaxhighlight lang="fortran">module FuncContainer |
||
implicit none |
implicit none |
||
contains |
contains |
||
Line 1,188: | Line 1,499: | ||
end subroutine asubroutine |
end subroutine asubroutine |
||
end program FuncArg</ |
end program FuncArg</syntaxhighlight> |
||
=={{header|FreeBASIC}}== |
=={{header|FreeBASIC}}== |
||
< |
<syntaxhighlight lang="freebasic">' FB 1.05.0 Win64 |
||
Function square(n As Integer) As Integer |
Function square(n As Integer) As Integer |
||
Line 1,213: | Line 1,524: | ||
Print |
Print |
||
Print "Press any key to quit" |
Print "Press any key to quit" |
||
Sleep</ |
Sleep</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 1,224: | Line 1,535: | ||
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. |
||
< |
<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. |
||
< |
<syntaxhighlight lang="frink"> |
||
lengthCompare[a,b] := length[a] <=> length[b] |
lengthCompare[a,b] := length[a] <=> length[b] |
||
Line 1,239: | Line 1,550: | ||
a = ["tree", "apple", "bee", "monkey", "z"] |
a = ["tree", "apple", "bee", "monkey", "z"] |
||
sort[a, func] |
sort[a, func] |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|FutureBasic}}== |
=={{header|FutureBasic}}== |
||
< |
<syntaxhighlight lang="futurebasic">window 1 |
||
include "ConsoleWindow" |
|||
dim as pointer functionOneAddress |
dim as pointer functionOneAddress |
||
Line 1,253: | Line 1,563: | ||
print fn FunctionTwo( 12, 12 ) |
print fn FunctionTwo( 12, 12 ) |
||
</lang> |
|||
HandleEvents</syntaxhighlight> |
|||
Output: |
Output: |
||
Line 1,259: | Line 1,570: | ||
576 |
576 |
||
</pre> |
</pre> |
||
=={{header|Fōrmulæ}}== |
|||
{{FormulaeEntry|page=https://formulae.org/?script=examples/Higher-order_functions}} |
|||
'''Solution''' |
|||
'''Case 1 (from Rosetta code)''' Passing a function as an argument to another function. |
|||
The following function takes a function as its first parameter, and other two parameters, x and y. When this function "Do" is called, it will perform the given function taking as arguments the values x and y. |
|||
[[File:Fōrmulæ - Higher-order functions 01.png]] |
|||
[[File:Fōrmulæ - Higher-order functions 02.png]] |
|||
[[File:Fōrmulæ - Higher-order functions 03.png]] |
|||
An anonymous function (a lambda expression) can be passed directly: |
|||
[[File:Fōrmulæ - Higher-order functions 04.png]] |
|||
[[File:Fōrmulæ - Higher-order functions 05.png]] |
|||
For the next example, the function to be passed, when invoked, will perform several operation to the same two arguments. It will add them, subtract them, multiply them, divide them and power them. Finally it will return a list with the results. |
|||
[[File:Fōrmulæ - Higher-order functions 06.png]] |
|||
[[File:Fōrmulæ - Higher-order functions 07.png]] |
|||
Up now, however, it is the half of the story. Let us build an example where a function takes a function as parameter, and returns another function. |
|||
'''Case 2 (from Wikipedia)''' Passing a function as an argument to another function, and returning a function |
|||
The following function is a higher-order function. It takes as its unique parameter the function f. When the function is invoked, it will apply twice the function f and will return it. In other words, it will return a new function, which is the composition of the function f with itself. |
|||
[[File:Fōrmulæ - Higher-order functions 08.png]] |
|||
The next function is an ordinary one. It returns the values given as argument added with 3. |
|||
[[File:Fōrmulæ - Higher-order functions 09.png]] |
|||
In the next example, g is a dynamically created function. |
|||
[[File:Fōrmulæ - Higher-order functions 10.png]] |
|||
[[File:Fōrmulæ - Higher-order functions 11.png]] |
|||
Since the '''Apply twice''' function returns a function, it can be immediately invoked: |
|||
[[File:Fōrmulæ - Higher-order functions 12.png]] |
|||
[[File:Fōrmulæ - Higher-order functions 11.png]] |
|||
It can also take a pure symbol, in order to retrrieve a symbolic result: |
|||
[[File:Fōrmulæ - Higher-order functions 13.png]] |
|||
[[File:Fōrmulæ - Higher-order functions 14.png]] |
|||
=={{header|GAP}}== |
=={{header|GAP}}== |
||
< |
<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</ |
# 343</syntaxhighlight> |
||
=={{header|Go}}== |
=={{header|Go}}== |
||
< |
<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)) }</ |
func main() { fmt.Println(func1(func2)) }</syntaxhighlight> |
||
=={{header|Groovy}}== |
=={{header|Groovy}}== |
||
As [[closures]]: |
As [[closures]]: |
||
< |
<syntaxhighlight lang="groovy">first = { func -> func() } |
||
second = { println "second" } |
second = { println "second" } |
||
first(second)</ |
first(second)</syntaxhighlight> |
||
As functions: |
As functions: |
||
< |
<syntaxhighlight lang="groovy">def first(func) { func() } |
||
def second() { println "second" } |
def second() { println "second" } |
||
first(this.&second)</ |
first(this.&second)</syntaxhighlight> |
||
=={{header|Haskell}}== |
=={{header|Haskell}}== |
||
Line 1,293: | Line 1,662: | ||
A function is just a value that wants arguments: |
A function is just a value that wants arguments: |
||
< |
<syntaxhighlight lang="haskell">func1 f = f "a string" |
||
func2 s = "func2 called with " ++ s |
func2 s = "func2 called with " ++ s |
||
main = putStrLn $ func1 func2</ |
main = putStrLn $ func1 func2</syntaxhighlight> |
||
Or, with an anonymous function: |
Or, with an anonymous function: |
||
< |
<syntaxhighlight lang="haskell">func f = f 1 2 |
||
main = print $ func (\x y -> x+y) |
main = print $ func (\x y -> x+y) |
||
-- output: 3</ |
-- 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}}== |
||
< |
<syntaxhighlight lang="icon"> procedure main() |
||
local lst |
local lst |
||
lst := [10, 20, 30, 40] |
lst := [10, 20, 30, 40] |
||
Line 1,317: | Line 1,686: | ||
procedure callback(arg) |
procedure callback(arg) |
||
write("->", arg) |
write("->", arg) |
||
end</ |
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. |
||
< |
<syntaxhighlight lang="inform6">[ func; |
||
print "Hello^"; |
print "Hello^"; |
||
]; |
]; |
||
Line 1,331: | Line 1,700: | ||
[ Main; |
[ Main; |
||
call_func(func); |
call_func(func); |
||
];</ |
];</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. |
||
< |
<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,349: | Line 1,718: | ||
demonstrate addition as "Add"; |
demonstrate addition as "Add"; |
||
demonstrate multiplication as "Mul"; |
demonstrate multiplication as "Mul"; |
||
end the story.</ |
end the story.</syntaxhighlight> |
||
=={{Header|Insitux}}== |
|||
{{Trans|Clojure}} |
|||
<syntaxhighlight lang="insitux"> |
|||
(function prepend-hello s |
|||
(str "Hello, " s)) |
|||
(function modify-string f s |
|||
(f s)) |
|||
(modify-string prepend-hello "World!") |
|||
</syntaxhighlight> |
|||
{{out}} |
|||
<pre> |
|||
Hello, World! |
|||
</pre> |
|||
=={{header|J}}== |
=={{header|J}}== |
||
Line 1,355: | Line 1,744: | ||
''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. |
||
< |
<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,385: | Line 1,774: | ||
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</ |
1 3r2 17r12 577r408 665857r470832</syntaxhighlight> |
||
Adverbs and conjunctions may also be user defined |
Adverbs and conjunctions may also be user defined |
||
< |
<syntaxhighlight lang="j"> + conjunction def 'u' - |
||
+ |
+ |
||
+ conjunction def 'v' - |
+ conjunction def 'v' - |
||
Line 1,396: | Line 1,785: | ||
110 |
110 |
||
^ conjunction def '10 v 2 u y' * 11 |
^ conjunction def '10 v 2 u y' * 11 |
||
20480</ |
20480</syntaxhighlight> |
||
=={{header|Java}}== |
=={{header|Java}}== |
||
Line 1,402: | Line 1,791: | ||
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. |
||
< |
<syntaxhighlight lang="java">public class NewClass { |
||
public NewClass() { |
public NewClass() { |
||
Line 1,427: | Line 1,816: | ||
interface AnEventOrCallback { |
interface AnEventOrCallback { |
||
public void call(); |
public void call(); |
||
}</ |
}</syntaxhighlight> |
||
From Java 8, lambda expressions may be used. Example (from Oracle): |
From Java 8, lambda expressions may be used. Example (from Oracle): |
||
< |
<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,448: | Line 1,837: | ||
frame.setVisible(true); |
frame.setVisible(true); |
||
} |
} |
||
}</ |
}</syntaxhighlight> |
||
=={{header|JavaScript}}== |
=={{header|JavaScript}}== |
||
< |
<syntaxhighlight lang="javascript">function first (func) { |
||
return func(); |
return func(); |
||
} |
} |
||
Line 1,461: | Line 1,850: | ||
var result = first(second); |
var result = first(second); |
||
result = first(function () { return "third"; });</ |
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,467: | Line 1,856: | ||
{{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>. |
||
< |
<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,493: | Line 1,882: | ||
// 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]</ |
[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> |
||
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> |
||
Pass first enclosed in quotes to second |
Pass first enclosed in quotes to second. |
||
<lang |
<syntaxhighlight lang="joy">2 3 [first] second.</syntaxhighlight> |
||
The program prints 6. |
The program prints 6. |
||
Line 1,516: | Line 1,905: | ||
====Example 1: "hello blue world"==== |
====Example 1: "hello blue world"==== |
||
< |
<syntaxhighlight lang="jq">def foo( filter ): |
||
("world" | filter) as $str |
("world" | filter) as $str |
||
| "hello \($str)" ; |
| "hello \($str)" ; |
||
Line 1,524: | Line 1,913: | ||
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</ |
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: |
||
< |
<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;</ |
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,561: | Line 1,950: | ||
false |
false |
||
true |
true |
||
false</ |
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,570: | Line 1,960: | ||
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,576: | Line 1,966: | ||
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,587: | Line 1,977: | ||
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. |
||
< |
<syntaxhighlight lang="julia">julia> all(iseven, 1:5) # not all integers between 1 and 5 are even. |
||
false |
false |
||
Line 1,608: | Line 1,998: | ||
true |
true |
||
false |
false |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|Klingphix}}== |
|||
<syntaxhighlight lang="klingphix">:+2 + 2 + ; |
|||
:*2 * 2 * ; |
|||
:apply exec ; |
|||
23 45 @+2 apply print nl |
|||
8 4 @*2 apply print nl |
|||
" " 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: |
||
< |
<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 h = list.map({ 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)) |
||
}</ |
}</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): |
||
<syntaxhighlight lang="scala">inline fun higherOrderFunction(x: Int, y: Int, function: (Int, Int) -> Int) = function(x, y) |
|||
<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) |
||
}</syntaxhighlight> |
|||
} |
|||
</lang> |
|||
{{out}} |
{{out}} |
||
<pre>8</pre> |
<pre>8</pre> |
||
=={{header| |
=={{header|Lambdatalk}}== |
||
<syntaxhighlight lang="scheme"> |
|||
Lingo doesn't support first-class functions. But global functions - i.e. either built-in functions or user-defined functions in movie scripts - can be specified and used by passing a "symbol". So for such global functions, the task can be solved. Here as example an implementation of a "map" function: |
|||
{def add |
|||
{lambda {:f :g :x} |
|||
{+ {:f :x} {:g :x}}}} |
|||
{add sin cos 10} |
|||
<lang lingo>-- in some movie script |
|||
-> -1.383092639965822 // {+ {sin 10} {cos 10}} |
|||
---------------------------------------- |
|||
-- Runs provided function on all elements of the provided list, returns results as new list |
|||
-- @param {list} tList |
|||
-- @param {symbol} cbFunc |
|||
-- @param {object} [cbObj=_movie] |
|||
-- @return {list} |
|||
---------------------------------------- |
|||
on map (tList, cbFunc, cbObj) |
|||
if voidP(cbObj) then cbObj = _movie |
|||
res = [] |
|||
cnt = tList.count |
|||
repeat with i = 1 to cnt |
|||
res[i] = call(cbFunc, cbObj, tList[i]) |
|||
end repeat |
|||
return res |
|||
end</lang> |
|||
{S.map sqrt {S.serie 1 5}} |
|||
<lang lingo>l = [1, 2, 3] |
|||
-> 1 1.4142135623730951 1.7320508075688772 2 2.23606797749979 |
|||
{S.reduce + {S.serie 1 10}} |
|||
-- passes the built-in function 'sin' (which is a method of the _movie object) as argument to map |
|||
-> 55 |
|||
res = map(l, #sin) |
|||
</syntaxhighlight> |
|||
put res |
|||
-- [0.8415, 0.9093, 0.1411]</lang> |
|||
=={{header|Logo}}== |
|||
You can pass the quoted symbol for the function and invoke it with RUN. |
|||
<lang logo>to printstuff |
|||
print "stuff |
|||
end |
|||
to runstuff :proc |
|||
run :proc |
|||
end |
|||
runstuff "printstuff ; stuff |
|||
runstuff [print [also stuff]] ; also stuff</lang> |
|||
=={{header|Lily}}== |
=={{header|Lily}}== |
||
< |
<syntaxhighlight lang="lily">define square(x: Integer): Integer |
||
{ |
{ |
||
return x * x |
return x * x |
||
Line 1,699: | Line 2,074: | ||
# Calling user-defined transformation. |
# Calling user-defined transformation. |
||
print(apply("123", String.parse_i)) # Some(123)</ |
print(apply("123", String.parse_i)) # Some(123)</syntaxhighlight> |
||
=={{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: |
|||
<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 |
|||
-- @param {list} aList |
|||
-- @param {symbol} cbFunc |
|||
-- @param {object} [cbObj=_movie] |
|||
-- @return {list} |
|||
---------------------------------------- |
|||
on map (aList, cbFunc, cbObj) |
|||
if voidP(cbObj) then cbObj = _movie |
|||
res = [] |
|||
cnt = aList.count |
|||
repeat with i = 1 to cnt |
|||
res[i] = call(cbFunc, cbObj, aList[i]) |
|||
end repeat |
|||
return res |
|||
end</syntaxhighlight> |
|||
<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 |
|||
res = map(l, #sin) |
|||
put res |
|||
-- [0.8415, 0.9093, 0.1411]</syntaxhighlight> |
|||
=={{header|Logo}}== |
|||
You can pass the quoted symbol for the function and invoke it with RUN. |
|||
<syntaxhighlight lang="logo">to printstuff |
|||
print "stuff |
|||
end |
|||
to runstuff :proc |
|||
run :proc |
|||
end |
|||
runstuff "printstuff ; stuff |
|||
runstuff [print [also stuff]] ; also stuff</syntaxhighlight> |
|||
=={{header|Lua}}== |
=={{header|Lua}}== |
||
Lua functions are first-class: |
Lua functions are first-class: |
||
< |
<syntaxhighlight lang="lua">a = function() return 1 end |
||
b = function(r) print( r() ) end |
b = function(r) print( r() ) end |
||
b(a)</ |
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: |
||
< |
<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") );;</ |
print( lambda_if(lambda_true)("condition was true")("condition was false") );;</syntaxhighlight> |
||
=={{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) |
|||
<syntaxhighlight lang="m2000 interpreter"> |
|||
Function Foo (x) { |
|||
=x**2 |
|||
} |
|||
Function Bar(&f(), k) { |
|||
=f(k) |
|||
} |
|||
Print Bar(&foo(), 20)=400 |
|||
Group K { |
|||
Z=10 |
|||
Function MulZ(x) { |
|||
=.Z*x |
|||
.Z++ |
|||
} |
|||
} |
|||
Print Bar(&K.MulZ(), 20)=200 |
|||
Print K.Z=11 |
|||
</syntaxhighlight> |
|||
Example using lambda function |
|||
<syntaxhighlight lang="m2000 interpreter"> |
|||
Foo = Lambda k=1 (x)-> { |
|||
k+=2 |
|||
=x**2+K |
|||
} |
|||
\\ by ref1 |
|||
Function Bar1(&f(), k) { |
|||
=f(k) |
|||
} |
|||
Print Bar1(&Foo(), 20)=403 |
|||
\\ by ref2 |
|||
Function Bar2(&f, k) { |
|||
=f(k) |
|||
} |
|||
Print Bar2(&Foo, 20)=405 |
|||
\\ by value |
|||
Function Bar(f, k) { |
|||
=f(k) |
|||
} |
|||
\\ we sent a copy of lambda, and any value type closure copied too |
|||
Print Bar(Foo, 20)=407 |
|||
Print Bar1(&Foo(), 20)=407 |
|||
\\ we can get a copy of Foo to NewFoo (also we get a copy of closure too) |
|||
NewFoo=Foo |
|||
Print Bar1(&Foo(), 20)=409 |
|||
Print Bar2(&Foo, 20)=411 |
|||
Print Bar2(&NewFoo, 20)=409 |
|||
</syntaxhighlight> |
|||
=={{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: |
||
< |
<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]</ |
PassFunc[Tan, Cos, Sin, 0.12]</syntaxhighlight> |
||
gives back: |
gives back: |
||
< |
<syntaxhighlight lang="mathematica">Tan[Cos[x] Sin[x]] |
||
0.119414 |
0.119414 |
||
0.119414</ |
0.119414</syntaxhighlight> |
||
=={{header|MATLAB}} / {{header|Octave}}== |
=={{header|MATLAB}} / {{header|Octave}}== |
||
< |
<syntaxhighlight lang="matlab"> F1=@sin; % F1 refers to function sin() |
||
F2=@cos; % F2 refers to function cos() |
F2=@cos; % F2 refers to function cos() |
||
% varios ways to call the |
% varios ways to call the referred function |
||
F1(pi/4) |
F1(pi/4) |
||
F2(pi/4) |
F2(pi/4) |
||
Line 1,744: | Line 2,212: | ||
F4 = 'cos'; |
F4 = 'cos'; |
||
feval(F3,pi/4) |
feval(F3,pi/4) |
||
feval(F4,pi/4)</ |
feval(F4,pi/4)</syntaxhighlight> |
||
=={{header|Maxima}}== |
=={{header|Maxima}}== |
||
< |
<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"</ |
"called with 3"</syntaxhighlight> |
||
=={{header|MAXScript}}== |
=={{header|MAXScript}}== |
||
< |
<syntaxhighlight lang="maxscript">fn second = |
||
( |
( |
||
print "Second" |
print "Second" |
||
Line 1,765: | Line 2,233: | ||
) |
) |
||
first second</ |
first second</syntaxhighlight> |
||
=={{header|Metafont}}== |
=={{header|Metafont}}== |
||
Line 1,771: | Line 2,239: | ||
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. |
||
< |
<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</ |
end</syntaxhighlight> |
||
=={{header|МК-61/52}}== |
=={{header|МК-61/52}}== |
||
<lang>6 ПП 04 |
<syntaxhighlight lang="text">6 ПП 04 |
||
П7 КПП7 В/О |
П7 КПП7 В/О |
||
1 В/О</ |
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}}== |
||
< |
<syntaxhighlight lang="modula3">MODULE Proc EXPORTS Main; |
||
IMPORT IO; |
IMPORT IO; |
||
Line 1,803: | Line 2,271: | ||
BEGIN |
BEGIN |
||
First(Second); |
First(Second); |
||
END Proc.</ |
END Proc.</syntaxhighlight> |
||
=={{header|Morfa}}== |
=={{header|Morfa}}== |
||
{{trans|D}} |
{{trans|D}} |
||
< |
<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 1,820: | Line 2,288: | ||
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}}== |
|||
{{trans|Python}} |
|||
<syntaxhighlight lang="nanoquery">def first(function) |
|||
return function() |
|||
end |
|||
def second() |
|||
return "second" |
|||
end |
|||
result = first(second) |
|||
println result</syntaxhighlight> |
|||
{{out}} |
|||
<pre>second</pre> |
|||
=={{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. |
||
< |
<syntaxhighlight lang="nemerle">Twice[T] (f : T -> T, x : T) : T { f(f(x)) }</syntaxhighlight> |
||
=={{header|NewLISP}}== |
=={{header|NewLISP}}== |
||
< |
<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 1,833: | Line 2,316: | ||
> (call-it my-multiply 2 3) |
> (call-it my-multiply 2 3) |
||
6 |
6 |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|Nim}}== |
=={{header|Nim}}== |
||
< |
<syntaxhighlight lang="nim">proc first(fn: proc): auto = |
||
return fn() |
return fn() |
||
Line 1,842: | Line 2,325: | ||
return "second" |
return "second" |
||
echo first(second)</ |
echo first(second)</syntaxhighlight> |
||
=={{header|Oberon-2}}== |
=={{header|Oberon-2}}== |
||
Works with oo2c version 2 |
Works with oo2c version 2 |
||
< |
<syntaxhighlight lang="oberon2"> |
||
MODULE HOFuns; |
MODULE HOFuns; |
||
IMPORT |
IMPORT |
||
Line 1,881: | Line 2,364: | ||
PrintWords(words,Tools.AdjustRight) |
PrintWords(words,Tools.AdjustRight) |
||
END HOFuns. |
END HOFuns. |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|Objeck}}== |
=={{header|Objeck}}== |
||
< |
<syntaxhighlight lang="objeck"> |
||
bundle Default { |
bundle Default { |
||
class HighOrder { |
class HighOrder { |
||
Line 1,901: | Line 2,384: | ||
} |
} |
||
} |
} |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|OCaml}}== |
=={{header|OCaml}}== |
||
A function is just a value that wants arguments: |
A function is just a value that wants arguments: |
||
< |
<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 1,913: | Line 2,396: | ||
# print_endline (func1 func2);; |
# print_endline (func1 func2);; |
||
func2 called with a string |
func2 called with a string |
||
- : unit = ()</ |
- : unit = ()</syntaxhighlight> |
||
Or, with an anonymous function: |
Or, with an anonymous function: |
||
< |
<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 = ()</ |
- : 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 1,928: | Line 2,411: | ||
We can pass a function handle (<code>@function_name</code>) |
We can pass a function handle (<code>@function_name</code>) |
||
< |
<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)</ |
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. |
||
< |
<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)</ |
computeit2(@exp, "sin", pi/3)</syntaxhighlight> |
||
=={{header|Odin}}== |
|||
<syntaxhighlight lang="odin">package main |
|||
import "core:fmt" |
|||
first :: proc(fn: proc() -> string) -> string { |
|||
return fn() |
|||
} |
|||
second :: proc() -> string { |
|||
return "second" |
|||
} |
|||
main :: proc() { |
|||
fmt.println(first(second)) // prints: second |
|||
}</syntaxhighlight> |
|||
=={{header|Oforth}}== |
=={{header|Oforth}}== |
||
Line 1,947: | Line 2,448: | ||
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 : |
||
< |
<syntaxhighlight lang="oforth">[1, 2, 3, 4, 5 ] map(#1+)</syntaxhighlight> |
||
=={{header|Ol}}== |
|||
<syntaxhighlight lang="scheme"> |
|||
; typical use: |
|||
(for-each display '(1 2 "ss" '(3 4) 8)) |
|||
; ==> 12ss(quote (3 4))8'() |
|||
; manual implementation in details: |
|||
(define (do f x) |
|||
(f x)) |
|||
(do print 12345) |
|||
; ==> 12345 |
|||
</syntaxhighlight> |
|||
=={{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. |
||
< |
<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,006: | Line 2,520: | ||
next = current |
next = current |
||
end |
end |
||
return current</ |
return current</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre>55 |
<pre>55 |
||
Line 2,020: | Line 2,534: | ||
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,049: | Line 2,563: | ||
) |
) |
||
// -> 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}}== |
||
< |
<syntaxhighlight lang="oxygenbasic"> |
||
'FUNCTION TO BE PASSED |
'FUNCTION TO BE PASSED |
||
'===================== |
'===================== |
||
Line 2,083: | Line 2,597: | ||
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. |
||
< |
<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</ |
{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 --> |
||
< |
<syntaxhighlight lang="parigp">secant_root(ff,a,b)={ |
||
e = eps() * 2; |
e = eps() * 2; |
||
aval=ff(a); |
aval=ff(a); |
||
Line 2,114: | Line 2,628: | ||
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.");</ |
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): |
||
< |
<syntaxhighlight lang="pascal">program example(output); |
||
function first(function f(x: real): real): real; |
function first(function f(x: real): real): real; |
||
Line 2,132: | Line 2,646: | ||
begin |
begin |
||
writeln(first(second)); |
writeln(first(second)); |
||
end.</ |
end.</syntaxhighlight> |
||
[[Turbo Pascal]] (will not work with Standard Pascal): |
[[Turbo Pascal]] (will not work with Standard Pascal): |
||
< |
<syntaxhighlight lang="pascal">program example; |
||
type |
type |
||
Line 2,155: | Line 2,669: | ||
begin |
begin |
||
writeln(first(second)); |
writeln(first(second)); |
||
end.</ |
end.</syntaxhighlight> |
||
=== using FreePascal : Higher-order function MAP / REDUCE ( FOLDL / FOLDR ) / FILTER === |
|||
{{works with|Free Pascal|3.2.0 }} |
|||
<syntaxhighlight lang="pascal"> |
|||
UNIT MRF; |
|||
{$mode Delphi} {$H+} {$J-} {$R+} (*) https://www.freepascal.org/docs-html/prog/progch1.html (*) |
|||
(*) |
|||
Free Pascal Compiler version 3.2.0 [2020/06/14] for x86_64 |
|||
The free and readable alternative at C/C++ speeds |
|||
compiles natively to almost any platform, including raspberry PI * |
|||
Can run independently from DELPHI / Lazarus |
|||
For debian Linux: apt -y install fpc |
|||
It contains a text IDE called fp |
|||
https://www.freepascal.org/advantage.var |
|||
(*) |
|||
INTERFACE |
|||
USES |
|||
Math, |
|||
SysUtils, |
|||
variants; |
|||
{$WARN 6058 off : Call to subroutine "$1" marked as inline is not inlined} // Use for variants |
|||
TYPE |
|||
Varyray = array of variant ; |
|||
FunA = FUNCTION ( x : variant ) : variant ; |
|||
FunB = PROCEDURE ( x : variant ) ; |
|||
FunC = FUNCTION ( x,y : variant ) : variant ; |
|||
FunD = FUNCTION ( x,y : longint ) : longint ; |
|||
FunE = FUNCTION ( x,y : variant ) : variant ; |
|||
PROCEDURE Show ( x : variant ) ; |
|||
FUNCTION Reverse ( x : Varyray ) : Varyray ; |
|||
FUNCTION Head ( x : Varyray ) : variant ; |
|||
FUNCTION Last ( x : Varyray ) : variant ; |
|||
FUNCTION Tail ( x : Varyray ) : Varyray ; |
|||
FUNCTION Take ( y : variant ; x : Varyray ) : Varyray ; |
|||
FUNCTION Map ( f : FunA ; x: Varyray ) : Varyray ; overload ; |
|||
PROCEDURE Map ( f : FunB ; x: Varyray ) ; overload ; |
|||
FUNCTION Map ( f : FunC ; x, y: Varyray ) : Varyray ; overload ; |
|||
FUNCTION Map ( f : FunD ; x, y: Varyray ) : Varyray ; overload ; |
|||
FUNCTION Filter ( f : FunA ; x: Varyray ) : Varyray ; overload ; |
|||
FUNCTION Filter ( f : FunE ; y: variant; x: Varyray ) : Varyray ; overload ; |
|||
FUNCTION FoldL ( f : FunC ; x: Varyray ) : variant ; overload ; |
|||
FUNCTION FoldL ( f : FunD ; x: Varyray ) : variant ; overload ; |
|||
FUNCTION FoldL ( f : FunE ; y: variant; x: Varyray ) : variant ; overload ; |
|||
FUNCTION Reduce ( f : FunC ; x: Varyray ) : variant ; overload ; |
|||
FUNCTION Reduce ( f : FunD ; x: Varyray ) : variant ; overload ; |
|||
FUNCTION Reduce ( f : FunE ; y: variant; x: Varyray ) : variant ; overload ; |
|||
FUNCTION FoldR ( f : FunC ; x: Varyray ) : variant ; overload ; |
|||
FUNCTION FoldR ( f : FunD ; x: Varyray ) : variant ; overload ; |
|||
(*) FOR TESTING (*) |
|||
FUNCTION RandFillInt ( x: variant ) : variant ; |
|||
FUNCTION RandFillReal ( x: variant ) : variant ; |
|||
FUNCTION AND_xy ( x, y: variant ) : variant ; |
|||
FUNCTION OR_xy ( x, y: variant ) : variant ; |
|||
FUNCTION AVG ( x: Varyray ) : variant ; |
|||
FUNCTION All ( f: FunA ; x: Varyray ) : variant ; |
|||
FUNCTION Any ( f: FunA ; x: Varyray ) : variant ; |
|||
FUNCTION Add ( x, y: variant ) : variant ; |
|||
FUNCTION Mult ( x, y: variant ) : variant ; |
|||
FUNCTION contain ( x, y: variant ) : variant ; |
|||
FUNCTION delete ( x, y: variant ) : variant ; |
|||
FUNCTION Add1 ( x: variant ) : variant ; |
|||
FUNCTION sine ( x: variant ) : variant ; |
|||
FUNCTION cosine ( x: variant ) : variant ; |
|||
FUNCTION cotangens ( x: variant ) : variant ; |
|||
FUNCTION Is_Even ( x: variant ) : variant ; |
|||
FUNCTION Is_Odd ( x: variant ) : variant ; |
|||
IMPLEMENTATION |
|||
PROCEDURE Show ( x: variant ) ; |
|||
BEGIN write( x, ' ' ) ; END ; |
|||
FUNCTION Reverse ( x : Varyray ) : Varyray ; |
|||
VAR |
|||
__ : varyray ; |
|||
k : integer ; |
|||
BEGIN |
|||
IF length ( x ) < Low ( x ) + 2 THEN Exit ; |
|||
Setlength ( __, length ( x ) ); |
|||
FOR k := Low ( x ) to High ( x ) DO |
|||
__ [ k ] := x [ High ( x ) - k ] ; |
|||
result := __ ; |
|||
Setlength ( __, 0 ); |
|||
END; |
|||
FUNCTION Head ( x : Varyray ) : variant ; |
|||
BEGIN result := x [ Low ( x ) ] ; END; |
|||
FUNCTION Last ( x : Varyray ) : variant ; |
|||
BEGIN result := x [ High ( x ) ] ; END; |
|||
FUNCTION Tail ( x : Varyray ) : Varyray ; |
|||
VAR |
|||
__ : varyray ; |
|||
k : integer ; |
|||
BEGIN |
|||
Setlength ( __, High ( x ) ); |
|||
FOR k := Low ( x ) + 1 to High ( x ) DO |
|||
__ [ k - 1 ] := x [ k ] ; |
|||
result := __ ; |
|||
Setlength ( __, 0 ); |
|||
END; |
|||
FUNCTION Take ( y : variant ; x : Varyray ) : Varyray ; |
|||
VAR |
|||
__ : varyray ; |
|||
k : integer ; |
|||
BEGIN |
|||
Setlength ( __, y ); |
|||
FOR k := Low ( x ) to y - 1 DO |
|||
__ [ k ] := x [ k ] ; |
|||
result := __ ; |
|||
Setlength ( __, 0 ); |
|||
END; |
|||
FUNCTION Map ( f: FunA ; x: Varyray ) : Varyray ; overload ; |
|||
VAR |
|||
Ar : array of variant ; |
|||
k : integer ; |
|||
BEGIN |
|||
SetLength ( Ar, length ( x ) ) ; |
|||
result := Ar ; |
|||
FOR k := Low ( Ar ) TO High ( Ar ) DO |
|||
Ar [ k ] := f ( x [ k ] ) ; |
|||
result := Ar ; |
|||
Setlength ( Ar, 0 ); |
|||
END; |
|||
PROCEDURE Map ( f: FunB ; x: Varyray ) ; overload ; |
|||
VAR |
|||
k : integer ; |
|||
BEGIN |
|||
FOR k := Low ( x ) TO High ( x ) DO f ( x [ k ] ) ; |
|||
END; |
|||
FUNCTION Map ( f: FunC ; x, y: Varyray ) : Varyray ; overload ; |
|||
VAR |
|||
Ar : array of variant ; |
|||
k : integer ; |
|||
BEGIN |
|||
SetLength ( Ar, min ( length ( x ) , length ( y ) ) ) ; |
|||
FOR k := Low ( Ar ) TO High ( Ar ) DO |
|||
Ar [ k ] := f ( x [ k ] , y [ k ] ) ; |
|||
result := Ar ; |
|||
Setlength ( Ar, 0 ); |
|||
END; |
|||
FUNCTION Map ( f: FunD ; x, y: Varyray ) : Varyray ; overload ; |
|||
VAR |
|||
Ar : array of variant ; |
|||
k : integer ; |
|||
BEGIN |
|||
SetLength ( Ar, min ( length ( x ) , length ( y ) ) ) ; |
|||
FOR k := Low ( Ar ) TO High ( Ar ) DO |
|||
Ar [ k ] := f ( x [ k ] , y [ k ] ) ; |
|||
result := Ar ; |
|||
Setlength ( Ar, 0 ); |
|||
END; |
|||
FUNCTION Map ( f: FunE ; x: variant; y: Varyray ) : Varyray ; overload ; |
|||
VAR |
|||
Ar : array of variant ; |
|||
k : integer ; |
|||
BEGIN |
|||
SetLength ( Ar, min ( length ( x ) , length ( y ) ) ) ; |
|||
FOR k := Low ( Ar ) TO High ( Ar ) DO |
|||
Ar [ k ] := f ( x , y [ k ] ) ; |
|||
result := Ar ; |
|||
Setlength ( Ar, 0 ); |
|||
END; |
|||
FUNCTION Filter ( f: FunA ; x: Varyray ) : Varyray ; overload ; |
|||
VAR |
|||
Ar : array of variant ; |
|||
__ : variant ; |
|||
k : integer ; |
|||
len : integer ; |
|||
BEGIN |
|||
SetLength ( Ar, 0 ) ; |
|||
result := Ar ; |
|||
FOR k := Low ( x ) TO High ( x ) DO |
|||
BEGIN |
|||
__ := f ( x [ k ] ) ; |
|||
IF __ <> False THEN |
|||
BEGIN |
|||
len := Length ( Ar ) ; |
|||
SetLength ( Ar, len + 1 ) ; |
|||
Ar [ len ] := __ ; |
|||
END ; |
|||
END ; |
|||
result := Ar ; |
|||
Setlength ( Ar, 0 ); |
|||
END; |
|||
FUNCTION Filter ( f: FunE ; y: variant; x: Varyray ) : Varyray ; overload ; |
|||
VAR |
|||
Ar : array of variant ; |
|||
__ : variant ; |
|||
k : integer ; |
|||
len : integer ; |
|||
BEGIN |
|||
SetLength ( Ar, 0 ) ; |
|||
result := Ar ; |
|||
FOR k := Low ( x ) TO High ( x ) DO |
|||
BEGIN |
|||
__ := f ( y, x [ k ] ) ; |
|||
IF __ <> False THEN |
|||
BEGIN |
|||
len := Length ( Ar ) ; |
|||
SetLength ( Ar, len + 1 ) ; |
|||
Ar [ len ] := __ ; |
|||
END ; |
|||
END ; |
|||
result := Ar ; |
|||
Setlength ( Ar, 0 ); |
|||
END; |
|||
FUNCTION FoldL ( f: FunC ; x: Varyray ) : variant ; overload ; |
|||
VAR |
|||
k : integer ; |
|||
BEGIN |
|||
result := x [ Low ( x ) ] ; |
|||
FOR k := Low ( x ) + 1 TO High ( x ) DO |
|||
result := f ( result , x [ k ] ) ; |
|||
END ; |
|||
FUNCTION FoldL ( f: FunD ; x: Varyray ) : variant ; overload ; |
|||
VAR |
|||
k : integer ; |
|||
BEGIN |
|||
result := x [ Low ( x ) ] ; |
|||
FOR k := Low ( x ) + 1 TO High ( x ) DO |
|||
result := f ( result , x [ k ] ) ; |
|||
END ; |
|||
FUNCTION FoldL ( f: FunE ; y: variant; x: Varyray ) : variant ; overload ; |
|||
VAR |
|||
k : integer ; |
|||
BEGIN |
|||
FOR k := Low ( x ) TO High ( x ) DO |
|||
result := f ( y , x [ k ] ) ; |
|||
END ; |
|||
FUNCTION Reduce ( f: FunC ; x: Varyray ) : variant ; overload ; |
|||
BEGIN result := FoldL ( f , x ) ; END ; |
|||
FUNCTION Reduce ( f: FunD ; x: Varyray ) : variant ; overload ; |
|||
BEGIN result := FoldL ( f , x ) ; END ; |
|||
FUNCTION Reduce ( f: FunE ; y: variant; x: Varyray ) : variant ; overload ; |
|||
BEGIN result := FoldL ( f , y, x ) ; END ; |
|||
FUNCTION FoldR ( f: FunC ; x: Varyray ) : variant ; overload ; |
|||
VAR |
|||
k : integer ; |
|||
BEGIN |
|||
result := x [ High ( x ) ] ; |
|||
FOR k := High ( x ) - 1 DOWNTO Low ( x ) DO |
|||
result := f ( result, x [ k ] ) ; |
|||
END ; |
|||
FUNCTION FoldR ( f: FunD ; x: Varyray ) : variant ; overload ; |
|||
VAR |
|||
k : integer ; |
|||
BEGIN |
|||
result := x [ High ( x ) ]; |
|||
FOR k := High ( x ) - 1 DOWNTO Low ( x ) DO |
|||
result := f ( result, x [ k ] ) ; |
|||
END ; |
|||
(*) TEST Functions (*) |
|||
(*) |
|||
Special thanks to PascalDragon , winni & BobDog ( FreePascal.org ), |
|||
who explained the specifics of the compiler. |
|||
(*) |
|||
FUNCTION Add ( x, y: variant ) : variant ; |
|||
BEGIN result := x + y ; END ; |
|||
FUNCTION Add1 ( x: variant ) : variant ; |
|||
BEGIN result := x + 1 ; END ; |
|||
FUNCTION AND_xy ( x, y: variant ) : variant ; |
|||
BEGIN result := ( x and y ) = True ; END ; |
|||
FUNCTION AVG ( x: Varyray ) : variant ; |
|||
VAR |
|||
k : integer ; |
|||
BEGIN |
|||
result := 0.0 ; |
|||
FOR k := Low ( x ) TO High ( x ) DO |
|||
result := result + ( x [ k ] - result ) / ( k + 1 ); |
|||
END ; |
|||
FUNCTION Cosine ( x: variant ) : variant ; |
|||
BEGIN result := cos ( x ); END ; |
|||
FUNCTION Cotangens ( x: variant ) : variant ; |
|||
BEGIN |
|||
IF ( x = 0 ) Then Exit ( 'Inf'); |
|||
result := cot ( x ); |
|||
END ; |
|||
FUNCTION Is_Even ( x: variant ) : variant ; |
|||
BEGIN |
|||
IF ( ( x mod 2 ) = 0 ) THEN |
|||
result := x |
|||
ELSE |
|||
result := False |
|||
END; |
|||
FUNCTION Mult( x, y: variant ) : variant ; |
|||
BEGIN result := x * y ; END ; |
|||
FUNCTION Contain ( x, y: variant ) : variant ; |
|||
BEGIN result := x = y ; END ; |
|||
FUNCTION Delete ( x, y: variant ) : variant ; |
|||
BEGIN |
|||
IF ( x = y ) THEN Exit ( False ) ; |
|||
result := y; |
|||
END ; |
|||
FUNCTION Is_Odd ( x: variant ) : variant ; |
|||
BEGIN |
|||
IF ( ( x mod 2 ) <> 0 ) THEN |
|||
result := x |
|||
ELSE |
|||
result := False |
|||
END; |
|||
FUNCTION OR_xy ( x, y: variant ) : variant ; |
|||
BEGIN result := ( x or y ) = True; END ; |
|||
FUNCTION RandFillInt ( x: variant ) : variant ; |
|||
BEGIN result := Random ( 100 ) ; END ; |
|||
FUNCTION RandFillReal ( x: variant ) : variant ; |
|||
VAR |
|||
tmp : real = 100.0 ; |
|||
BEGIN result := ( Random ( ) ) * tmp ; END ; |
|||
FUNCTION sine ( x: variant ) : variant ; |
|||
BEGIN result := sin ( x ); END ; |
|||
FUNCTION All ( f: FunA ; x: Varyray ) : variant ; |
|||
VAR |
|||
k : integer ; |
|||
BEGIN |
|||
result := True ; |
|||
FOR k := Low ( x ) TO High ( x ) DO |
|||
result := AND_xy ( result , f ( x [ k ] ) ) ; |
|||
END ; |
|||
FUNCTION Any ( f: FunA ; x: Varyray ) : variant ; |
|||
VAR |
|||
k : integer ; |
|||
BEGIN |
|||
result := False ; |
|||
FOR k := Low ( x ) TO High ( x ) DO |
|||
result := OR_xy ( result , f ( x [ k ] ) ) ; |
|||
END ; |
|||
END. |
|||
(*) === How to use in a program === (*) |
|||
program testMRF.pas; |
|||
{$mode Delphi} {$H+} {$J-} {$R+} (*) https://www.freepascal.org/docs-html/prog/progch1.html (*) |
|||
USES |
|||
MRF, |
|||
Math, |
|||
SysUtils, |
|||
Variants; |
|||
{$WARN 6058 off : Call to subroutine "$1" marked as inline is not inlined} // Use for variants |
|||
VAR |
|||
a,b,c : array of variant ; |
|||
Acc : variant ; |
|||
BEGIN |
|||
Randomize ; |
|||
setlength ( a, 6 ) ; |
|||
setlength ( b, 4 ) ; |
|||
setlength ( c, 6 ) ; |
|||
a := Map ( RandFillInt , a ) ; |
|||
Map ( show , a ) ; |
|||
writeln ; |
|||
b := Map ( RandFillInt , b ) ; |
|||
Map ( show , b ) ; |
|||
writeln ; |
|||
c := Map ( RandFillInt , c ) ; |
|||
Map ( show , c ) ; |
|||
writeln ; |
|||
Acc := FoldL ( add , a ) ; |
|||
WriteLn ( 'Sum = ' , Acc ) ; |
|||
writeln ; |
|||
Acc := Reduce ( contain , 31, a ) ; |
|||
WriteLn ( 'contains = ' , Acc ) ; |
|||
writeln ; |
|||
c := Filter ( delete , 31, a ) ; |
|||
WriteLn ( 'del c :' ) ; |
|||
Map ( show , c ) ; |
|||
writeln ; |
|||
a := Reverse ( c ) ; |
|||
WriteLn ( 'reverse c :' ) ; |
|||
Map ( show , a ) ; |
|||
writeln ; |
|||
Acc := avg ( b ) ; |
|||
WriteLn ( 'avg = ' , Acc ) ; |
|||
writeln ; |
|||
c := Map ( cotangens , b ) ; |
|||
writeln ( 'cot : ' ) ; |
|||
Map ( show , c ) ; |
|||
writeln ; |
|||
Acc := FoldR ( min , b ) ; |
|||
WriteLn ( 'min = ' , Acc ); |
|||
writeln ; |
|||
Acc := FoldR ( max , b ) ; |
|||
WriteLn ( 'max = ' , Acc ); |
|||
writeln ; |
|||
Map ( show , b ) ; |
|||
Acc := All ( Is_Odd , b ) ; |
|||
writeln ; |
|||
WriteLn ( 'All Is_Odd = ' , Acc ) ; |
|||
writeln ; |
|||
Map ( show , b ) ; |
|||
Acc := Any ( Is_Even , b ) ; |
|||
writeln ; |
|||
WriteLn ( 'Any Is_Even = ' , Acc ) ; |
|||
writeln ; |
|||
Acc := Head ( b ) ; |
|||
WriteLn ( 'Head = ' , Acc ) ; |
|||
Acc := Last ( b ) ; |
|||
WriteLn ( 'Last = ' , Acc ) ; |
|||
Map ( show , b ) ; |
|||
a := Tail ( b ) ; |
|||
writeln ; |
|||
WriteLn ( 'Tail of b :' ) ; |
|||
Map ( show , a ) ; |
|||
writeln ; |
|||
Map ( show , b ) ; |
|||
a := Take ( 2, b ) ; |
|||
writeln ; |
|||
WriteLn ( 'Take 2 from b :' ) ; |
|||
Map ( show , a ) ; |
|||
writeln ; |
|||
setlength ( c, 0 ) ; |
|||
setlength ( b, 0 ) ; |
|||
setlength ( a, 0 ) ; |
|||
END. |
|||
</syntaxhighlight>JPD 2021/07/10 |
|||
Output: |
|||
Random ( Like me :) |
|||
=={{header|Perl}}== |
=={{header|Perl}}== |
||
< |
<syntaxhighlight lang="perl">sub another { |
||
# take a function and a value |
# take a function and a value |
||
my $func = shift; |
my $func = shift; |
||
Line 2,184: | Line 3,429: | ||
); |
); |
||
print another $dispatch{$_}, 123 for qw(square cube rev);</ |
print another $dispatch{$_}, 123 for qw(square cube rev);</syntaxhighlight> |
||
< |
<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 2,193: | Line 3,438: | ||
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</ |
# OnE, twO, thrEE, fOUr</syntaxhighlight> |
||
< |
<syntaxhighlight lang="perl">sub first {shift->()} |
||
sub second {'second'} |
sub second {'second'} |
||
Line 2,201: | Line 3,446: | ||
print first \&second; |
print first \&second; |
||
print first sub{'sub'};</ |
print first sub{'sub'};</syntaxhighlight> |
||
=={{header|Perl 6}}== |
|||
The best type to use for the parameter of a higher-order function is <code>Callable</code> (implied by the <code>&</code> sigil), a role common to all function-like objects. For an example of defining and calling a second-order function, see [[Functional Composition#Perl_6|Functional Composition]]. |
|||
Convenient syntax is provided for anonymous functions, |
|||
either a bare block, or a parameterized block introduced with <tt>-></tt>, which serves as a "lambda": |
|||
<lang Perl 6>sub twice(&todo) { |
|||
todo(); todo(); # declaring &todo also defines bare function |
|||
} |
|||
twice { say "Boing!" } |
|||
# output: |
|||
# Boing! |
|||
# Boing! |
|||
sub twice-with-param(&todo) { |
|||
todo(0); todo(1); |
|||
} |
|||
twice-with-param -> $time { |
|||
say "{$time+1}: Hello!" |
|||
} |
|||
# output: |
|||
# 1: Hello! |
|||
# 2: Hello!</lang> |
|||
=={{header|Phix}}== |
=={{header|Phix}}== |
||
{{libheader|Phix/basics}} |
|||
Copy of [[Higher-order_functions#Euphoria|Euphoria]] |
|||
<!--<syntaxhighlight lang="phix">(phixonline)--> |
|||
<lang Phix>procedure use(integer fi, integer a, integer b) |
|||
<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> |
|||
print(1,call_func(fi,{a,b})) |
|||
<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> |
|||
end procedure |
|||
<span style="color: #008080;">end</span> <span style="color: #008080;">procedure</span> |
|||
function add(integer a, integer b) |
|||
<span style="color: #008080;">function</span> <span style="color: #000000;">add</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> |
|||
return a + b |
|||
<span style="color: #008080;">return</span> <span style="color: #000000;">a</span> <span style="color: #0000FF;">+</span> <span style="color: #000000;">b</span> |
|||
end function |
|||
<span style="color: #008080;">end</span> <span style="color: #008080;">function</span> |
|||
use(routine_id("add"),23,45)</lang> |
|||
<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> |
|||
<!--</syntaxhighlight>--> |
|||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
68 |
68 |
||
</pre> |
</pre> |
||
You could also use get_routine_info(fi) to retrieve the maximum and minimum number of parameters, along with a string representing the signature in roottype format, and the actual name of the routine. Above it would return {2,2,"FII","add"} indicating add is a function that takes two integers, none of which are optional. Obviously you would need to invoke functions and procedures differently, eg you cannot print the result of a procedure call, likewise for different numbers and base types of parameters. Or as above just trust you were passed something appropriate, and rely on/expect a very clear human readable fatal error message if not. |
|||
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 |
|||
<!--<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;">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> |
|||
<!--</syntaxhighlight>--> |
|||
=={{header|Phixmonti}}== |
|||
<syntaxhighlight lang="phixmonti">def suma + enddef |
|||
def apply exec enddef |
|||
23 45 getid suma apply print |
|||
</syntaxhighlight> |
|||
=={{header|PHP}}== |
=={{header|PHP}}== |
||
< |
<syntaxhighlight lang="php">function first($func) { |
||
return $func(); |
return $func(); |
||
} |
} |
||
Line 2,252: | Line 3,492: | ||
} |
} |
||
$result = first('second');</ |
$result = first('second');</syntaxhighlight> |
||
Or, with an anonymous function in PHP 5.3+: |
Or, with an anonymous function in PHP 5.3+: |
||
< |
<syntaxhighlight lang="php">function first($func) { |
||
return $func(); |
return $func(); |
||
} |
} |
||
$result = first(function() { return 'second'; });</ |
$result = first(function() { return 'second'; });</syntaxhighlight> |
||
=={{header|Picat}}== |
|||
Here are some different approaches. |
|||
The following variables and functions are assumed to be defined: |
|||
<syntaxhighlight lang="picat">go => |
|||
% ... |
|||
L = 1..10, |
|||
L2 = 1..3, |
|||
% ... |
|||
f1(X) = X**2. |
|||
f2(X,A) = X**A + A**X. |
|||
% |
|||
% qsort(List, SortFunction) |
|||
% returns a sorted list according to the sort function SortFunction |
|||
% |
|||
qsort([],_F) = []. |
|||
qsort([H|T],F) = qsort([E : E in T, call(F,E,H)], F) |
|||
++ [H] ++ |
|||
qsort([E : E in T, not call(F,E,H)],F). |
|||
% sort on length |
|||
sortf(F1,F2) => |
|||
F1.length < F2.length.</syntaxhighlight> |
|||
===Using map=== |
|||
<syntaxhighlight lang="picat"> % ... |
|||
println(map(f1,L)), |
|||
println(map($f2(3),L)), |
|||
println(map(f2,L,map(f1,L))).</syntaxhighlight> |
|||
===List comprehension=== |
|||
In general the recommended approach. |
|||
<syntaxhighlight lang="picat"> % |
|||
println([f1(I) : I in L]), |
|||
println([[I,J,f2(I,J)] : I in L, J in L2]).</syntaxhighlight> |
|||
===Apply=== |
|||
<syntaxhighlight lang="picat"> % ... |
|||
println(apply(+,1,2)), |
|||
println(apply(f2,10,22)).</syntaxhighlight> |
|||
===Sort function=== |
|||
Here is an example how to sort on length. |
|||
<syntaxhighlight lang="picat"> % ... |
|||
S = [ |
|||
"rosetta code", |
|||
"adam", |
|||
"eve", |
|||
"picat", |
|||
"pattern-matching", |
|||
"imperative", |
|||
"constraints", |
|||
"actors", |
|||
"tabling" |
|||
], |
|||
println(map(len,S)), |
|||
println(S.qsort(sortf)).</syntaxhighlight> |
|||
{{out}} |
|||
<pre>[1,4,9,16,25,36,49,64,81,100] |
|||
[4,17,54,145,368,945,2530,7073,20412,60049] |
|||
[2,32,20412,4295032832,298023223886718750,10314424798490535548348731392,256923577521058878088611477224913844394456,6277101735386680763835789423207666416102355725939011223552,196627050475552913618075908526912116283103450944214766927315565632601688195930,10000000000000000000000000000000000000000000000000000000000000000000000000000000100000000000000000000] |
|||
[1,4,9,16,25,36,49,64,81,100] |
|||
[[1,1,2],[1,2,3],[1,3,4],[2,1,3],[2,2,8],[2,3,17],[3,1,4],[3,2,17],[3,3,54],[4,1,5],[4,2,32],[4,3,145],[5,1,6],[5,2,57],[5,3,368],[6,1,7],[6,2,100],[6,3,945],[7,1,8],[7,2,177],[7,3,2530],[8,1,9],[8,2,320],[8,3,7073],[9,1,10],[9,2,593],[9,3,20412],[10,1,11],[10,2,1124],[10,3,60049]] |
|||
3 |
|||
10000000026559922791424 |
|||
[12,4,3,5,16,10,11,6,7] |
|||
[eve,adam,picat,actors,tabling,imperative,constraints,rosetta code,pattern-matching]</pre> |
|||
=={{header|PicoLisp}}== |
=={{header|PicoLisp}}== |
||
< |
<syntaxhighlight lang="picolisp">: (de first (Fun) |
||
(Fun) ) |
(Fun) ) |
||
-> first |
-> first |
||
Line 2,293: | Line 3,603: | ||
: (mapcar add (1 2 3) (4 5 6)) |
: (mapcar add (1 2 3) (4 5 6)) |
||
-> (5 7 9)</ |
-> (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 2,306: | Line 3,615: | ||
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}}== |
||
< |
<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 2,315: | Line 3,624: | ||
;;; 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) =></ |
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. |
|||
{{libheader|initlib}} |
|||
<lang> |
<syntaxhighlight lang="text"> |
||
% operator example |
|||
/x_times_3_sub_1 {3 * 1 sub}. |
|||
% 'ifelse' is passed a boolean and two procedures |
|||
[0 1 2 3 4] {x_times_3_sub_1} map |
|||
/a 5 def |
|||
</lang> |
|||
a 0 gt { (Hello!) } { (World?) } ifelse == |
|||
% procedure example |
|||
% 'bar' is loaded onto the stack and passed to 'foo' |
|||
/foo { exec } def |
|||
/bar { (Hello, world!) } def |
|||
/bar load foo == |
|||
</syntaxhighlight> |
|||
=={{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 2,333: | Line 3,650: | ||
(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 2,344: | Line 3,661: | ||
(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 2,357: | Line 3,674: | ||
=={{header|Prolog}}== |
=={{header|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}}== |
||
< |
<syntaxhighlight lang="purebasic">Prototype.d func(*text$) |
||
Procedure NumberTwo(arg$) |
Procedure NumberTwo(arg$) |
||
Line 2,376: | Line 3,693: | ||
EndProcedure |
EndProcedure |
||
NumberOne(@NumberTwo(),"Hello Worldy!")</ |
NumberOne(@NumberTwo(),"Hello Worldy!")</syntaxhighlight> |
||
=={{header|Python}}== |
=={{header|Python}}== |
||
{{works with|Python|2.5}} |
{{works with|Python|2.5}} |
||
< |
<syntaxhighlight lang="python">def first(function): |
||
return function() |
return function() |
||
Line 2,387: | Line 3,704: | ||
return "second" |
return "second" |
||
result = first(second)</ |
result = first(second)</syntaxhighlight> |
||
or |
or |
||
< |
<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 2,399: | Line 3,716: | ||
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 2,405: | Line 3,722: | ||
Hello Peter |
Hello Peter |
||
q)callFuncWithParam[sayHi] |
q)callFuncWithParam[sayHi] |
||
Hello Peter</ |
Hello Peter</syntaxhighlight> |
||
=={{header|Quackery}}== |
|||
First define the higher order functions <code>fold</code>, <code>map</code>, and <code>filter</code>. |
|||
<pre> [ over [] = iff drop done |
|||
dip |
|||
[ behead swap |
|||
' [ witheach ] ] |
|||
nested join do ] is fold ( [ x --> x ) |
|||
[ ' [ [ ] ] rot join swap |
|||
nested |
|||
' [ nested join ] join |
|||
fold ] is map ( [ x --> [ ) |
|||
[ ' [ [ ] ] rot join swap |
|||
nested ' dup swap join |
|||
' [ iff [ nested join ] |
|||
else drop ] join |
|||
fold ] is filter ( [ x --> [ ) |
|||
</pre> |
|||
Then test them in the Quackery shell by summing a nest of numbers, recursively flattening a deeply nested nest, reversing every string in a nest of strings, and removing all the negative numbers from a nest of numbers. |
|||
For another example of usage of <code>map</code> and <code>filter</code>, see <code>countchars</code> in [[Huffman coding#Quackery]]. |
|||
<pre>/O> ' [ 1 2 3 4 5 6 7 8 9 10 ] ' + fold echo |
|||
... |
|||
55 |
|||
Stack empty. |
|||
/O> forward is flatten ( x --> [ ) |
|||
... [ ' [ [ ] ] swap join |
|||
... ' [ dup nest? if |
|||
... flatten |
|||
... join ] |
|||
... fold ] resolves flatten ( x --> [ ) |
|||
... |
|||
Stack empty. |
|||
/O> ' [ 1 2 [ [ 3 4 ] ] 5 [ 6 [ 7 [ 8 [ 9 ] ] ] ] ] flatten |
|||
... echo |
|||
... |
|||
[ 1 2 3 4 5 6 7 8 9 ] |
|||
Stack empty. |
|||
/O> $ "esreveR yreve gnirts ni a tsen fo .sgnirts" nest$ |
|||
... ' reverse map |
|||
... witheach [ echo$ sp ] |
|||
... |
|||
Reverse every string in a nest of strings. |
|||
Stack empty. |
|||
/O> ' [ 42 -23 23 -42 ] |
|||
... ' [ 0 < not ] filter |
|||
... echo |
|||
... |
|||
[ 42 23 ] |
|||
Stack empty.</pre> |
|||
=={{header|R}}== |
=={{header|R}}== |
||
< |
<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))</ |
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}}== |
|||
(formerly Perl 6) |
|||
The best type to use for the parameter of a higher-order function is <code>Callable</code> (implied by the <code>&</code> sigil), a role common to all function-like objects. For an example of defining and calling a second-order function, see [[Functional Composition#Raku|Functional Composition]]. |
|||
Convenient syntax is provided for anonymous functions, |
|||
either a bare block, or a parametrized block introduced with <tt>-></tt>, which serves as a "lambda": |
|||
<syntaxhighlight lang="raku" line>sub twice(&todo) { |
|||
todo(); todo(); # declaring &todo also defines bare function |
|||
} |
|||
twice { say "Boing!" } |
|||
# output: |
|||
# Boing! |
|||
# Boing! |
|||
sub twice-with-param(&todo) { |
|||
todo(0); todo(1); |
|||
} |
|||
twice-with-param -> $time { |
|||
say "{$time+1}: Hello!" |
|||
} |
|||
# output: |
|||
# 1: Hello! |
|||
# 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. |
||
< |
<syntaxhighlight lang="raven">define doit use $v1 |
||
"doit called with " print $v1 print "\n" print |
"doit called with " print $v1 print "\n" print |
||
Line 2,432: | Line 3,837: | ||
$v2 call |
$v2 call |
||
23.54 "doit" callit</ |
23.54 "doit" callit</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre>callit called with doit |
<pre>callit called with doit |
||
doit called with 23.54 |
doit called with 23.54 |
||
</pre> |
</pre> |
||
=={{header|REBOL}}== |
=={{header|REBOL}}== |
||
< |
<syntaxhighlight lang="rebol">REBOL [ |
||
Title: "Function Argument" |
Title: "Function Argument" |
||
Author: oofoe |
|||
Date: 2009-12-19 |
|||
URL: http://rosettacode.org/wiki/Function_as_an_Argument |
URL: http://rosettacode.org/wiki/Function_as_an_Argument |
||
] |
] |
||
Line 2,469: | Line 3,873: | ||
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]</ |
print ["Unnamed:" mold map func [i][i * 2 + 1] x]</syntaxhighlight> |
||
Output: |
Output: |
||
Line 2,479: | Line 3,883: | ||
=={{header|Retro}}== |
=={{header|Retro}}== |
||
< |
<syntaxhighlight lang="retro">:disp (nq-) call n:put ; |
||
do putn ; |
|||
31 [ ( |
#31 [ (n-n) #100 * ] disp |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|REXX}}== |
=={{header|REXX}}== |
||
< |
<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 'square' , 13; say right( 'square{'$"} = ", 30) result |
|||
call function 'cube' , 3; say right( 'cube{'$"} = ", 30) result |
|||
call function 'reverse', 721; say right( 'reverse{'$"} = ", 30) result |
|||
funcName = 'cube' ; q= 3; call someFunk funcName, q; call tell |
|||
q=721; call someFunk 'reverse',q; call tell |
|||
say copies('═', 30) /*display a nice separator fence */ |
|||
say 'done as' d2x(n). /*prove that variable N is still intact*/ |
|||
exit /*stick a fork in it, we're all done. */ |
exit /*stick a fork in it, we're all done. */ |
||
/*──────────────────────────────────────────────────────────────────────────────────────*/ |
/*──────────────────────────────────────────────────────────────────────────────────────*/ |
||
cube: return |
cube: return $**3 |
||
fact: !=1; |
fact: procedure expose $; !=1; do j=2 to $; !=!*j; end; return ! |
||
function: arg ?.; parse arg ,$; signal value (?.) |
|||
fib: if n<2 then return n; _=0; a=0; b=1; do j=2 to n; _=a+b; a=b; b=_; end; return _ |
|||
reverse: return 'REVERSE'( |
reverse: return 'REVERSE'($) |
||
square: return $**2</syntaxhighlight> |
|||
someFunk: procedure; arg ?,n; signal value (?); say result 'result'; return |
|||
{{out|output|text= when using the default input:}} |
|||
square: return n**2 |
|||
tell: say right(funcName'('q") = ",20) result; return</lang> |
|||
'''output''' |
|||
<pre> |
<pre> |
||
fact{6} = 720 |
|||
square{13} = 169 |
|||
cube{3} = 27 |
|||
reverse{721} = 127 |
|||
</pre> |
|||
cube(721) = 127 |
|||
══════════════════════════════ |
|||
=={{header|Ring}}== |
|||
done as DEADBEEF. |
|||
<syntaxhighlight lang="ring"> |
|||
# Project : Higher-order functions |
|||
docalcs(1,10,"squares",:square) |
|||
docalcs(1,10,"cubes",:cube) |
|||
func square(n) |
|||
return n * n |
|||
func cube(n) |
|||
return n * n * n |
|||
func docalcs(from2,upto,title,func2) |
|||
see title + " -> " + nl |
|||
for i = from2 to upto |
|||
x = call func2(i) |
|||
see x + nl |
|||
next |
|||
see nl |
|||
</syntaxhighlight> |
|||
Output: |
|||
<pre> |
|||
squares -> |
|||
1 |
|||
4 |
|||
9 |
|||
16 |
|||
25 |
|||
36 |
|||
49 |
|||
64 |
|||
81 |
|||
100 |
|||
cubes -> |
|||
1 |
|||
8 |
|||
27 |
|||
64 |
|||
125 |
|||
216 |
|||
343 |
|||
512 |
|||
729 |
|||
1000 |
|||
</pre> |
</pre> |
||
=={{header|Ruby}}== |
=={{header|Ruby}}== |
||
With a proc (procedure): |
With a proc (procedure): |
||
< |
<syntaxhighlight lang="ruby">succ = proc{|x| x+1} |
||
def to2(&f) |
def to2(&f) |
||
f[2] |
f[2] |
||
Line 2,523: | Line 3,965: | ||
to2(&succ) #=> 3 |
to2(&succ) #=> 3 |
||
to2{|x| x+1} #=> 3</ |
to2{|x| x+1} #=> 3</syntaxhighlight> |
||
With a method: |
With a method: |
||
< |
<syntaxhighlight lang="ruby">def succ(n) |
||
n+1 |
n+1 |
||
end |
end |
||
Line 2,534: | Line 3,976: | ||
meth = method(:succ) |
meth = method(:succ) |
||
to2(meth) #=> 3</ |
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. |
||
< |
<syntaxhighlight lang="rust">fn execute_with_10<F: Fn(u64) -> u64> (f: F) -> u64 { |
||
f(10) |
f(10) |
||
} |
} |
||
Line 2,550: | Line 3,991: | ||
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 |
||
}</ |
}</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre>100 |
<pre>100 |
||
100</pre> |
100</pre> |
||
=={{header|Scala}}== |
=={{header|Scala}}== |
||
< |
<syntaxhighlight lang="scala">def functionWithAFunctionArgument(x : int, y : int, f : (int, int) => int) = f(x,y)</syntaxhighlight> |
||
Call: |
Call: |
||
< |
<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: |
||
< |
<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</ |
func2 called with a string</syntaxhighlight> |
||
Or, with an anonymous function: |
Or, with an anonymous function: |
||
< |
<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</ |
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}}== |
|||
<syntaxhighlight lang="sensetalk">function Map oldlist, func |
|||
put () into newlist |
|||
repeat with each item of oldlist |
|||
insert (func)(it) after newlist |
|||
end repeat |
|||
return newlist |
|||
end Map</syntaxhighlight> |
|||
<syntaxhighlight lang="sensetalk">put ("tomato", "aubergine", "courgette") into fruits |
|||
put Map(fruits, Uppercase) |
|||
</syntaxhighlight> |
|||
=={{header|Sidef}}== |
=={{header|Sidef}}== |
||
< |
<syntaxhighlight lang="ruby">func first(f) { |
||
return f(); |
return f(); |
||
} |
} |
||
Line 2,583: | Line 4,038: | ||
say first(second); # => "second" |
say first(second); # => "second" |
||
say first(func { "third" }); # => "third"</ |
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): |
||
< |
<syntaxhighlight lang="slate">define: #function -> [| :x | x * 3 - 1]. |
||
#(1 1 2 3 5 8) collect: function.</ |
#(1 1 2 3 5 8) collect: function.</syntaxhighlight> |
||
=={{header|Smalltalk}}== |
=={{header|Smalltalk}}== |
||
< |
<syntaxhighlight lang="smalltalk">first := [ :f | f value ]. |
||
second := [ 'second' ]. |
second := [ 'second' ]. |
||
Transcript show: (first value: second).</ |
Transcript show: (first value: second).</syntaxhighlight> |
||
< |
<syntaxhighlight lang="smalltalk">function := [:x | x * 3 - 1]. |
||
#(1 1 2 3 5 8) collect: function.</ |
#(1 1 2 3 5 8) collect: function.</syntaxhighlight> |
||
=={{header|Sparkling}}== |
=={{header|Sparkling}}== |
||
< |
<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);</ |
print(answer);</syntaxhighlight> |
||
=={{header|Standard ML}}== |
=={{header|Standard ML}}== |
||
< |
<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 2,615: | Line 4,070: | ||
- print (func1 func2 ^ "\n"); |
- print (func1 func2 ^ "\n"); |
||
func2 called with a string |
func2 called with a string |
||
val it = () : unit</ |
val it = () : unit</syntaxhighlight> |
||
Or, with an anonymous function: |
Or, with an anonymous function: |
||
< |
<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</ |
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}}== |
||
< |
<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</ |
f.({ |x| x + 1 }, 5); // returns 5</syntaxhighlight> |
||
=={{header|Swift}}== |
=={{header|Swift}}== |
||
< |
<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"</ |
println(func1(func2)) // prints "func2 called with a string"</syntaxhighlight> |
||
Or, with an anonymous function: |
Or, with an anonymous function: |
||
< |
<syntaxhighlight lang="swift">func func3<T>(f: (Int,Int)->T) -> T { return f(1, 2) } |
||
println(func3 {(x, y) in x + y}) // prints "3"</ |
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}}== |
||
< |
<syntaxhighlight lang="tcl"># this procedure executes its argument: |
||
proc demo {function} { |
proc demo {function} { |
||
$function |
$function |
||
} |
} |
||
# for example: |
# for example: |
||
demo bell</ |
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. |
||
< |
<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 2,666: | Line 4,121: | ||
demoScript { |
demoScript { |
||
parray tcl_platform |
parray tcl_platform |
||
}</ |
}</syntaxhighlight> |
||
=={{header|TI-89 BASIC}}== |
=={{header|TI-89 BASIC}}== |
||
Line 2,674: | Line 4,129: | ||
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. |
||
< |
<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})</ |
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. |
||
< |
<syntaxhighlight lang="toka">[ ." First\n" ] is first |
||
[ invoke ] is second |
[ invoke ] is second |
||
` first second</ |
` 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: |
||
< |
<syntaxhighlight lang="trith">: twice 2 times ; |
||
: hello "Hello, world!" print ; |
: hello "Hello, world!" print ; |
||
[hello] twice</ |
[hello] twice</syntaxhighlight> |
||
=={{header|TXR}}== |
=={{header|TXR}}== |
||
Line 2,697: | Line 4,152: | ||
<code>lambda</code> passed to <code>mapcar</code> with environment capture: |
<code>lambda</code> passed to <code>mapcar</code> with environment capture: |
||
< |
<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 2,704: | Line 4,159: | ||
@ (rep)@a:@(last)@a@(end) |
@ (rep)@a:@(last)@a@(end) |
||
@ (end) |
@ (end) |
||
@(end)</ |
@(end)</syntaxhighlight> |
||
<pre>1:a:t |
<pre>1:a:t |
||
Line 2,710: | Line 4,165: | ||
3:c:s</pre> |
3:c:s</pre> |
||
=={{header|uBasic/4tH}}== |
|||
{{trans|BBC BASIC}} |
|||
<syntaxhighlight lang="text">' Test passing a function to a function: |
|||
Print FUNC(_FNtwo(_FNone, 10, 11)) |
|||
End |
|||
' Function to be passed: |
|||
_FNone Param (2) : Return ((a@ + b@)^2) |
|||
' Function taking a function as an argument: |
|||
_FNtwo Param (3) : Return (FUNC(a@ (b@, c@)))</syntaxhighlight> |
|||
{{out}} |
|||
<pre>441 |
|||
0 OK, 0:79</pre> |
|||
=={{header|Ursa}}== |
=={{header|Ursa}}== |
||
{{trans|Python}} |
{{trans|Python}} |
||
Functions are first-class objects in Ursa. |
Functions are first-class objects in Ursa. |
||
< |
<syntaxhighlight lang="ursa">def first (function f) |
||
return (f) |
return (f) |
||
end |
end |
||
Line 2,722: | Line 4,192: | ||
out (first second) endl console |
out (first second) endl console |
||
# "second" is output to the console</ |
# "second" is output to the console</syntaxhighlight> |
||
=={{header|Ursala}}== |
=={{header|Ursala}}== |
||
Line 2,730: | Line 4,200: | ||
equivalent to the given functon composed with itself. |
equivalent to the given functon composed with itself. |
||
< |
<syntaxhighlight lang="ursala">(autocomposition "f") "x" = "f" "f" "x"</syntaxhighlight> |
||
test program: |
test program: |
||
< |
<syntaxhighlight lang="ursala">#import flo |
||
#cast %e |
#cast %e |
||
example = autocomposition(sqrt) 16.0</ |
example = autocomposition(sqrt) 16.0</syntaxhighlight> |
||
output: |
output: |
||
<pre>2.000000e+00</pre> |
<pre>2.000000e+00</pre> |
||
=={{header|V}}== |
=={{header|V}}== |
||
Define first as multiplying two numbers on stack |
Define first as multiplying two numbers on stack |
||
<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 |
<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 |
<syntaxhighlight lang="v">2 3 [first] second</syntaxhighlight> |
||
=6 |
=6 |
||
=={{header|VBA}}== |
|||
Based on the Pascal solution |
|||
<syntaxhighlight lang="pascal">Sub HigherOrder() |
|||
Dim result As Single |
|||
result = first("second") |
|||
MsgBox result |
|||
End Sub |
|||
Function first(f As String) As Single |
|||
first = Application.Run(f, 1) + 2 |
|||
End Function |
|||
Function second(x As Single) As Single |
|||
second = x / 2 |
|||
End Function</syntaxhighlight> |
|||
=={{header|Visual Basic .NET}}== |
|||
Each example below performs the same task and utilizes .NET delegates, which are objects that refer to a static method or to an instance method of a particular object instance. |
|||
c.f. [[#C#|C#]] |
|||
{{out|note=for each example}} |
|||
<pre>f=Add, f(6, 2) = 8 |
|||
f=Mul, f(6, 2) = 12 |
|||
f=Div, f(6, 2) = 3</pre> |
|||
===Named methods=== |
|||
{{trans|C#: Named methods}} |
|||
<syntaxhighlight lang="vbnet">' Delegate declaration is similar to C#. |
|||
Delegate Function Func2(a As Integer, b As Integer) As Integer |
|||
Module Program |
|||
Function Add(a As Integer, b As Integer) As Integer |
|||
Return a + b |
|||
End Function |
|||
Function Mul(a As Integer, b As Integer) As Integer |
|||
Return a * b |
|||
End Function |
|||
Function Div(a As Integer, b As Integer) As Integer |
|||
Return a \ b |
|||
End Function |
|||
' Call is a keyword and must be escaped using brackets. |
|||
Function [Call](f As Func2, a As Integer, b As Integer) As Integer |
|||
Return f(a, b) |
|||
End Function |
|||
Sub Main() |
|||
Dim a = 6 |
|||
Dim b = 2 |
|||
' Delegates in VB.NET could be created without a New expression from the start. Both syntaxes are shown here. |
|||
Dim add As Func2 = New Func2(AddressOf Program.Add) |
|||
' The "As New" idiom applies to delegate creation. |
|||
Dim div As New Func2(AddressOf Program.Div) |
|||
' Directly coercing the AddressOf expression: |
|||
Dim mul As Func2 = AddressOf Program.Mul |
|||
Console.WriteLine("f=Add, f({0}, {1}) = {2}", a, b, [Call](add, a, b)) |
|||
Console.WriteLine("f=Mul, f({0}, {1}) = {2}", a, b, [Call](mul, a, b)) |
|||
Console.WriteLine("f=Div, f({0}, {1}) = {2}", a, b, [Call](div, a, b)) |
|||
End Sub |
|||
End Module</syntaxhighlight> |
|||
===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. |
|||
<syntaxhighlight lang="vbnet">Module Program |
|||
' 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 |
|||
Return f(a, b) |
|||
End Function |
|||
Sub Main() |
|||
Dim a = 6 |
|||
Dim b = 2 |
|||
Console.WriteLine("f=Add, f({0}, {1}) = {2}", a, b, [Call](Function(x As Integer, y As Integer) x + y, a, b)) |
|||
' With inferred parameter types: |
|||
Console.WriteLine("f=Mul, f({0}, {1}) = {2}", a, b, [Call](Function(x, y) x * y, a, b)) |
|||
' The block syntax must be used in order to specify a return type. As there is no target type in this case, the parameter types must be explicitly specified. anon has an anonymous, compiler-generated type. |
|||
Dim anon = Function(x As Integer, y As Integer) As Integer |
|||
Return x \ y |
|||
End Function |
|||
' Parameters are contravariant and the return type is covariant. Note that this conversion is not valid CLR variance (which disallows boxing conversions) and so is compiled as an additional anonymous delegate that explicitly boxes the return value. |
|||
Dim example As Func(Of Integer, Integer, Object) = anon |
|||
' Dropped-return-type conversion. |
|||
Dim example2 As Action(Of Integer, Integer) = anon |
|||
Console.WriteLine("f=Div, f({0}, {1}) = {2}", a, b, [Call](anon, a, b)) |
|||
End Sub |
|||
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 2,768: | Line 4,336: | ||
write(dotwice(addone,2)), |
write(dotwice(addone,2)), |
||
succeed(). |
succeed(). |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|Wren}}== |
|||
<syntaxhighlight lang="wren">var first = Fn.new { |f| |
|||
System.print("first function called") |
|||
f.call() |
|||
} |
|||
var second = Fn.new { System.print("second function called") } |
|||
first.call(second)</syntaxhighlight> |
|||
{{out}} |
|||
<pre> |
|||
first function called |
|||
second function called |
|||
</pre> |
|||
=={{header|Z80 Assembly}}== |
|||
Higher-order functions are often used for IRQ handlers which don't have a lot of time to figure out what to do. (I'll admit this is a bit of a stretch since typically the function that receives the IRQ handler as a parameter just calls it and does nothing else.) |
|||
Typically, the IRQ handler will jump to RAM, and before the program is in a state where the IRQ conditions will be met (such as a video game during a level transition), the function will be passed (sometimes even by value!) to the IRQ handler. On the Game Boy and the ZX Spectrum, RSTs are in ROM and thus cannot be changed at runtime, so there's not much of a choice. |
|||
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. |
|||
<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. |
|||
jp &ff80 |
|||
;more code goes here |
|||
;during setup, we'll CALL SetupDMA before enabling the vblank IRQ. |
|||
SetupDMA: |
|||
ld bc,DMACopyEnd-DMACopy ;how many bytes to copy |
|||
ld hl,DMACopy ;pointer to source |
|||
ld de,&ff80 ;pointer to destination |
|||
z_ldir ;macro for LDIR which the game boy doesn't have. |
|||
ret |
|||
DMACopy: ;must be run from &ff80 |
|||
push af |
|||
ld a,>GBSpriteCache ;high byte of wherever we're storing our object attribute memory |
|||
gb_out <dma ;start the transfer - DMA auto-copies 256 bytes from xx00-xxFF where xx = >GBSpriteCache |
|||
ld a,&28 ;delay - this ensures the DMA is done before we exit. Adjust to your liking. |
|||
;game boy doesn't have in/out commands, rather all its I/O ports are at &FFxx so there are special commands just for accessing them faster |
|||
;gb_out is a macro that inlines the bytecode, since not all assemblers auto-convert LD (&FFxx),a. |
|||
DMACopyWait: |
|||
dec a |
|||
jr nz,DMACopyWait |
|||
pop af |
|||
reti |
|||
DMACopyEnd:</syntaxhighlight> |
|||
=={{header|zkl}}== |
=={{header|zkl}}== |
||
Everything is a first class object so |
Everything is a first class object so |
||
< |
<syntaxhighlight lang="zkl">fcn f(g){ g() } fcn g{ "Hello World!".println() }</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 2,779: | Line 4,405: | ||
</pre> |
</pre> |
||
or |
or |
||
< |
<syntaxhighlight lang="zkl">fcn f(g){ g() } |
||
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. |
||
< |
<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)</ |
30 PRINT FN f("n",10,11)</syntaxhighlight> |
||
{{omit from|GUISS}} |
{{omit from|GUISS}} |
Latest revision as of 03:15, 17 March 2024
You are encouraged to solve this task according to the task description, using any language you may know.
- Task
Pass a function as an argument to another function.
- Related task
11l
F first(function)
R function()
F second()
R ‘second’
V result = first(second)
print(result)
- Output:
second
6502 Assembly
For the most part, it's easier to call two functions back to back. However passing functions as arguments can still be done.
Code is called using the following macro, e.g. PrintOutput #$FF,foo
. The printing routine is left unimplemented.
macro PrintOutput,input,addr
; input: desired function's input
; addr: function you wish to call
LDA #<\addr ;#< represents this number's low byte
STA z_L
LDA #>\addr ;#> represents this number's high byte
STA z_H
LDA \input
JSR doPrintOutput
endm
PrintOutput:
; prints the output of the function "foo" to the screen.
; input:
; A = input for the function "foo".
; z_L = contains the low byte of the memory address of "foo"
; z_H = contains the high byte of the memory address of "foo"
pha
LDA z_L
STA smc+1 ;store in the low byte of the operand
LDA z_H
STA smc+2 ;store in the high byte of the operand
pla
smc:
JSR $1234
;uses self-modifying code to overwrite the destination with the address of the passed function.
;assuming that function ends in an RTS, execution will return to this line after the function is done.
JSR PrintAccumulator
rts
68000 Assembly
This trivial example shows a simple return spoof.
LEA foo,A0
JSR bar
JMP * ;HALT
bar:
MOVE.L A0,-(SP)
RTS ;JMP foo
foo:
RTS ;do nothing and return. This rts retuns execution just after "JSR bar" but before "JMP *".
8th
: pass-me
"I was passed\n" . ;
: passer
w:exec ;
\ pass 'pass-me' to 'passer'
' pass-me passer
- Output:
I was passed
ActionScript
package {
public class MyClass {
public function first(func:Function):String {
return func.call();
}
public function second():String {
return "second";
}
public static function main():void {
var result:String = first(second);
trace(result);
result = first(function() { return "third"; });
trace(result);
}
}
}
Ada
Simple Example
with Ada.Text_Io; use Ada.Text_Io;
procedure Subprogram_As_Argument is
type Proc_Access is access procedure;
procedure Second is
begin
Put_Line("Second Procedure");
end Second;
procedure First(Proc : Proc_Access) is
begin
Proc.all;
end First;
begin
First(Second'Access);
end Subprogram_As_Argument;
Complex Example
with Ada.Text_Io; use Ada.Text_Io;
procedure Subprogram_As_Argument_2 is
-- Definition of an access to long_float
type Lf_Access is access Long_Float;
-- Definition of a function returning Lf_Access taking an
-- integer as a parameter
function Func_To_Be_Passed(Item : Integer) return Lf_Access is
Result : Lf_Access := new Long_Float;
begin
Result.All := 3.14159 * Long_Float(Item);
return Result;
end Func_To_Be_Passed;
-- Definition of an access to function type matching the function
-- signature above
type Func_Access is access function(Item : Integer) return Lf_Access;
-- Definition of an integer access type
type Int_Access is access Integer;
-- Define a function taking an instance of Func_Access as its
-- parameter and returning an integer access type
function Complex_Func(Item : Func_Access; Parm2 : Integer) return Int_Access is
Result : Int_Access := new Integer;
begin
Result.All := Integer(Item(Parm2).all / 3.14149);
return Result;
end Complex_Func;
-- Declare an access variable to hold the access to the function
F_Ptr : Func_Access := Func_To_Be_Passed'access;
-- Declare an access to integer variable to hold the result
Int_Ptr : Int_Access;
begin
-- Call the function using the access variable
Int_Ptr := Complex_Func(F_Ptr, 3);
Put_Line(Integer'Image(Int_Ptr.All));
end Subprogram_As_Argument_2;
Aime
integer
average(integer p, integer q)
{
return (p + q) / 2;
}
void
out(integer p, integer q, integer (*f) (integer, integer))
{
o_integer(f(p, q));
o_byte('\n');
}
integer
main(void)
{
# display the minimum, the maximum and the average of 117 and 319
out(117, 319, min);
out(117, 319, max);
out(117, 319, average);
return 0;
}
ALGOL 68
PROC first = (PROC(LONG REAL)LONG REAL f) LONG REAL:
(
f(1) + 2
);
PROC second = (LONG REAL x)LONG REAL:
(
x/2
);
main: (
printf(($xg(5,2)l$,first(second)))
)
Output:
+2.50
AmigaE
The {} takes the pointer to an object (code/functions, variables and so on); Amiga E does not distinguish nor check anything, so it is up to the programmer to use the pointer properly. For this reason, a warning is always raised when a variable (func, holding a pointer to a real function in our case) is used like a function.
PROC compute(func, val)
DEF s[10] : STRING
WriteF('\s\n', RealF(s,func(val),4))
ENDPROC
PROC sin_wrap(val) IS Fsin(val)
PROC cos_wrap(val) IS Fcos(val)
PROC main()
compute({sin_wrap}, 0.0)
compute({cos_wrap}, 3.1415)
ENDPROC
AntLang
twice:{x[x[y]]}
echo twice "Hello!"
AppleScript
-- This handler takes a script object (singer)
-- with another handler (call).
on sing about topic by singer
call of singer for "Of " & topic & " I sing"
end sing
-- Define a handler in a script object,
-- then pass the script object.
script cellos
on call for what
say what using "Cellos"
end call
end script
sing about "functional programming" by cellos
-- Pass a different handler. This one is a closure
-- that uses a variable (voice) from its context.
on hire for voice
script
on call for what
say what using voice
end call
end script
end hire
sing about "closures" by (hire for "Pipe Organ")
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.
We could, for example, write map, fold/reduce and filter functions for AppleScript as follows:
on run
-- PASSING FUNCTIONS AS ARGUMENTS TO
-- MAP, FOLD/REDUCE, AND FILTER, ACROSS A LIST
set lstRange to {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10}
map(squared, lstRange)
--> {0, 1, 4, 9, 16, 25, 36, 49, 64, 81, 100}
foldl(summed, 0, map(squared, lstRange))
--> 385
filter(isEven, lstRange)
--> {0, 2, 4, 6, 8, 10}
-- OR MAPPING OVER A LIST OF FUNCTIONS
map(testFunction, {doubled, squared, isEven})
--> {{0, 2, 4, 6, 8, 10, 12, 14, 16, 18, 20},
-- {0, 1, 4, 9, 16, 25, 36, 49, 64, 81, 100},
-- {true, false, true, false, true, false, true, false, true, false, true}}
end run
-- testFunction :: (a -> b) -> [b]
on testFunction(f)
map(f, {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10})
end testFunction
-- MAP, REDUCE, FILTER
-- Returns a new list consisting of the results of applying the
-- provided function to each element of the first list
-- map :: (a -> b) -> [a] -> [b]
on map(f, xs)
tell mReturn(f)
set lng to length of xs
set lst to {}
repeat with i from 1 to lng
set end of lst to |λ|(item i of xs, i, xs)
end repeat
return lst
end tell
end map
-- Applies a function against an accumulator and
-- each list element (from left-to-right) to reduce it
-- to a single return value
-- In some languages, like JavaScript, this is called reduce()
-- Arguments: function, initial value of accumulator, list
-- foldl :: (a -> b -> a) -> a -> [b] -> a
on foldl(f, startValue, xs)
tell mReturn(f)
set v to startValue
set lng to length of xs
repeat with i from 1 to lng
set v to |λ|(v, item i of xs, i, xs)
end repeat
return v
end tell
end foldl
-- Sublist of those elements for which the predicate
-- function returns true
-- filter :: (a -> Bool) -> [a] -> [a]
on filter(f, xs)
tell mReturn(f)
set lst to {}
set lng to length of xs
repeat with i from 1 to lng
set v to item i of xs
if |λ|(v, i, xs) then set end of lst to v
end repeat
return lst
end tell
end filter
-- Lift 2nd class handler function into 1st class script wrapper
-- mReturn :: Handler -> Script
on mReturn(f)
if class of f is script then
f
else
script
property |λ| : f
end script
end if
end mReturn
-- HANDLER FUNCTIONS TO BE PASSED AS ARGUMENTS
-- squared :: Number -> Number
on squared(x)
x * x
end squared
-- doubled :: Number -> Number
on doubled(x)
x * 2
end doubled
-- summed :: Number -> Number -> Number
on summed(a, b)
a + b
end summed
-- isEven :: Int -> Bool
on isEven(x)
x mod 2 = 0
end isEven
- Output:
{{0, 2, 4, 6, 8, 10, 12, 14, 16, 18, 20},
{0, 1, 4, 9, 16, 25, 36, 49, 64, 81, 100},
{true, false, true, false, true, false, true, false, true, false, true}}
Alternative description
In plain English, one handler can be passed as a parameter to another either in a script object …
script aScript
on aHandler(aParameter)
say aParameter
end aHandler
end script
on receivingHandler(passedScript)
passedScript's aHandler("Hello")
end receivingHandler
receivingHandler(aScript)
… or directly, with the passed pointer being assigned to a script object property upon receipt:
on aHandler(aParameter)
say aParameter
end aHandler
on receivingHandler(passedHandler)
script o
property h : passedHandler
end script
o's h("Hello")
end receivingHandler
receivingHandler(aHandler)
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.
An alternative to the script object property in the second case would be a global or property of the main script (the one containing the receiving handler), but this isn't recommended owing to the possibilities for conflict.
Arturo
doSthWith: function [x y f][
f x y
]
print [ "add:" doSthWith 2 3 $[x y][x+y] ]
print [ "multiply:" doSthWith 2 3 $[x y][x*y] ]
- Output:
add: 5 multiply: 6
ATS
#include
"share/atspre_staload.hats"
fun app_to_0 (f: (int) -> int): int = f (0)
implement
main0 () =
{
//
val () = assertloc (app_to_0(lam(x) => x+1) = 1)
val () = assertloc (app_to_0(lam(x) => 10*(x+1)) = 10)
//
} (* end of [main0] *)
AutoHotkey
f(x) {
return "This " . x
}
g(x) {
return "That " . x
}
show(fun) {
msgbox % %fun%("works")
}
show(Func("f")) ; either create a Func object
show("g") ; or just name the function
return
BBC BASIC
REM Test passing a function to a function:
PRINT FNtwo(FNone(), 10, 11)
END
REM Function to be passed:
DEF FNone(x, y) = (x + y) ^ 2
REM Function taking a function as an argument:
DEF FNtwo(RETURN f%, x, y) = FN(^f%)(x, y)
Output:
441
Binary Lambda Calculus
Every BLC program uses higher order functions, since the parsed lambda term is applied to the remainder of input, which is, like everything in lambda calculus, itself a function. For example, the empty input is nil = \x\y.y
. So the following minimal 4-bit BLC program passes nil to the identity function:
0010
BQN
BQN has built-in support for higher order functions.
A function's name in lowercase can be used to pass it as a subject, rather than a function to be executed.
Uniq ← ⍷
•Show uniq {𝕎𝕩} 5‿6‿7‿5
⟨ 5 6 7 ⟩
Bracmat
( (plus=a b.!arg:(?a.?b)&!a+!b)
& ( print
= text a b func
. !arg:(?a.?b.(=?func).?text)
& out$(str$(!text "(" !a "," !b ")=" func$(!a.!b)))
)
& print$(3.7.'$plus.add)
& print
$ ( 3
. 7
. (=a b.!arg:(?a.?b)&!a*!b)
. multiply
)
);
Output:
add(3,7)=10 multiply(3,7)=21
Brat
add = { a, b | a + b }
doit = { f, a, b | f a, b }
p doit ->add 1 2 #prints 3
Bruijn
Everything in bruijn is a function (including strings and numbers), so even
main [0]
would be a valid solution since the argument of main
is already a functional encoding of stdin.
A more obvious example:
first [0 [[0]]]
second [first [[1]]]
:test (second) ([[[[0]]]])
Burlesque
Burlesque doesn't have functions in the usual sense. One can think of blocks in Burlesque as anonymous functions. 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):
blsq ) {1 2 3 4}{5.+}m[
{6 7 8 9}
C
Simple example
The pointer to the function to be passed as an argument is the only involved pointer.
Definition of a function whose only parameter is a pointer to a function with no parameters and no return value:
void myFuncSimple( void (*funcParameter)(void) )
{
/* ... */
(*funcParameter)(); /* Call the passed function. */
funcParameter(); /* Same as above with slight different syntax. */
/* ... */
}
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".
Call:
void funcToBePassed(void);
/* ... */
myFuncSimple(&funcToBePassed);
Complex example
Definition of a function whose return value is a pointer to int and whose only parameter is a pointer to a function, whose (in turn) return value is a pointer to double and whose only parameter is a pointer to long.
int* myFuncComplex( double* (*funcParameter)(long* parameter) )
{
long inLong;
double* outDouble;
long *inLong2 = &inLong;
/* ... */
outDouble = (*funcParameter)(&inLong); /* Call the passed function and store returned pointer. */
outDouble = funcParameter(inLong2); /* Same as above with slight different syntax. */
/* ... */
}
Call:
double* funcToBePassed(long* parameter);
/* ... */
int* outInt;
outInt = myFuncComplex(&funcToBePassed);
Pointer
Finally, declaration of a pointer variable of the proper type to hold such a function as myFunc:
int* (*funcPointer)( double* (*funcParameter)(long* parameter) );
/* ... */
funcPointer = &myFuncComplex;
Of course, in a real project you shouldn't write such a convoluted code, but use some typedef instead, in order to break complexity into steps.
C#
Each example below performs the same task and utilizes .NET delegates, which are objects that refer to a static method or to an instance method of a particular object instance.
- Output (for each example):
f=Add, f(6, 2) = 8 f=Mul, f(6, 2) = 12 f=Div, f(6, 2) = 3
Named methods
This implementation works in all standard versions of C#.
using System;
// A delegate declaration. Because delegates are types, they can exist directly in namespaces.
delegate int Func2(int a, int b);
class Program
{
static int Add(int a, int b)
{
return a + b;
}
static int Mul(int a, int b)
{
return a * b;
}
static int Div(int a, int b)
{
return a / b;
}
static int Call(Func2 f, int a, int b)
{
// Invoking a delegate like a method is syntax sugar; this compiles down to f.Invoke(a, b);
return f(a, b);
}
static void Main()
{
int a = 6;
int b = 2;
// Delegates must be created using the "constructor" syntax in C# 1.0; in C# 2.0 and above, only the name of the method is required (when a target type exists, such as in an assignment to a variable with a delegate type or usage in a function call with a parameter of a delegate type; initializers of implicitly typed variables must use the constructor syntax as a raw method has no delegate type). Overload resolution is performed using the parameter types of the target delegate type.
Func2 add = new Func2(Add);
Func2 mul = new Func2(Mul);
Func2 div = new Func2(Div);
Console.WriteLine("f=Add, f({0}, {1}) = {2}", a, b, Call(add, a, b));
Console.WriteLine("f=Mul, f({0}, {1}) = {2}", a, b, Call(mul, a, b));
Console.WriteLine("f=Div, f({0}, {1}) = {2}", a, b, Call(div, a, b));
}
}
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.
using System;
delegate int Func2(int a, int b);
class Program
{
static int Call(Func2 f, int a, int b)
{
return f(a, b);
}
static void Main()
{
int a = 6;
int b = 2;
Console.WriteLine("f=Add, f({0}, {1}) = {2}", a, b, Call(delegate(int x, int y) { return x + y; }, a, b));
Console.WriteLine("f=Mul, 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));
}
}
C# 3.0: Lambda expressions
Lambda expressions were added in C# 3.0 as a more concise replacement to anonymous methods. The target delegate type must also be known at compile-time.
With .NET Framework 3.5, the System namespace also gained the Func and Action "families" of generic delegate types. Action delegates are void-returning, while Func delegates return a value of a specified type. In both families, a separate type exists for every function arity from zero to sixteen, as .NET does not have variadic generics.
For instance, the Action
delegate has no parameters, Action<T>
, has one parameter of type T, Action<T1, T2>
has two parameters of types T1 and T2, and so on. Similarly, Func<TResult>
has no parameters and a return type of TResult, Func<T1, TResult>
additionally has one parameter of type T, and so on.
using System;
class Program
{
static int Call(Func<int, int, int> f, int a, int b)
{
return f(a, b);
}
static void Main()
{
int a = 6;
int b = 2;
// No lengthy delegate keyword.
Console.WriteLine("f=Add, f({0}, {1}) = {2}", a, b, Call((int x, int y) => { return x + y; }, a, b));
// Parameter types can be inferred.
Console.WriteLine("f=Mul, f({0}, {1}) = {2}", a, b, Call((x, y) => { return x * y; }, a, b));
// Expression lambdas are even shorter (and are most idiomatic).
Console.WriteLine("f=Div, f({0}, {1}) = {2}", a, b, Call((x, y) => x / y, a, b));
}
}
C++
Function Pointer
C++ can pass function pointers in the same manner as C.
Function class template
Using the std::tr1::function class template allows more powerful usage. function<> can be used to pass around arbitrary function objects. This permits them to be used as closures.
For C++11 this is now std::function.
// Use <functional> for C++11
#include <tr1/functional>
#include <iostream>
using namespace std;
using namespace std::tr1;
void first(function<void()> f)
{
f();
}
void second()
{
cout << "second\n";
}
int main()
{
first(second);
}
Template and Inheritance
#include <iostream>
#include <functional>
template<class Func>
typename Func::result_type first(Func func, typename Func::argument_type arg)
{
return func(arg);
}
class second : public std::unary_function<int, int>
{
public:
result_type operator()(argument_type arg) const
{
return arg * arg;
}
};
int main()
{
std::cout << first(second(), 2) << std::endl;
return 0;
}
Clean
Take a function as an argument and apply it to all elements in a list:
map f [x:xs] = [f x:map f xs]
map f [] = []
Pass a function as an argument:
incr x = x + 1
Start = map incr [1..10]
Do the same using a anonymous function:
Start = map (\x -> x + 1) [1..10]
Do the same using currying:
Start = map ((+) 1) [1..10]
Clojure
(defn append-hello [s]
(str "Hello " s))
(defn modify-string [f s]
(f s))
(println (modify-string append-hello "World!"))
CLU
% Functions can be passed to other functions using the 'proctype'
% type generator. The same works for iterators, using 'itertype'
% Here are two functions
square = proc (n: int) returns (int) return (n*n) end square
cube = proc (n: int) returns (int) return (n*n*n) end cube
% Here is a function that takes another function
do_calcs = proc (from, to: int, title: string,
fn: proctype (int) returns (int))
po: stream := stream$primary_output()
stream$putleft(po, title, 8)
stream$puts(po, " -> ")
for i: int in int$from_to(from,to) do
stream$putright(po, int$unparse(fn(i)), 5)
end
stream$putc(po, '\n')
end do_calcs
start_up = proc ()
do_calcs(1, 10, "Squares", square)
do_calcs(1, 10, "Cubes", cube)
end start_up
- Output:
Squares -> 1 4 9 16 25 36 49 64 81 100 Cubes -> 1 8 27 64 125 216 343 512 729 1000
CoffeeScript
Passing an anonymous function to built-in map/reduce functions:
double = [1,2,3].map (x) -> x*2
Using a function stored in a variable:
fn = -> return 8
sum = (a, b) -> a() + b()
sum(fn, fn) # => 16
List comprehension with a function argument:
bowl = ["Cheese", "Tomato"]
smash = (ingredient) ->
return "Smashed #{ingredient}"
contents = smash ingredient for ingredient in bowl
# => ["Smashed Cheese", "Smashed Tomato"]
Nested function passing:
double = (x) -> x*2
triple = (x) -> x*3
addOne = (x) -> x+1
addOne triple double 2 # same as addOne(triple(double(2)))
A function that returns a function that returns a function that returns a function that returns 2, immediately executed:
(-> -> -> -> 2 )()()()() # => 2
A function that takes a function that takes a function argument:
((x)->
2 + x(-> 5)
)((y) -> y()+3)
# result: 10
Common Lisp
In Common Lisp, functions are first class objects, so you can pass function objects as arguments to other functions:
CL-USER> (defun add (a b) (+ a b))
ADD
CL-USER> (add 1 2)
3
CL-USER> (defun call-it (fn x y)
(funcall fn x y))
CALL-IT
CL-USER> (call-it #'add 1 2)
3
The Common Lisp library makes extensive use of higher-order functions:
CL-USER> (funcall #'+ 1 2 3) 6 CL-USER> (apply #'+ (list 1 2 3)) 6 CL-USER> (sort (string-downcase "Common Lisp will bend your mind!") #'string<) " !bcddeiiilllmmmnnnoooprsuwy" CL-USER> (reduce #'/ '(1 2 3 4 5)) 1/120 CL-USER> (mapcar #'(lambda (n) (expt 2 n)) '(0 1 2 3 4 5)) (1 2 4 8 16 32) CL-USER>
Cowgol
include "cowgol.coh";
# In order to pass functions around, you must first define an interface.
# This is similar to a delegate in C#; it becomes a function pointer type.
# This interface takes two integers and returns one.
interface Dyadic(x: int32, y: int32): (r: int32);
# For a function to be able to be passed around, it must explicitly implement
# an interface. Then it has the same type as that interface.
# The interface replaces the method's parameter list entirely.
sub Add implements Dyadic is
r := x + y;
end sub;
# Here are the other basic operators.
sub Sub implements Dyadic is r := x - y; end sub;
sub Mul implements Dyadic is r := x * y; end sub;
sub Div implements Dyadic is r := x / y; end sub;
# An interface is just like any other type, and the functions that implement
# it are first-class values. For example, this code maps the operator
# characters to their functions.
record Operator is
char: uint8;
func: Dyadic;
end record;
var operators: Operator[] := {
{'+', Add}, {'-', Sub}, {'*', Mul}, {'/', Div},
{0, Dyadic}
};
# This is a function that applies such a function to two values
sub apply(f: Dyadic, x: int32, y: int32): (r: int32) is
r := f(x,y); # the function can be called as normal
end sub;
# And this is a function that applies all the above operators to two values
sub showAll(ops: [Operator], x: int32, y: int32) is
while ops.char != 0 loop
print_i32(x as uint32);
print_char(' ');
print_char(ops.char);
print_char(' ');
print_i32(y as uint32);
print(" = ");
print_i32(apply(ops.func, x, y) as uint32);
print_nl();
ops := @next ops;
end loop;
end sub;
showAll(&operators[0], 84, 42); # example
- Output:
84 + 42 = 126 84 - 42 = 42 84 * 42 = 3528 84 / 42 = 2
D
int hof(int a, int b, int delegate(int, int) f) {
return f(a, b);
}
void main() {
import std.stdio;
writeln("Add: ", hof(2, 3, (a, b) => a + b));
writeln("Multiply: ", hof(2, 3, (a, b) => a * b));
}
- Output:
Add: 5 Multiply: 6
This longer and more systematic example shows D functions/delegates by passing each type of function/delegate to _test_ as argument.
import std.stdio;
// Test the function argument.
string test(U)(string scopes, U func) {
string typeStr = typeid(typeof(func)).toString();
string isFunc = (typeStr[$ - 1] == '*') ? "function" : "delegate";
writefln("Hi, %-13s : scope: %-8s (%s) : %s",
func(), scopes, isFunc, typeStr );
return scopes;
}
// Normal module level function.
string aFunction() { return "Function"; }
// Implicit-Function-Template-Instantiation (IFTI) Function.
T tmpFunc(T)() { return "IFTI.function"; }
// Member in a template.
template tmpGroup(T) {
T t0(){ return "Tmp.member.0"; }
T t1(){ return "Tmp.member.1"; }
T t2(){ return "Tmp.member.2"; }
}
// Used for implementing member function at class & struct.
template Impl() {
static string aStatic() { return "Static Method"; }
string aMethod() { return "Method"; }
}
class C { mixin Impl!(); }
struct S { mixin Impl!(); }
void main() {
// Nested function.
string aNested() {
return "Nested";
}
// Bind to a variable.
auto variableF = function string() { return "variable.F"; };
auto variableD = delegate string() { return "variable.D"; };
C c = new C;
S s;
"Global".test(&aFunction);
"Nested".test(&aNested);
"Class".test(&C.aStatic)
.test(&c.aMethod);
"Struct".test(&S.aStatic)
.test(&s.aMethod);
"Template".test(&tmpFunc!(string))
.test(&tmpGroup!(string).t2);
"Binding".test(variableF)
.test(variableD);
// Literal function/delegate.
"Literal".test(function string() { return "literal.F"; })
.test(delegate string() { return "literal.D"; });
}
- Output:
}
Hi, Function : scope: Global (function) : immutable(char)[]()* Hi, Nested : scope: Nested (delegate) : immutable(char)[] delegate() Hi, Static Method : scope: Class (function) : immutable(char)[]()* Hi, Method : scope: Class (delegate) : immutable(char)[] delegate() Hi, Static Method : scope: Struct (function) : immutable(char)[]()* Hi, Method : scope: Struct (delegate) : immutable(char)[] delegate() Hi, IFTI.function : scope: Template (function) : immutable(char)[]()* Hi, Tmp.member.2 : scope: Template (function) : immutable(char)[]()* Hi, variable.F : scope: Binding (function) : immutable(char)[]()* Hi, variable.D : scope: Binding (delegate) : immutable(char)[] delegate() Hi, literal.F : scope: Literal (function) : immutable(char)[]()* Hi, literal.D : scope: Literal (delegate) : immutable(char)[] delegate()
Delphi
- See Pascal
DWScript
type TFnType = function(x : Float) : Float;
function First(f : TFnType) : Float;
begin
Result := f(1) + 2;
end;
function Second(f : Float) : Float;
begin
Result := f/2;
end;
PrintLn(First(Second));
Dyalect
func call(f, a, b) {
f(a, b)
}
let a = 6
let b = 2
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=div, f(\(a), \(b)) = \(call((x, y) => x / y, a, b))")
- Output:
f=add, f(6, 2) = 8 f=mul, f(6, 2) = 12 f=div, f(6, 2) = 3
Déjà Vu
map f lst:
]
for item in lst:
f item
[
twice:
* 2
!. map @twice [ 1 2 5 ]
- Output:
[ 2 4 10 ]
Draco
/* Example functions - there are no anonymous functions */
proc nonrec square(word n) word: n*n corp
proc nonrec cube(word n) word: n*n*n corp
/* A function that takes another function.
* Note how a function is defined as:
* proc name(arguments) returntype: [code here] corp
* But a function variable is instead defined as:
* proc(arguments) returntype name
*/
proc nonrec do_func(word start, stop; proc(word n) word fn) void:
word n;
for n from start upto stop do
write(fn(n):8)
od;
writeln()
corp
/* We can then just pass the name of a function as an argument */
proc main() void:
do_func(1, 10, square);
do_func(1, 10, cube)
corp
- Output:
1 4 9 16 25 36 49 64 81 100 1 8 27 64 125 216 343 512 729 1000
E
def map(f, list) {
var out := []
for x in list {
out with= f(x)
}
return out
}
? map(fn x { x + x }, [1, "two"])
# value: [2, "twotwo"]
? map(1.add, [5, 10, 20])
# value: [6, 11, 21]
? def foo(x) { return -(x.size()) }
> map(foo, ["", "a", "bc"])
# value: [0, -1, -2]
ECL
//a Function prototype:
INTEGER actionPrototype(INTEGER v1, INTEGER v2) := 0;
INTEGER aveValues(INTEGER v1, INTEGER v2) := (v1 + v2) DIV 2;
INTEGER addValues(INTEGER v1, INTEGER v2) := v1 + v2;
INTEGER multiValues(INTEGER v1, INTEGER v2) := v1 * v2;
//a Function prototype using a function prototype:
INTEGER applyPrototype(INTEGER v1, actionPrototype actionFunc) := 0;
//using the Function prototype and a default value:
INTEGER applyValue2(INTEGER v1,
actionPrototype actionFunc = aveValues) :=
actionFunc(v1, v1+1)*2;
//Defining the Function parameter inline, witha default value:
INTEGER applyValue4(INTEGER v1,
INTEGER actionFunc(INTEGER v1,INTEGER v2) = aveValues)
:= actionFunc(v1, v1+1)*4;
INTEGER doApplyValue(INTEGER v1,
INTEGER actionFunc(INTEGER v1, INTEGER v2))
:= applyValue2(v1+1, actionFunc);
//producing simple results:
OUTPUT(applyValue2(1)); // 2
OUTPUT(applyValue2(2)); // 4
OUTPUT(applyValue2(1, addValues)); // 6
OUTPUT(applyValue2(2, addValues)); // 10
OUTPUT(applyValue2(1, multiValues)); // 4
OUTPUT(applyValue2(2, multiValues)); // 12
OUTPUT(doApplyValue(1, multiValues)); // 12
OUTPUT(doApplyValue(2, multiValues)); // 24
//A definition taking function parameters which themselves
//have parameters that are functions...
STRING doMany(INTEGER v1,
INTEGER firstAction(INTEGER v1,
INTEGER actionFunc(INTEGER v1,INTEGER v2)),
INTEGER secondAction(INTEGER v1,
INTEGER actionFunc(INTEGER v1,INTEGER v2)),
INTEGER actionFunc(INTEGER v1,INTEGER v2))
:= (STRING)firstAction(v1, actionFunc) + ':' + (STRING)secondaction(v1, actionFunc);
OUTPUT(doMany(1, applyValue2, applyValue4, addValues));
// produces "6:12"
OUTPUT(doMany(2, applyValue4, applyValue2,multiValues));
// produces "24:12"
Efene
first = fn (F) {
F()
}
second = fn () {
io.format("hello~n")
}
@public
run = fn () {
# passing the function specifying the name and arity
# arity: the number of arguments it accepts
first(fn second:0)
first(fn () { io.format("hello~n") })
# holding a reference to the function in a variable
F1 = fn second:0
F2 = fn () { io.format("hello~n") }
first(F1)
first(F2)
}
Elena
ELENA 6.x :
import extensions;
public program()
{
var first := (f => f());
var second := { ^ "second" };
console.printLine(first(second))
}
- Output:
second
Elixir
iex(1)> defmodule RC do
...(1)> def first(f), do: f.()
...(1)> def second, do: :hello
...(1)> end
{:module, RC,
<<70, 79, 82, 49, 0, 0, 4, 224, 66, 69, 65, 77, 69, 120, 68, 99, 0, 0, 0, 142,
131, 104, 2, 100, 0, 14, 101, 108, 105, 120, 105, 114, 95, 100, 111, 99, 115, 95
, 118, 49, 108, 0, 0, 0, 2, 104, 2, ...>>,
{:second, 0}}
iex(2)> RC.first(fn -> RC.second end)
:hello
iex(3)> RC.first(&RC.second/0) # Another expression
:hello
iex(4)> f = fn -> :world end # Anonymous function
#Function<20.54118792/0 in :erl_eval.expr/5>
iex(5)> RC.first(f)
:world
Erlang
Erlang functions are atoms, and they're considered different functions if their arity (the number of arguments they take) is different. As such, an Erlang function must be passed as fun Function/Arity
, but can be used as any other variable:
-module(test).
-export([first/1, second/0]).
first(F) -> F().
second() -> hello.
Testing it:
1> c(tests).
{ok, tests}
2> tests:first(fun tests:second/0).
hello
3> tests:first(fun() -> anonymous_function end).
anonymous_function
ERRE
ERRE function are limited to one-line FUNCTION, but you can write:
PROGRAM FUNC_PASS
FUNCTION ONE(X,Y)
ONE=(X+Y)^2
END FUNCTION
FUNCTION TWO(X,Y)
TWO=ONE(X,Y)+1
END FUNCTION
BEGIN
PRINT(TWO(10,11))
END PROGRAM
Answer is 442
Euler Math Toolbox
>function f(x,a) := x^a-a^x
>function dof (f$:string,x) := f$(x,args());
>dof("f",1:5;2)
[ -1 0 1 0 -7 ]
>plot2d("f",1,5;2):
Euphoria
procedure use(integer fi, integer a, integer b)
print(1,call_func(fi,{a,b}))
end procedure
function add(integer a, integer b)
return a + b
end function
use(routine_id("add"),23,45)
F#
We define a function that takes another function f as an argument and applies that function twice to the argument x:
> let twice f x = f (f x);;
val twice : ('a -> 'a) -> 'a -> 'a
> twice System.Math.Sqrt 81.0;;
val it : float = 3.0
Another example, using an operator as a function:
> List.map2 (+) [1;2;3] [3;2;1];;
val it : int list = [4; 4; 4]
Factor
Using words (factor's functions) :
USING: io ;
IN: rosetacode
: argument-function1 ( -- ) "Hello World!" print ;
: argument-function2 ( -- ) "Goodbye World!" print ;
! normal words have to know the stack effect of the input parameters they execute
: calling-function1 ( another-function -- ) execute( -- ) ;
! unlike normal words, inline words do not have to know the stack effect.
: calling-function2 ( another-function -- ) execute ; inline
! Stack effect has to be written for runtime computed values :
: calling-function3 ( bool -- ) \ argument-function1 \ argument-function2 ? execute( -- ) ;
( scratchpad ) \ argument-function1 calling-function1 \ argument-function1 calling-function2 t calling-function3 f calling-function3
Hello World! Hello World! Hello World! Goodbye World!
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.
[f:[$0>][@@\f;!\1-]#%]r: { reduce n stack items using the given basis and binary function }
1 2 3 4 0 4[+]r;!." " { 10 }
1 2 3 4 1 4[*]r;!." " { 24 }
1 2 3 4 0 4[$*+]r;!. { 30 }
Fantom
class Main
{
// apply given function to two arguments
static Int performOp (Int arg1, Int arg2, |Int, Int -> Int| fn)
{
fn (arg1, arg2)
}
public static Void main ()
{
echo (performOp (2, 5, |Int a, Int b -> Int| { a + b }))
echo (performOp (2, 5, |Int a, Int b -> Int| { a * b }))
}
}
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.
: square dup * ;
: cube dup dup * * ;
: map. ( xt addr len -- )
0 do 2dup i cells + @ swap execute . loop 2drop ;
create array 1 , 2 , 3 , 4 , 5 ,
' square array 5 map. cr \ 1 4 9 16 25
' cube array 5 map. cr \ 1 8 27 64 125
:noname 2* 1+ ; array 5 map. cr \ 3 5 7 9 11
Fortran
use the EXTERNAL attribute to show the dummy argument is another function rather than a data object. i.e.
FUNCTION FUNC3(FUNC1, FUNC2, x, y)
REAL, EXTERNAL :: FUNC1, FUNC2
REAL :: FUNC3
REAL :: x, y
FUNC3 = FUNC1(x) * FUNC2(y)
END FUNCTION FUNC3
Another way is to put the functions you want to pass in a module:
module FuncContainer
implicit none
contains
function func1(x)
real :: func1
real, intent(in) :: x
func1 = x**2.0
end function func1
function func2(x)
real :: func2
real, intent(in) :: x
func2 = x**2.05
end function func2
end module FuncContainer
program FuncArg
use FuncContainer
implicit none
print *, "Func1"
call asubroutine(func1)
print *, "Func2"
call asubroutine(func2)
contains
subroutine asubroutine(f)
! the following interface is redundant: can be omitted
interface
function f(x)
real, intent(in) :: x
real :: f
end function f
end interface
real :: px
px = 0.0
do while( px < 10.0 )
print *, px, f(px)
px = px + 1.0
end do
end subroutine asubroutine
end program FuncArg
FreeBASIC
' FB 1.05.0 Win64
Function square(n As Integer) As Integer
Return n * n
End Function
Function cube(n As Integer) As Integer
Return n * n * n
End Function
Sub doCalcs(from As Integer, upTo As Integer, title As String, func As Function(As Integer) As Integer)
Print title; " -> ";
For i As Integer = from To upTo
Print Using "#####"; func(i);
Next
Print
End Sub
doCalcs 1, 10, "Squares", @square
doCalcs 1, 10, "Cubes ", @cube
Print
Print "Press any key to quit"
Sleep
- Output:
Squares -> 1 4 9 16 25 36 49 64 81 100 Cubes -> 1 8 27 64 125 216 343 512 729 1000
Frink
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.
cmpFunc = {|a,b| length[a] <=> length[b]}
a = ["tree", "apple", "bee", "monkey", "z"]
sort[a, cmpFunc]
You can also look up functions by name and number of arguments. The following is equivalent to the previous example.
lengthCompare[a,b] := length[a] <=> length[b]
func = getFunction["lengthCompare", 2]
a = ["tree", "apple", "bee", "monkey", "z"]
sort[a, func]
FutureBasic
window 1
dim as pointer functionOneAddress
def fn FunctionOne( x as long, y as long ) as long = (x + y) ^ 2
functionOneAddress = @fn FunctionOne
def fn FunctionTwo( x as long, y as long ) using functionOneAddress
print fn FunctionTwo( 12, 12 )
HandleEvents
Output:
576
Fōrmulæ
Fōrmulæ programs are not textual, visualization/edition of programs is done showing/manipulating structures but not text. Moreover, there can be multiple visual representations of the same program. Even though it is possible to have textual representation —i.e. XML, JSON— they are intended for storage and transfer purposes more than visualization and edition.
Programs in Fōrmulæ are created/edited online in its website.
In this page you can see and run the program(s) related to this task and their results. You can also change either the programs or the parameters they are called with, for experimentation, but remember that these programs were created with the main purpose of showing a clear solution of the task, and they generally lack any kind of validation.
Solution
Case 1 (from Rosetta code) Passing a function as an argument to another function.
The following function takes a function as its first parameter, and other two parameters, x and y. When this function "Do" is called, it will perform the given function taking as arguments the values x and y.
An anonymous function (a lambda expression) can be passed directly:
For the next example, the function to be passed, when invoked, will perform several operation to the same two arguments. It will add them, subtract them, multiply them, divide them and power them. Finally it will return a list with the results.
Up now, however, it is the half of the story. Let us build an example where a function takes a function as parameter, and returns another function.
Case 2 (from Wikipedia) Passing a function as an argument to another function, and returning a function
The following function is a higher-order function. It takes as its unique parameter the function f. When the function is invoked, it will apply twice the function f and will return it. In other words, it will return a new function, which is the composition of the function f with itself.
The next function is an ordinary one. It returns the values given as argument added with 3.
In the next example, g is a dynamically created function.
Since the Apply twice function returns a function, it can be immediately invoked:
It can also take a pure symbol, in order to retrrieve a symbolic result:
GAP
Eval := function(f, x)
return f(x);
end;
Eval(x -> x^3, 7);
# 343
Go
package main
import "fmt"
func func1(f func(string) string) string { return f("a string") }
func func2(s string) string { return "func2 called with " + s }
func main() { fmt.Println(func1(func2)) }
Groovy
As closures:
first = { func -> func() }
second = { println "second" }
first(second)
As functions:
def first(func) { func() }
def second() { println "second" }
first(this.&second)
Haskell
A function is just a value that wants arguments:
func1 f = f "a string"
func2 s = "func2 called with " ++ s
main = putStrLn $ func1 func2
Or, with an anonymous function:
func f = f 1 2
main = print $ func (\x y -> x+y)
-- output: 3
Note that func (\x y -> x+y) is equivalent to func (+). (Operators are functions too.)
Icon and Unicon
Inform 6
As in C, functions in Inform 6 are not first-class, but pointers to functions can be used.
[ func;
print "Hello^";
];
[ call_func x;
x();
];
[ Main;
call_func(func);
];
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.
Higher Order Functions is a room.
To decide which number is (N - number) added to (M - number) (this is addition):
decide on N + M.
To decide which number is multiply (N - number) by (M - number) (this is multiplication):
decide on N * M.
To demonstrate (P - phrase (number, number) -> number) as (title - text):
say "[title]: [P applied to 12 and 34]."
When play begins:
demonstrate addition as "Add";
demonstrate multiplication as "Mul";
end the story.
Insitux
(function prepend-hello s
(str "Hello, " s))
(function modify-string f s
(f s))
(modify-string prepend-hello "World!")
- Output:
Hello, World!
J
Adverbs take a single verb or noun argument and conjunctions take two. For example, / (insert) \ (prefix) and \. (suffix) are adverbs and @ (atop), & (bond or compose) and ^: (power) are conjunctions. The following expressions illustrate their workings.
+ / 3 1 4 1 5 9 NB. sum
23
>./ 3 1 4 1 5 9 NB. max
9
*./ 3 1 4 1 5 9 NB. lcm
180
+/\ 3 1 4 1 5 9 NB. sum prefix (partial sums)
3 4 8 9 14 23
+/\. 3 1 4 1 5 9 NB. sum suffix
23 20 19 15 14 9
2&% 1 2 3 NB. divide 2 by
2 1 0.666667
%&2 (1 2 3) NB. divide by 2 (need parenthesis to break up list formation)
0.5 1 1.5
-: 1 2 3 NB. but divide by 2 happens a lot so it's a primitive
0.5 1 1.5
f=: -:@(+ 2&%) NB. one Newton iteration
f 1
1.5
f f 1
1.41667
f^:(i.5) 1 NB. first 5 Newton iterations
1 1.5 1.41667 1.41422 1.41421
f^:(i.5) 1x NB. rational approximations to sqrt 2
1 3r2 17r12 577r408 665857r470832
Adverbs and conjunctions may also be user defined
+ conjunction def 'u' -
+
+ conjunction def 'v' -
-
* adverb def '10 u y' 11
110
^ conjunction def '10 v 2 u y' * 11
20480
Java
There is no real callback in Java like in C or C++, but we can do the same as swing does for executing an event. We need to create an interface that has the method we want to call or create one that will call the method we want to call. The following example uses the second way.
public class NewClass {
public NewClass() {
first(new AnEventOrCallback() {
public void call() {
second();
}
});
}
public void first(AnEventOrCallback obj) {
obj.call();
}
public void second() {
System.out.println("Second");
}
public static void main(String[] args) {
new NewClass();
}
}
interface AnEventOrCallback {
public void call();
}
From Java 8, lambda expressions may be used. Example (from Oracle):
public class ListenerTest {
public static void main(String[] args) {
JButton testButton = new JButton("Test Button");
testButton.addActionListener(new ActionListener(){
@Override public void actionPerformed(ActionEvent ae){
System.out.println("Click Detected by Anon Class");
}
});
testButton.addActionListener(e -> System.out.println("Click Detected by Lambda Listner"));
// Swing stuff
JFrame frame = new JFrame("Listener Test");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(testButton, BorderLayout.CENTER);
frame.pack();
frame.setVisible(true);
}
}
JavaScript
function first (func) {
return func();
}
function second () {
return "second";
}
var result = first(second);
result = first(function () { return "third"; });
An example with anonymous functions and uses in the core library
for methods filter
and map
.
>>> var array = [2, 4, 5, 13, 18, 24, 34, 97];
>>> array
[2, 4, 5, 13, 18, 24, 34, 97]
// return all elements less than 10
>>> array.filter(function (x) { return x < 10 });
[2, 4, 5]
// return all elements less than 30
>>> array.filter(function (x) { return x < 30 });
[2, 4, 5, 13, 18, 24]
// return all elements less than 100
>>> array.filter(function (x) { return x < 100 });
[2, 4, 5, 13, 18, 24, 34, 97]
// multiply each element by 2 and return the new array
>>> array.map(function (x) { return x * 2 });
[4, 8, 10, 26, 36, 48, 68, 194]
// sort the array from smallest to largest
>>> array.sort(function (a, b) { return a > b });
[2, 4, 5, 13, 18, 24, 34, 97]
// sort the array from largest to smallest
>>> array.sort(function (a, b) { return a < b });
[97, 34, 24, 18, 13, 5, 4, 2]
Joy
This example is taken from V. Define first as multiplying two numbers on the stack.
DEFINE first == *.
There will be a warning about overwriting builtin first. Define second as interpreting the passed quotation on the stack.
DEFINE second == i.
Pass first enclosed in quotes to second.
2 3 [first] second.
The program prints 6.
jq
The examples given in this section closely follow the exposition in the Julia section of this page.
To understand these examples, it is helpful to remember that:
- jq functions are filters that can participate in a left-to-right pipeline, just as in most modern command shells;
- "." on the right of a pipe ("|") refers to the output from the filter on the left.
Example 1: "hello blue world"
def foo( filter ):
("world" | filter) as $str
| "hello \($str)" ;
# blue is defined here as a filter that adds blue to its input:
def blue: "blue \(.)";
foo( blue ) # prints "hello blue world"
Example 2: g(add; 2; 3)
def g(f; x; y): [x,y] | f;
g(add; 2; 3) # => 5
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:
def is_even:
if floor == . then (. % 2) == 0
else error("is_even expects its input to be an integer")
end;
# Are all integers between 1 and 5 even?
# For this example, we will use all/2 even
# though it requires a release of jq after jq 1.4;
# we do so to highlight the fact that all/2
# terminates the generator once the condition is satisfied:
all( range(1;6); is_even )
false
# Display the even integers in the given range:
range(1;6) | select(is_even)
2
4
# Evaluate is_even for each integer in an array
[range(1;6)] | map(is_even)
[false, true, false, true, false]
# Note that in jq, there is actually no need to call
# a higher-order function in cases like this.
# For example one can simply write:
range(1;6) | is_even
false
true
false
true
false
Julia
function foo(x)
str = x("world")
println("hello $(str)!")
end
foo(y -> "blue $y") # prints "hello blue world"
The above code snippet defines a named function, foo, which takes a single argument, which is a Function. foo calls this function on the string literal "world", and then interpolates the result into the "hello ___!" string literal, and prints it. In the final line, foo is called with an anonymous function that takes a string, and returns a that string with "blue " preppended to it.
function g(x,y,z)
x(y,z)
end
println(g(+,2,3)) # prints 5
This code snippet defines a named function g that takes three arguments: x is a function to call, and y and z are the values to call x on. We then call g on the + function. Operators in Julia are just special names for functions.
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.
julia> all(iseven, 1:5) # not all integers between 1 and 5 are even.
false
julia> findfirst(iseven, 1:5) # the first even integer is at index 2 in the range.
2
julia> count(iseven, 1:5) # there are two even integers between 1 and 5.
2
julia> filter(iseven, 1:5) # here are the even integers in the given range.
2-element Array{Int64,1}:
2
4
julia> map(iseven, 1:5) # we apply our function to all integers in range.
5-element Array{Bool,1}:
false
true
false
true
false
Klingphix
:+2 + 2 + ;
:*2 * 2 * ;
:apply exec ;
23 45 @+2 apply print nl
8 4 @*2 apply print nl
" " input
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:
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 a = list.map({ x -> x + 2 }).average()
val h = list.map({ x -> x * x }).average()
val g = list.map({ x -> x * x * x }).average()
println("A = %f G = %f H = %f".format(a, g, h))
}
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):
inline fun higherOrderFunction(x: Int, y: Int, function: (Int, Int) -> Int) = function(x, y)
fun main(args: Array<String>) {
val result = higherOrderFunction(3, 5) { x, y -> x + y }
println(result)
}
- Output:
8
Lambdatalk
{def add
{lambda {:f :g :x}
{+ {:f :x} {:g :x}}}}
{add sin cos 10}
-> -1.383092639965822 // {+ {sin 10} {cos 10}}
{S.map sqrt {S.serie 1 5}}
-> 1 1.4142135623730951 1.7320508075688772 2 2.23606797749979
{S.reduce + {S.serie 1 10}}
-> 55
Lily
define square(x: Integer): Integer
{
return x * x
}
var l = [1, 2, 3] # Inferred type: List[Integer].
# Transform using a user-defined function.
print(l.map(square)) # [1, 4, 9]
# Using a built-in method this time.
print(l.map(Integer.to_s)) # ["1", "2", "3"]
# Using a lambda (with the type of 'x' properly inferred).
print(l.map{|x| (x + 1).to_s()}) # ["2", "3", "4"]
# In reverse order using F#-styled pipes.
Boolean.to_i |> [true, false].map |> print
define apply[A, B](value: A, f: Function(A => B)): B
{
return f(value)
}
# Calling user-defined transformation.
print(apply("123", String.parse_i)) # Some(123)
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:
-- in some movie script
----------------------------------------
-- Runs provided function (of some object) on all elements of the provided list, returns results as new list
-- @param {list} aList
-- @param {symbol} cbFunc
-- @param {object} [cbObj=_movie]
-- @return {list}
----------------------------------------
on map (aList, cbFunc, cbObj)
if voidP(cbObj) then cbObj = _movie
res = []
cnt = aList.count
repeat with i = 1 to cnt
res[i] = call(cbFunc, cbObj, aList[i])
end repeat
return res
end
l = [1, 2, 3]
-- passes the built-in function 'sin' (which is a method of the _movie object) as argument to map
res = map(l, #sin)
put res
-- [0.8415, 0.9093, 0.1411]
Logo
You can pass the quoted symbol for the function and invoke it with RUN.
to printstuff
print "stuff
end
to runstuff :proc
run :proc
end
runstuff "printstuff ; stuff
runstuff [print [also stuff]] ; also stuff
Lua
Lua functions are first-class:
a = function() return 1 end
b = function(r) print( r() ) end
b(a)
Luck
Higher-order functions can be used to implement conditional expressions:
function lambda_true(x: 'a)(y: 'a): 'a = x;;
function lambda_false(x: 'a)(y: 'a): 'a = y;;
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") );;
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)
Function Foo (x) {
=x**2
}
Function Bar(&f(), k) {
=f(k)
}
Print Bar(&foo(), 20)=400
Group K {
Z=10
Function MulZ(x) {
=.Z*x
.Z++
}
}
Print Bar(&K.MulZ(), 20)=200
Print K.Z=11
Example using lambda function
Foo = Lambda k=1 (x)-> {
k+=2
=x**2+K
}
\\ by ref1
Function Bar1(&f(), k) {
=f(k)
}
Print Bar1(&Foo(), 20)=403
\\ by ref2
Function Bar2(&f, k) {
=f(k)
}
Print Bar2(&Foo, 20)=405
\\ by value
Function Bar(f, k) {
=f(k)
}
\\ we sent a copy of lambda, and any value type closure copied too
Print Bar(Foo, 20)=407
Print Bar1(&Foo(), 20)=407
\\ we can get a copy of Foo to NewFoo (also we get a copy of closure too)
NewFoo=Foo
Print Bar1(&Foo(), 20)=409
Print Bar2(&Foo, 20)=411
Print Bar2(&NewFoo, 20)=409
Mathematica / 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:
PassFunc[f_, g_, h_, x_] := f[g[x]*h[x]]
PassFunc[Tan, Cos, Sin, x]
% /. x -> 0.12
PassFunc[Tan, Cos, Sin, 0.12]
gives back:
Tan[Cos[x] Sin[x]]
0.119414
0.119414
MATLAB / Octave
F1=@sin; % F1 refers to function sin()
F2=@cos; % F2 refers to function cos()
% varios ways to call the referred function
F1(pi/4)
F2(pi/4)
feval(@sin,pi/4)
feval(@cos,pi/4)
feval(F1,pi/4)
feval(F2,pi/4)
% named functions, stored as strings
feval('sin',pi/4)
feval('cos',pi/4)
F3 = 'sin';
F4 = 'cos';
feval(F3,pi/4)
feval(F4,pi/4)
Maxima
callee(n) := (print(sconcat("called with ", n)), n + 1)$
caller(f, n) := sum(f(i), i, 1, n)$
caller(callee, 3);
"called with 1"
"called with 2"
"called with 3"
MAXScript
fn second =
(
print "Second"
)
fn first func =
(
func()
)
first second
Metafont
We can simulate this by using scantokens
, which digests a string as if it would be a source input.
def calcit(expr v, s) = scantokens(s & decimal v) enddef;
t := calcit(100.4, "sind");
show t;
end
МК-61/52
6 ПП 04
П7 КПП7 В/О
1 В/О
Note: as the receiver of argument used register Р7; the result is "1" on the indicator.
Modula-3
MODULE Proc EXPORTS Main;
IMPORT IO;
TYPE Proc = PROCEDURE();
PROCEDURE Second() =
BEGIN
IO.Put("Second procedure.\n");
END Second;
PROCEDURE First(proc: Proc) =
BEGIN
proc();
END First;
BEGIN
First(Second);
END Proc.
Morfa
func g(a: int, b: int, f: func(int,int): int): int
{
return f(a, b);
}
import morfa.base;
func main(): void
{
println("Add: ", g(2, 3, func(a: int, b: int) { return a + b; }));
println("Multiply: ", g(2, 3, func(a: int, b: int) { return a * b; }));
}
Nanoquery
def first(function)
return function()
end
def second()
return "second"
end
result = first(second)
println result
- Output:
second
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.
Twice[T] (f : T -> T, x : T) : T { f(f(x)) }
NewLISP
> (define (my-multiply a b) (* a b))
(lambda (a b) (* a b))
> (define (call-it f x y) (f x y))
(lambda (f x y) (f x y))
> (call-it my-multiply 2 3)
6
Nim
proc first(fn: proc): auto =
return fn()
proc second(): string =
return "second"
echo first(second)
Oberon-2
Works with oo2c version 2
MODULE HOFuns;
IMPORT
NPCT:Tools,
Out;
TYPE
Formatter = PROCEDURE (s: STRING; len: LONGINT): STRING;
VAR
words: ARRAY 8 OF STRING;
PROCEDURE PrintWords(w: ARRAY OF STRING; format: Formatter);
VAR
i: INTEGER;
BEGIN
i := 0;
WHILE (i < LEN(words)) DO
Out.Object(format(words[i],16));
INC(i)
END;
Out.Ln
END PrintWords;
BEGIN
words[0] := "Al-Andalus";
words[1] := "contributed";
words[2] := "significantly";
words[3] := "to";
words[4] := "the";
words[5] := "field";
words[6] := "of";
words[7] := "medicine";
PrintWords(words,Tools.AdjustLeft);
PrintWords(words,Tools.AdjustCenter);
PrintWords(words,Tools.AdjustRight)
END HOFuns.
Objeck
bundle Default {
class HighOrder {
function : Main(args : String[]) ~ Nil {
f := GetSize(String) ~ Int;
Print(f);
}
function : GetSize(s : String) ~ Int {
return s->Size();
}
function : Print(func : (String)~Int) ~ Nil {
func("Hello World!")->PrintLine();
}
}
}
OCaml
A function is just a value that wants arguments:
# let func1 f = f "a string";;
val func1 : (string -> 'a) -> 'a = <fun>
# let func2 s = "func2 called with " ^ s;;
val func2 : string -> string = <fun>
# print_endline (func1 func2);;
func2 called with a string
- : unit = ()
Or, with an anonymous function:
# let func f = f 1 2;;
val func : (int -> int -> 'a) -> 'a = <fun>
# Printf.printf "%d\n" (func (fun x y -> x + y));;
3
- : unit = ()
Note that func (fun x y -> x + y) is equivalent to func (+). (Operators are functions too.)
Octave
We can pass a function handle (@function_name
)
function r = computeit(f, g, v)
r = f(g(v));
endfunction
computeit(@exp, @sin, pi/3)
computeit(@log, @cos, pi/6)
Or pass the string name of the function and use the feval
primitive.
function r = computeit2(f, g, v)
r = f(feval(g, v));
endfunction
computeit2(@exp, "sin", pi/3)
Odin
package main
import "core:fmt"
first :: proc(fn: proc() -> string) -> string {
return fn()
}
second :: proc() -> string {
return "second"
}
main :: proc() {
fmt.println(first(second)) // prints: second
}
Oforth
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 :
[1, 2, 3, 4, 5 ] map(#1+)
Ol
; typical use:
(for-each display '(1 2 "ss" '(3 4) 8))
; ==> 12ss(quote (3 4))8'()
; manual implementation in details:
(define (do f x)
(f x))
(do print 12345)
; ==> 12345
ooRexx
routines are first class ooRexx objects that can be passed to other routines or methods and invoked.
say callit(.routines~fib, 10)
say callit(.routines~fact, 6)
say callit(.routines~square, 13)
say callit(.routines~cube, 3)
say callit(.routines~reverse, 721)
say callit(.routines~sumit, 1, 2)
say callit(.routines~sumit, 2, 4, 6, 8)
-- call the provided routine object with the provided variable number of arguments
::routine callit
use arg function
args = arg(2, 'a') -- get all arguments after the first to pass along
return function~callWith(args) -- and pass along the call
::routine cube
use arg n
return n**3
::routine square
use arg n
return n**2
::routine reverse
use arg n
return reverse(n)
::routine fact
use arg n
accum = 1
loop j = 2 to n
accum = accum * j
end
return accum
::routine sumit
use arg n
accum = 0
do i over arg(1, 'a') -- iterate over the array of args
accum += i
end
return accum
::routine fib
use arg n
if n == 0 then
return n
if n == 1 then
return n
last = 0
next = 1
loop j = 2 to n;
current = last + next
last = next
next = current
end
return current
- Output:
55 720 169 27 127 3 20
Order
Functions in Order can accept any other named function, local variable, or anonymous function as arguments:
#include <order/interpreter.h>
#define ORDER_PP_DEF_8func1 ORDER_PP_FN ( \
8fn(8F, \
8ap(8F, 8("a string")) ))
#define ORDER_PP_DEF_8func2 ORDER_PP_FN ( \
8fn(8S, \
8adjoin(8("func2 called with "), 8S ) ))
ORDER_PP(
8func1(8func2)
)
// -> "func2 called with ""a string"
#define ORDER_PP_DEF_8func3 ORDER_PP_FN ( \
8fn(8F, \
8ap(8F, 1, 2) ))
ORDER_PP(
8func3(8plus)
)
// -> 3
ORDER_PP(
8ap( 8fn(8X, 8Y, 8mul(8add(8X, 8Y), 8sub(8X, 8Y))), 5, 3)
)
// -> 16
The only difference between toplevel function definitions, and variables or literals, is that variables and anonymous functions must be called using the 8ap
syntactic form rather than direct argument application syntax. This is a limitation of the C preprocessor.
OxygenBasic
'FUNCTION TO BE PASSED
'=====================
function f(double d,e) as double
return (d+e)*2
end function
'FUNCTION TAKING A FUNCTION AS AN ARGUMENT
'=========================================
function g(sys p) as string
declare function x(double d,e) as double at p
return x(10,11)
end function
'TEST: PASSING ADDRESS OF FUNCTION f
'===================================
'the name 'f' is combined with the prototype signature '#double#double'
'@' signifies the address of the function is being passed
print g(@f#double#double) 'result '42'
Oz
Functions are just regular values in Oz.
declare
fun {Twice Function X}
{Function {Function X}}
end
in
{Show {Twice Sqrt 81.0}} %% prints 3.0
PARI/GP
secant_root(ff,a,b)={
e = eps() * 2;
aval=ff(a);
bval=ff(b);
while (abs(bval) > e,
oldb = b;
b = b - (b - a)/(bval - aval) * bval;
aval = bval;
bval = ff(b);
a = oldb
);
b
};
addhelp(secant_root, "secant_root(ff,a,b): Finds a root of ff between a and b using the secant method.");
eps()={
precision(2. >> (32 * ceil(default(realprecision) * 38539962 / 371253907)), 9)
};
addhelp(eps,"Returns machine epsilon for the current precision.");
Pascal
Standard Pascal (will not work with Turbo Pascal):
program example(output);
function first(function f(x: real): real): real;
begin
first := f(1.0) + 2.0;
end;
function second(x: real): real;
begin
second := x/2.0;
end;
begin
writeln(first(second));
end.
Turbo Pascal (will not work with Standard Pascal):
program example;
type
FnType = function(x: real): real;
function first(f: FnType): real;
begin
first := f(1.0) + 2.0;
end;
{$F+}
function second(x: real): real;
begin
second := x/2.0;
end;
{$F-}
begin
writeln(first(second));
end.
using FreePascal : Higher-order function MAP / REDUCE ( FOLDL / FOLDR ) / FILTER
UNIT MRF;
{$mode Delphi} {$H+} {$J-} {$R+} (*) https://www.freepascal.org/docs-html/prog/progch1.html (*)
(*)
Free Pascal Compiler version 3.2.0 [2020/06/14] for x86_64
The free and readable alternative at C/C++ speeds
compiles natively to almost any platform, including raspberry PI *
Can run independently from DELPHI / Lazarus
For debian Linux: apt -y install fpc
It contains a text IDE called fp
https://www.freepascal.org/advantage.var
(*)
INTERFACE
USES
Math,
SysUtils,
variants;
{$WARN 6058 off : Call to subroutine "$1" marked as inline is not inlined} // Use for variants
TYPE
Varyray = array of variant ;
FunA = FUNCTION ( x : variant ) : variant ;
FunB = PROCEDURE ( x : variant ) ;
FunC = FUNCTION ( x,y : variant ) : variant ;
FunD = FUNCTION ( x,y : longint ) : longint ;
FunE = FUNCTION ( x,y : variant ) : variant ;
PROCEDURE Show ( x : variant ) ;
FUNCTION Reverse ( x : Varyray ) : Varyray ;
FUNCTION Head ( x : Varyray ) : variant ;
FUNCTION Last ( x : Varyray ) : variant ;
FUNCTION Tail ( x : Varyray ) : Varyray ;
FUNCTION Take ( y : variant ; x : Varyray ) : Varyray ;
FUNCTION Map ( f : FunA ; x: Varyray ) : Varyray ; overload ;
PROCEDURE Map ( f : FunB ; x: Varyray ) ; overload ;
FUNCTION Map ( f : FunC ; x, y: Varyray ) : Varyray ; overload ;
FUNCTION Map ( f : FunD ; x, y: Varyray ) : Varyray ; overload ;
FUNCTION Filter ( f : FunA ; x: Varyray ) : Varyray ; overload ;
FUNCTION Filter ( f : FunE ; y: variant; x: Varyray ) : Varyray ; overload ;
FUNCTION FoldL ( f : FunC ; x: Varyray ) : variant ; overload ;
FUNCTION FoldL ( f : FunD ; x: Varyray ) : variant ; overload ;
FUNCTION FoldL ( f : FunE ; y: variant; x: Varyray ) : variant ; overload ;
FUNCTION Reduce ( f : FunC ; x: Varyray ) : variant ; overload ;
FUNCTION Reduce ( f : FunD ; x: Varyray ) : variant ; overload ;
FUNCTION Reduce ( f : FunE ; y: variant; x: Varyray ) : variant ; overload ;
FUNCTION FoldR ( f : FunC ; x: Varyray ) : variant ; overload ;
FUNCTION FoldR ( f : FunD ; x: Varyray ) : variant ; overload ;
(*) FOR TESTING (*)
FUNCTION RandFillInt ( x: variant ) : variant ;
FUNCTION RandFillReal ( x: variant ) : variant ;
FUNCTION AND_xy ( x, y: variant ) : variant ;
FUNCTION OR_xy ( x, y: variant ) : variant ;
FUNCTION AVG ( x: Varyray ) : variant ;
FUNCTION All ( f: FunA ; x: Varyray ) : variant ;
FUNCTION Any ( f: FunA ; x: Varyray ) : variant ;
FUNCTION Add ( x, y: variant ) : variant ;
FUNCTION Mult ( x, y: variant ) : variant ;
FUNCTION contain ( x, y: variant ) : variant ;
FUNCTION delete ( x, y: variant ) : variant ;
FUNCTION Add1 ( x: variant ) : variant ;
FUNCTION sine ( x: variant ) : variant ;
FUNCTION cosine ( x: variant ) : variant ;
FUNCTION cotangens ( x: variant ) : variant ;
FUNCTION Is_Even ( x: variant ) : variant ;
FUNCTION Is_Odd ( x: variant ) : variant ;
IMPLEMENTATION
PROCEDURE Show ( x: variant ) ;
BEGIN write( x, ' ' ) ; END ;
FUNCTION Reverse ( x : Varyray ) : Varyray ;
VAR
__ : varyray ;
k : integer ;
BEGIN
IF length ( x ) < Low ( x ) + 2 THEN Exit ;
Setlength ( __, length ( x ) );
FOR k := Low ( x ) to High ( x ) DO
__ [ k ] := x [ High ( x ) - k ] ;
result := __ ;
Setlength ( __, 0 );
END;
FUNCTION Head ( x : Varyray ) : variant ;
BEGIN result := x [ Low ( x ) ] ; END;
FUNCTION Last ( x : Varyray ) : variant ;
BEGIN result := x [ High ( x ) ] ; END;
FUNCTION Tail ( x : Varyray ) : Varyray ;
VAR
__ : varyray ;
k : integer ;
BEGIN
Setlength ( __, High ( x ) );
FOR k := Low ( x ) + 1 to High ( x ) DO
__ [ k - 1 ] := x [ k ] ;
result := __ ;
Setlength ( __, 0 );
END;
FUNCTION Take ( y : variant ; x : Varyray ) : Varyray ;
VAR
__ : varyray ;
k : integer ;
BEGIN
Setlength ( __, y );
FOR k := Low ( x ) to y - 1 DO
__ [ k ] := x [ k ] ;
result := __ ;
Setlength ( __, 0 );
END;
FUNCTION Map ( f: FunA ; x: Varyray ) : Varyray ; overload ;
VAR
Ar : array of variant ;
k : integer ;
BEGIN
SetLength ( Ar, length ( x ) ) ;
result := Ar ;
FOR k := Low ( Ar ) TO High ( Ar ) DO
Ar [ k ] := f ( x [ k ] ) ;
result := Ar ;
Setlength ( Ar, 0 );
END;
PROCEDURE Map ( f: FunB ; x: Varyray ) ; overload ;
VAR
k : integer ;
BEGIN
FOR k := Low ( x ) TO High ( x ) DO f ( x [ k ] ) ;
END;
FUNCTION Map ( f: FunC ; x, y: Varyray ) : Varyray ; overload ;
VAR
Ar : array of variant ;
k : integer ;
BEGIN
SetLength ( Ar, min ( length ( x ) , length ( y ) ) ) ;
FOR k := Low ( Ar ) TO High ( Ar ) DO
Ar [ k ] := f ( x [ k ] , y [ k ] ) ;
result := Ar ;
Setlength ( Ar, 0 );
END;
FUNCTION Map ( f: FunD ; x, y: Varyray ) : Varyray ; overload ;
VAR
Ar : array of variant ;
k : integer ;
BEGIN
SetLength ( Ar, min ( length ( x ) , length ( y ) ) ) ;
FOR k := Low ( Ar ) TO High ( Ar ) DO
Ar [ k ] := f ( x [ k ] , y [ k ] ) ;
result := Ar ;
Setlength ( Ar, 0 );
END;
FUNCTION Map ( f: FunE ; x: variant; y: Varyray ) : Varyray ; overload ;
VAR
Ar : array of variant ;
k : integer ;
BEGIN
SetLength ( Ar, min ( length ( x ) , length ( y ) ) ) ;
FOR k := Low ( Ar ) TO High ( Ar ) DO
Ar [ k ] := f ( x , y [ k ] ) ;
result := Ar ;
Setlength ( Ar, 0 );
END;
FUNCTION Filter ( f: FunA ; x: Varyray ) : Varyray ; overload ;
VAR
Ar : array of variant ;
__ : variant ;
k : integer ;
len : integer ;
BEGIN
SetLength ( Ar, 0 ) ;
result := Ar ;
FOR k := Low ( x ) TO High ( x ) DO
BEGIN
__ := f ( x [ k ] ) ;
IF __ <> False THEN
BEGIN
len := Length ( Ar ) ;
SetLength ( Ar, len + 1 ) ;
Ar [ len ] := __ ;
END ;
END ;
result := Ar ;
Setlength ( Ar, 0 );
END;
FUNCTION Filter ( f: FunE ; y: variant; x: Varyray ) : Varyray ; overload ;
VAR
Ar : array of variant ;
__ : variant ;
k : integer ;
len : integer ;
BEGIN
SetLength ( Ar, 0 ) ;
result := Ar ;
FOR k := Low ( x ) TO High ( x ) DO
BEGIN
__ := f ( y, x [ k ] ) ;
IF __ <> False THEN
BEGIN
len := Length ( Ar ) ;
SetLength ( Ar, len + 1 ) ;
Ar [ len ] := __ ;
END ;
END ;
result := Ar ;
Setlength ( Ar, 0 );
END;
FUNCTION FoldL ( f: FunC ; x: Varyray ) : variant ; overload ;
VAR
k : integer ;
BEGIN
result := x [ Low ( x ) ] ;
FOR k := Low ( x ) + 1 TO High ( x ) DO
result := f ( result , x [ k ] ) ;
END ;
FUNCTION FoldL ( f: FunD ; x: Varyray ) : variant ; overload ;
VAR
k : integer ;
BEGIN
result := x [ Low ( x ) ] ;
FOR k := Low ( x ) + 1 TO High ( x ) DO
result := f ( result , x [ k ] ) ;
END ;
FUNCTION FoldL ( f: FunE ; y: variant; x: Varyray ) : variant ; overload ;
VAR
k : integer ;
BEGIN
FOR k := Low ( x ) TO High ( x ) DO
result := f ( y , x [ k ] ) ;
END ;
FUNCTION Reduce ( f: FunC ; x: Varyray ) : variant ; overload ;
BEGIN result := FoldL ( f , x ) ; END ;
FUNCTION Reduce ( f: FunD ; x: Varyray ) : variant ; overload ;
BEGIN result := FoldL ( f , x ) ; END ;
FUNCTION Reduce ( f: FunE ; y: variant; x: Varyray ) : variant ; overload ;
BEGIN result := FoldL ( f , y, x ) ; END ;
FUNCTION FoldR ( f: FunC ; x: Varyray ) : variant ; overload ;
VAR
k : integer ;
BEGIN
result := x [ High ( x ) ] ;
FOR k := High ( x ) - 1 DOWNTO Low ( x ) DO
result := f ( result, x [ k ] ) ;
END ;
FUNCTION FoldR ( f: FunD ; x: Varyray ) : variant ; overload ;
VAR
k : integer ;
BEGIN
result := x [ High ( x ) ];
FOR k := High ( x ) - 1 DOWNTO Low ( x ) DO
result := f ( result, x [ k ] ) ;
END ;
(*) TEST Functions (*)
(*)
Special thanks to PascalDragon , winni & BobDog ( FreePascal.org ),
who explained the specifics of the compiler.
(*)
FUNCTION Add ( x, y: variant ) : variant ;
BEGIN result := x + y ; END ;
FUNCTION Add1 ( x: variant ) : variant ;
BEGIN result := x + 1 ; END ;
FUNCTION AND_xy ( x, y: variant ) : variant ;
BEGIN result := ( x and y ) = True ; END ;
FUNCTION AVG ( x: Varyray ) : variant ;
VAR
k : integer ;
BEGIN
result := 0.0 ;
FOR k := Low ( x ) TO High ( x ) DO
result := result + ( x [ k ] - result ) / ( k + 1 );
END ;
FUNCTION Cosine ( x: variant ) : variant ;
BEGIN result := cos ( x ); END ;
FUNCTION Cotangens ( x: variant ) : variant ;
BEGIN
IF ( x = 0 ) Then Exit ( 'Inf');
result := cot ( x );
END ;
FUNCTION Is_Even ( x: variant ) : variant ;
BEGIN
IF ( ( x mod 2 ) = 0 ) THEN
result := x
ELSE
result := False
END;
FUNCTION Mult( x, y: variant ) : variant ;
BEGIN result := x * y ; END ;
FUNCTION Contain ( x, y: variant ) : variant ;
BEGIN result := x = y ; END ;
FUNCTION Delete ( x, y: variant ) : variant ;
BEGIN
IF ( x = y ) THEN Exit ( False ) ;
result := y;
END ;
FUNCTION Is_Odd ( x: variant ) : variant ;
BEGIN
IF ( ( x mod 2 ) <> 0 ) THEN
result := x
ELSE
result := False
END;
FUNCTION OR_xy ( x, y: variant ) : variant ;
BEGIN result := ( x or y ) = True; END ;
FUNCTION RandFillInt ( x: variant ) : variant ;
BEGIN result := Random ( 100 ) ; END ;
FUNCTION RandFillReal ( x: variant ) : variant ;
VAR
tmp : real = 100.0 ;
BEGIN result := ( Random ( ) ) * tmp ; END ;
FUNCTION sine ( x: variant ) : variant ;
BEGIN result := sin ( x ); END ;
FUNCTION All ( f: FunA ; x: Varyray ) : variant ;
VAR
k : integer ;
BEGIN
result := True ;
FOR k := Low ( x ) TO High ( x ) DO
result := AND_xy ( result , f ( x [ k ] ) ) ;
END ;
FUNCTION Any ( f: FunA ; x: Varyray ) : variant ;
VAR
k : integer ;
BEGIN
result := False ;
FOR k := Low ( x ) TO High ( x ) DO
result := OR_xy ( result , f ( x [ k ] ) ) ;
END ;
END.
(*) === How to use in a program === (*)
program testMRF.pas;
{$mode Delphi} {$H+} {$J-} {$R+} (*) https://www.freepascal.org/docs-html/prog/progch1.html (*)
USES
MRF,
Math,
SysUtils,
Variants;
{$WARN 6058 off : Call to subroutine "$1" marked as inline is not inlined} // Use for variants
VAR
a,b,c : array of variant ;
Acc : variant ;
BEGIN
Randomize ;
setlength ( a, 6 ) ;
setlength ( b, 4 ) ;
setlength ( c, 6 ) ;
a := Map ( RandFillInt , a ) ;
Map ( show , a ) ;
writeln ;
b := Map ( RandFillInt , b ) ;
Map ( show , b ) ;
writeln ;
c := Map ( RandFillInt , c ) ;
Map ( show , c ) ;
writeln ;
Acc := FoldL ( add , a ) ;
WriteLn ( 'Sum = ' , Acc ) ;
writeln ;
Acc := Reduce ( contain , 31, a ) ;
WriteLn ( 'contains = ' , Acc ) ;
writeln ;
c := Filter ( delete , 31, a ) ;
WriteLn ( 'del c :' ) ;
Map ( show , c ) ;
writeln ;
a := Reverse ( c ) ;
WriteLn ( 'reverse c :' ) ;
Map ( show , a ) ;
writeln ;
Acc := avg ( b ) ;
WriteLn ( 'avg = ' , Acc ) ;
writeln ;
c := Map ( cotangens , b ) ;
writeln ( 'cot : ' ) ;
Map ( show , c ) ;
writeln ;
Acc := FoldR ( min , b ) ;
WriteLn ( 'min = ' , Acc );
writeln ;
Acc := FoldR ( max , b ) ;
WriteLn ( 'max = ' , Acc );
writeln ;
Map ( show , b ) ;
Acc := All ( Is_Odd , b ) ;
writeln ;
WriteLn ( 'All Is_Odd = ' , Acc ) ;
writeln ;
Map ( show , b ) ;
Acc := Any ( Is_Even , b ) ;
writeln ;
WriteLn ( 'Any Is_Even = ' , Acc ) ;
writeln ;
Acc := Head ( b ) ;
WriteLn ( 'Head = ' , Acc ) ;
Acc := Last ( b ) ;
WriteLn ( 'Last = ' , Acc ) ;
Map ( show , b ) ;
a := Tail ( b ) ;
writeln ;
WriteLn ( 'Tail of b :' ) ;
Map ( show , a ) ;
writeln ;
Map ( show , b ) ;
a := Take ( 2, b ) ;
writeln ;
WriteLn ( 'Take 2 from b :' ) ;
Map ( show , a ) ;
writeln ;
setlength ( c, 0 ) ;
setlength ( b, 0 ) ;
setlength ( a, 0 ) ;
END.
JPD 2021/07/10
Output:
Random ( Like me :)
Perl
sub another {
# take a function and a value
my $func = shift;
my $val = shift;
# call the function with the value as argument
return $func->($val);
};
sub reverser {
return scalar reverse shift;
};
# pass named coderef
print another \&reverser, 'data';
# pass anonymous coderef
print another sub {return scalar reverse shift}, 'data';
# if all you have is a string and you want to act on that,
# set up a dispatch table
my %dispatch = (
square => sub {return shift() ** 2},
cube => sub {return shift() ** 3},
rev => \&reverser,
);
print another $dispatch{$_}, 123 for qw(square cube rev);
sub apply (&@) { # use & as the first item in a prototype to take bare blocks like map and grep
my ($sub, @ret) = @_; # this function applies a function that is expected to modify $_ to a list
$sub->() for @ret; # it allows for simple inline application of the s/// and tr/// constructs
@ret
}
print join ", " => apply {tr/aeiou/AEIOU/} qw/one two three four/;
# OnE, twO, thrEE, fOUr
sub first {shift->()}
sub second {'second'}
print first \&second;
print first sub{'sub'};
Phix
procedure use(integer fi, a, b) ?fi(a,b) end procedure function add(integer a, b) return a + b end function use(add,23,45)
- Output:
68
You could also use get_routine_info(fi) to retrieve the maximum and minimum number of parameters, along with a string representing the signature in roottype format, and the actual name of the routine. Above it would return {2,2,"FII","add"} indicating add is a function that takes two integers, none of which are optional. Obviously you would need to invoke functions and procedures differently, eg you cannot print the result of a procedure call, likewise for different numbers and base types of parameters. Or as above just trust you were passed something appropriate, and rely on/expect a very clear human readable fatal error message if not.
The plain add, without a trailing '(' to make it a direct invocation, resolves to a symbol table index.
Obviously you can use (an otherwise pointless) user defined type (of any name you like) instead of integer if preferred, eg
type rid(integer /*r*/) return true end type procedure use(rid fi, integer a,b)...
Phixmonti
def suma + enddef
def apply exec enddef
23 45 getid suma apply print
PHP
function first($func) {
return $func();
}
function second() {
return 'second';
}
$result = first('second');
Or, with an anonymous function in PHP 5.3+:
function first($func) {
return $func();
}
$result = first(function() { return 'second'; });
Picat
Here are some different approaches. The following variables and functions are assumed to be defined:
go =>
% ...
L = 1..10,
L2 = 1..3,
% ...
f1(X) = X**2.
f2(X,A) = X**A + A**X.
%
% qsort(List, SortFunction)
% returns a sorted list according to the sort function SortFunction
%
qsort([],_F) = [].
qsort([H|T],F) = qsort([E : E in T, call(F,E,H)], F)
++ [H] ++
qsort([E : E in T, not call(F,E,H)],F).
% sort on length
sortf(F1,F2) =>
F1.length < F2.length.
Using map
% ...
println(map(f1,L)),
println(map($f2(3),L)),
println(map(f2,L,map(f1,L))).
List comprehension
In general the recommended approach.
%
println([f1(I) : I in L]),
println([[I,J,f2(I,J)] : I in L, J in L2]).
Apply
% ...
println(apply(+,1,2)),
println(apply(f2,10,22)).
Sort function
Here is an example how to sort on length.
% ...
S = [
"rosetta code",
"adam",
"eve",
"picat",
"pattern-matching",
"imperative",
"constraints",
"actors",
"tabling"
],
println(map(len,S)),
println(S.qsort(sortf)).
- Output:
[1,4,9,16,25,36,49,64,81,100] [4,17,54,145,368,945,2530,7073,20412,60049] [2,32,20412,4295032832,298023223886718750,10314424798490535548348731392,256923577521058878088611477224913844394456,6277101735386680763835789423207666416102355725939011223552,196627050475552913618075908526912116283103450944214766927315565632601688195930,10000000000000000000000000000000000000000000000000000000000000000000000000000000100000000000000000000] [1,4,9,16,25,36,49,64,81,100] [[1,1,2],[1,2,3],[1,3,4],[2,1,3],[2,2,8],[2,3,17],[3,1,4],[3,2,17],[3,3,54],[4,1,5],[4,2,32],[4,3,145],[5,1,6],[5,2,57],[5,3,368],[6,1,7],[6,2,100],[6,3,945],[7,1,8],[7,2,177],[7,3,2530],[8,1,9],[8,2,320],[8,3,7073],[9,1,10],[9,2,593],[9,3,20412],[10,1,11],[10,2,1124],[10,3,60049]] 3 10000000026559922791424 [12,4,3,5,16,10,11,6,7] [eve,adam,picat,actors,tabling,imperative,constraints,rosetta code,pattern-matching]
PicoLisp
: (de first (Fun)
(Fun) )
-> first
: (de second ()
"second" )
-> second
: (first second)
-> "second"
: (de add (A B)
(+ A B) )
-> add
: (add 1 2)
-> 3
: (de call-it (Fun X Y)
(Fun X Y) )
-> call-it
: (call-it add 1 2)
-> 3
: (mapcar inc (1 2 3 4 5))
-> (2 3 4 5 6)
: (mapcar + (1 2 3) (4 5 6))
-> (5 7 9)
: (mapcar add (1 2 3) (4 5 6))
-> (5 7 9)
PL/I
f: procedure (g) returns (float);
declare g entry (float);
get (x);
put (g(x));
end f;
x = f(p); /* where "p" is the name of a function. */
Pop11
;;; Define a function
define x_times_three_minus_1(x);
return(3*x-1);
enddefine;
;;; Pass it as argument to built-in function map and print the result
mapdata({0 1 2 3 4}, x_times_three_minus_1) =>
PostScript
Postscript functions are either built-in operators or executable arrays (procedures). Both can take either as arguments.
% operator example
% 'ifelse' is passed a boolean and two procedures
/a 5 def
a 0 gt { (Hello!) } { (World?) } ifelse ==
% procedure example
% 'bar' is loaded onto the stack and passed to 'foo'
/foo { exec } def
/bar { (Hello, world!) } def
/bar load foo ==
PowerShell
function f ($y) {
$y*$y
}
function g (${function:f}, $y) {
(f $y)
}
You can implement a function inside a function.
function g2($y) {
function f2($y) {
$y*$y
}
(f2 $y)
}
Calling:
g f 5
g2 9
Output:
25 81
Prolog
first(Predicate) :- call(Predicate).
second(Argument) :- write(Argument).
:-first(second('Hello World!')).
PureBasic
Prototype.d func(*text$)
Procedure NumberTwo(arg$)
Debug arg$
EndProcedure
Procedure NumberOne(*p, text$)
Define MyFunc.func=*p
MyFunc(@text$)
EndProcedure
NumberOne(@NumberTwo(),"Hello Worldy!")
Python
def first(function):
return function()
def second():
return "second"
result = first(second)
or
result = first(lambda: "second")
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.
Q
Its helpful to remember that in Q, when parameters aren't named in the function declaration, x is assumed to be the first parameter.
q)sayHi:{-1"Hello ",x;}
q)callFuncWithParam:{x["Peter"]}
q)callFuncWithParam sayHi
Hello Peter
q)callFuncWithParam[sayHi]
Hello Peter
Quackery
First define the higher order functions fold
, map
, and filter
.
[ over [] = iff drop done dip [ behead swap ' [ witheach ] ] nested join do ] is fold ( [ x --> x ) [ ' [ [ ] ] rot join swap nested ' [ nested join ] join fold ] is map ( [ x --> [ ) [ ' [ [ ] ] rot join swap nested ' dup swap join ' [ iff [ nested join ] else drop ] join fold ] is filter ( [ x --> [ )
Then test them in the Quackery shell by summing a nest of numbers, recursively flattening a deeply nested nest, reversing every string in a nest of strings, and removing all the negative numbers from a nest of numbers.
For another example of usage of map
and filter
, see countchars
in Huffman coding#Quackery.
/O> ' [ 1 2 3 4 5 6 7 8 9 10 ] ' + fold echo ... 55 Stack empty. /O> forward is flatten ( x --> [ ) ... [ ' [ [ ] ] swap join ... ' [ dup nest? if ... flatten ... join ] ... fold ] resolves flatten ( x --> [ ) ... Stack empty. /O> ' [ 1 2 [ [ 3 4 ] ] 5 [ 6 [ 7 [ 8 [ 9 ] ] ] ] ] flatten ... echo ... [ 1 2 3 4 5 6 7 8 9 ] Stack empty. /O> $ "esreveR yreve gnirts ni a tsen fo .sgnirts" nest$ ... ' reverse map ... witheach [ echo$ sp ] ... Reverse every string in a nest of strings. Stack empty. /O> ' [ 42 -23 23 -42 ] ... ' [ 0 < not ] filter ... echo ... [ 42 23 ] Stack empty.
R
f <- function(f0) f0(pi) # calc. the function in pi
tf <- function(x) x^pi # a func. just to test
print(f(sin))
print(f(cos))
print(f(tf))
Racket
#lang racket/base
(define (add f g x)
(+ (f x) (g x)))
(add sin cos 10)
Raku
(formerly Perl 6)
The best type to use for the parameter of a higher-order function is Callable
(implied by the &
sigil), a role common to all function-like objects. For an example of defining and calling a second-order function, see Functional Composition.
Convenient syntax is provided for anonymous functions, either a bare block, or a parametrized block introduced with ->, which serves as a "lambda":
sub twice(&todo) {
todo(); todo(); # declaring &todo also defines bare function
}
twice { say "Boing!" }
# output:
# Boing!
# Boing!
sub twice-with-param(&todo) {
todo(0); todo(1);
}
twice-with-param -> $time {
say "{$time+1}: Hello!"
}
# output:
# 1: Hello!
# 2: Hello!
Raven
This is not strictly passing a function, but the string representing the function name.
define doit use $v1
"doit called with " print $v1 print "\n" print
define callit use $v2
"callit called with " print $v2 print "\n" print
$v2 call
23.54 "doit" callit
- Output:
callit called with doit doit called with 23.54
REBOL
REBOL [
Title: "Function Argument"
URL: http://rosettacode.org/wiki/Function_as_an_Argument
]
map: func [
"Apply function to contents of list, return new list."
f [function!] "Function to apply to list."
data [block! list!] "List to transform."
/local result i
][
result: copy [] repeat i data [append result f i] result]
square: func [
"Calculate x^2."
x [number!]
][x * x]
cube: func [
"Calculate x^3."
x [number!]
][x * x * x]
; Testing:
x: [1 2 3 4 5]
print ["Data: " mold x]
print ["Squared:" mold map :square x]
print ["Cubed: " mold map :cube x]
print ["Unnamed:" mold map func [i][i * 2 + 1] x]
Output:
Data: [1 2 3 4 5] Squared: [1 4 9 16 25] Cubed: [1 8 27 64 125] Unnamed: [3 5 7 9 11]
Retro
:disp (nq-) call n:put ;
#31 [ (n-n) #100 * ] disp
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 'square' , 13; say right( 'square{'$"} = ", 30) result
call function 'cube' , 3; say right( 'cube{'$"} = ", 30) result
call function 'reverse', 721; say right( 'reverse{'$"} = ", 30) result
exit /*stick a fork in it, we're all done. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
cube: return $**3
fact: procedure expose $; !=1; do j=2 to $; !=!*j; end; return !
function: arg ?.; parse arg ,$; signal value (?.)
reverse: return 'REVERSE'($)
square: return $**2
- output when using the default input:
fact{6} = 720 square{13} = 169 cube{3} = 27 reverse{721} = 127
Ring
# Project : Higher-order functions
docalcs(1,10,"squares",:square)
docalcs(1,10,"cubes",:cube)
func square(n)
return n * n
func cube(n)
return n * n * n
func docalcs(from2,upto,title,func2)
see title + " -> " + nl
for i = from2 to upto
x = call func2(i)
see x + nl
next
see nl
Output:
squares -> 1 4 9 16 25 36 49 64 81 100 cubes -> 1 8 27 64 125 216 343 512 729 1000
Ruby
With a proc (procedure):
succ = proc{|x| x+1}
def to2(&f)
f[2]
end
to2(&succ) #=> 3
to2{|x| x+1} #=> 3
With a method:
def succ(n)
n+1
end
def to2(m)
m[2]
end
meth = method(:succ)
to2(meth) #=> 3
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.
fn execute_with_10<F: Fn(u64) -> u64> (f: F) -> u64 {
f(10)
}
fn square(n: u64) -> u64 {
n*n
}
fn main() {
println!("{}", execute_with_10(|n| n*n )); // closure
println!("{}", execute_with_10(square)); // function
}
- Output:
100 100
Scala
def functionWithAFunctionArgument(x : int, y : int, f : (int, int) => int) = f(x,y)
Call:
functionWithAFunctionArgument(3, 5, {(x, y) => x + y}) // returns 8
Scheme
A function is just a value that wants arguments:
> (define (func1 f) (f "a string"))
> (define (func2 s) (string-append "func2 called with " s))
> (begin (display (func1 func2)) (newline))
func2 called with a string
Or, with an anonymous function:
> (define (func f) (f 1 2))
> (begin (display (func (lambda (x y) (+ x y)))) (newline))
3
Note that (func (lambda (x y) (+ x y))) is equivalent to (func +). (Operators are functions too.)
SenseTalk
function Map oldlist, func
put () into newlist
repeat with each item of oldlist
insert (func)(it) after newlist
end repeat
return newlist
end Map
put ("tomato", "aubergine", "courgette") into fruits
put Map(fruits, Uppercase)
Sidef
func first(f) {
return f();
}
func second {
return "second";
}
say first(second); # => "second"
say first(func { "third" }); # => "third"
Slate
Methods and blocks can both be passed as arguments to functions (other methods and blocks):
define: #function -> [| :x | x * 3 - 1].
#(1 1 2 3 5 8) collect: function.
Smalltalk
first := [ :f | f value ].
second := [ 'second' ].
Transcript show: (first value: second).
function := [:x | x * 3 - 1].
#(1 1 2 3 5 8) collect: function.
Sparkling
function call_me(func, arg) {
return func(arg);
}
let answer = call_me(function(x) { return 6 * x; }, 7);
print(answer);
Standard ML
- fun func1 f = f "a string";
val func1 = fn : (string -> 'a) -> 'a
- fun func2 s = "func2 called with " ^ s;
val func2 = fn : string -> string
- print (func1 func2 ^ "\n");
func2 called with a string
val it = () : unit
Or, with an anonymous function:
- fun func f = f (1, 2);
val func = fn : (int * int -> 'a) -> 'a
- print (Int.toString (func (fn (x, y) => x + y)) ^ "\n");
3
val it = () : unit
Note that func (fn (x, y) => x + y) is equivalent to func op+. (Operators are functions too.)
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
Swift
func func1(f: String->String) -> String { return f("a string") }
func func2(s: String) -> String { return "func2 called with " + s }
println(func1(func2)) // prints "func2 called with a string"
Or, with an anonymous function:
func func3<T>(f: (Int,Int)->T) -> T { return f(1, 2) }
println(func3 {(x, y) in x + y}) // prints "3"
Note that {(x, y) in x + y} can also be written as {$0 + $1} or just +.
Tcl
# this procedure executes its argument:
proc demo {function} {
$function
}
# for example:
demo bell
It is more common to pass not just a function, but a command fragment or entire script. When used with the built-in list command (which introduces a very useful degree of quoting) this makes for a very common set of techniques when doing advanced Tcl programming.
# This procedure executes its argument with an extra argument of "2"
proc demoFrag {fragment} {
{*}$fragment 2
}
# This procedure executes its argument in the context of its caller, which is
# useful for scripts so they get the right variable resolution context
proc demoScript {script} {
uplevel 1 $script
}
# Examples...
set chan stderr
demoFrag [list puts $chan]
demoFrag {
apply {x {puts [string repeat ? $x]}}
}
demoScript {
parray tcl_platform
}
TI-89 BASIC
TI-89 BASIC does not have first-class functions; while function definitions as stored in variables are fully dynamic, it is not possible to extract a function value from a variable rather than calling it. In this case, we use the indirection operator #
, which takes a string and returns the value of the named variable, to use the name of the function as something to be passed.
The function name passed cannot be that of a local function, because the local function map
does not see the local variables of the enclosing function.
Local map
Define map(f,l)=Func
Return seq(#f(l[i]),i,1,dim(l))
EndFunc
Disp map("sin", {0, π/6, π/4, π/3, π/2})
Toka
Toka allows obtaining a function pointer via the ` (backtick) word. The pointers are passed on the stack, just like all other data.
[ ." First\n" ] is first
[ invoke ] is second
` first second
Trith
Due to the homoiconic program representation and the concatenative nature of the language, higher-order functions are as simple as:
: twice 2 times ;
: hello "Hello, world!" print ;
[hello] twice
TXR
lambda
passed to mapcar
with environment capture:
@(bind a @(let ((counter 0))
(mapcar (lambda (x y) (list (inc counter) x y))
'(a b c) '(t r s))))
@(output)
@ (repeat)
@ (rep)@a:@(last)@a@(end)
@ (end)
@(end)
1:a:t 2:b:r 3:c:s
uBasic/4tH
' Test passing a function to a function:
Print FUNC(_FNtwo(_FNone, 10, 11))
End
' Function to be passed:
_FNone Param (2) : Return ((a@ + b@)^2)
' Function taking a function as an argument:
_FNtwo Param (3) : Return (FUNC(a@ (b@, c@)))
- Output:
441 0 OK, 0:79
Ursa
Functions are first-class objects in Ursa.
def first (function f)
return (f)
end
def second ()
return "second"
end
out (first second) endl console
# "second" is output to the console
Ursala
Autocomposition is a user defined function that takes a function as an argument, and returns a function equivalent to the given functon composed with itself.
(autocomposition "f") "x" = "f" "f" "x"
test program:
#import flo
#cast %e
example = autocomposition(sqrt) 16.0
output:
2.000000e+00
V
Define first as multiplying two numbers on stack
[first *].
Define second as applying the passed quote on stack
[second i].
Pass the first enclosed in quote to second which applies it on stack.
2 3 [first] second
=6
VBA
Based on the Pascal solution
Sub HigherOrder()
Dim result As Single
result = first("second")
MsgBox result
End Sub
Function first(f As String) As Single
first = Application.Run(f, 1) + 2
End Function
Function second(x As Single) As Single
second = x / 2
End Function
Visual Basic .NET
Each example below performs the same task and utilizes .NET delegates, which are objects that refer to a static method or to an instance method of a particular object instance.
c.f. C#
- Output (for each example):
f=Add, f(6, 2) = 8 f=Mul, f(6, 2) = 12 f=Div, f(6, 2) = 3
Named methods
' Delegate declaration is similar to C#.
Delegate Function Func2(a As Integer, b As Integer) As Integer
Module Program
Function Add(a As Integer, b As Integer) As Integer
Return a + b
End Function
Function Mul(a As Integer, b As Integer) As Integer
Return a * b
End Function
Function Div(a As Integer, b As Integer) As Integer
Return a \ b
End Function
' Call is a keyword and must be escaped using brackets.
Function [Call](f As Func2, a As Integer, b As Integer) As Integer
Return f(a, b)
End Function
Sub Main()
Dim a = 6
Dim b = 2
' Delegates in VB.NET could be created without a New expression from the start. Both syntaxes are shown here.
Dim add As Func2 = New Func2(AddressOf Program.Add)
' The "As New" idiom applies to delegate creation.
Dim div As New Func2(AddressOf Program.Div)
' Directly coercing the AddressOf expression:
Dim mul As Func2 = AddressOf Program.Mul
Console.WriteLine("f=Add, f({0}, {1}) = {2}", a, b, [Call](add, a, b))
Console.WriteLine("f=Mul, f({0}, {1}) = {2}", a, b, [Call](mul, a, b))
Console.WriteLine("f=Div, f({0}, {1}) = {2}", a, b, [Call](div, a, b))
End Sub
End Module
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.
Module Program
' 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
Return f(a, b)
End Function
Sub Main()
Dim a = 6
Dim b = 2
Console.WriteLine("f=Add, f({0}, {1}) = {2}", a, b, [Call](Function(x As Integer, y As Integer) x + y, a, b))
' With inferred parameter types:
Console.WriteLine("f=Mul, f({0}, {1}) = {2}", a, b, [Call](Function(x, y) x * y, a, b))
' The block syntax must be used in order to specify a return type. As there is no target type in this case, the parameter types must be explicitly specified. anon has an anonymous, compiler-generated type.
Dim anon = Function(x As Integer, y As Integer) As Integer
Return x \ y
End Function
' Parameters are contravariant and the return type is covariant. Note that this conversion is not valid CLR variance (which disallows boxing conversions) and so is compiled as an additional anonymous delegate that explicitly boxes the return value.
Dim example As Func(Of Integer, Integer, Object) = anon
' Dropped-return-type conversion.
Dim example2 As Action(Of Integer, Integer) = anon
Console.WriteLine("f=Div, f({0}, {1}) = {2}", a, b, [Call](anon, a, b))
End Sub
End Module
Visual Prolog
domains
intFunction = (integer In) -> integer Out procedure (i).
class predicates
addone : intFunction.
doTwice : (intFunction, integer) -> integer procedure (i, i).
clauses
doTwice(Pred,X) = Y :- Y = Pred(Pred(X)).
addone(X) = Y := Y = X + 1.
run():-
init(),
write(dotwice(addone,2)),
succeed().
Wren
var first = Fn.new { |f|
System.print("first function called")
f.call()
}
var second = Fn.new { System.print("second function called") }
first.call(second)
- Output:
first function called second function called
Z80 Assembly
Higher-order functions are often used for IRQ handlers which don't have a lot of time to figure out what to do. (I'll admit this is a bit of a stretch since typically the function that receives the IRQ handler as a parameter just calls it and does nothing else.)
Typically, the IRQ handler will jump to RAM, and before the program is in a state where the IRQ conditions will be met (such as a video game during a level transition), the function will be passed (sometimes even by value!) to the IRQ handler. On the Game Boy and the ZX Spectrum, RSTs are in ROM and thus cannot be changed at runtime, so there's not much of a choice.
In fact, it is mandatory 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.
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.
jp &ff80
;more code goes here
;during setup, we'll CALL SetupDMA before enabling the vblank IRQ.
SetupDMA:
ld bc,DMACopyEnd-DMACopy ;how many bytes to copy
ld hl,DMACopy ;pointer to source
ld de,&ff80 ;pointer to destination
z_ldir ;macro for LDIR which the game boy doesn't have.
ret
DMACopy: ;must be run from &ff80
push af
ld a,>GBSpriteCache ;high byte of wherever we're storing our object attribute memory
gb_out <dma ;start the transfer - DMA auto-copies 256 bytes from xx00-xxFF where xx = >GBSpriteCache
ld a,&28 ;delay - this ensures the DMA is done before we exit. Adjust to your liking.
;game boy doesn't have in/out commands, rather all its I/O ports are at &FFxx so there are special commands just for accessing them faster
;gb_out is a macro that inlines the bytecode, since not all assemblers auto-convert LD (&FFxx),a.
DMACopyWait:
dec a
jr nz,DMACopyWait
pop af
reti
DMACopyEnd:
zkl
Everything is a first class object so
fcn f(g){ g() } fcn g{ "Hello World!".println() }
- Output:
f(g) "Hello World!"
or
fcn f(g){ g() }
fcn(g){ g() }(fcn{ "Hello World!".println() } )
ZX Spectrum Basic
Input "FN " token first, then enclose it in double quotation marks.
10 DEF FN f(f$,x,y)=VAL ("FN "+f$+"("+STR$ (x)+","+STR$ (y)+")")
20 DEF FN n(x,y)=(x+y)^2
30 PRINT FN f("n",10,11)
- Programming Tasks
- Programming language concepts
- 11l
- 6502 Assembly
- 68000 Assembly
- 8th
- ActionScript
- Ada
- Aime
- ALGOL 68
- AmigaE
- AntLang
- AppleScript
- Arturo
- ATS
- AutoHotkey
- BBC BASIC
- Binary Lambda Calculus
- BQN
- Bracmat
- Brat
- Bruijn
- Burlesque
- C
- C sharp
- C++
- Clean
- Clojure
- CLU
- CoffeeScript
- Common Lisp
- Cowgol
- D
- Delphi
- DWScript
- Dyalect
- Déjà Vu
- Draco
- E
- ECL
- Efene
- Elena
- Elixir
- Erlang
- ERRE
- Euler Math Toolbox
- Euphoria
- F Sharp
- Factor
- FALSE
- Fantom
- Forth
- Fortran
- FreeBASIC
- Frink
- FutureBasic
- Fōrmulæ
- GAP
- Go
- Groovy
- Haskell
- Icon
- Unicon
- Inform 6
- Inform 7
- Insitux
- J
- Java
- JavaScript
- Joy
- Jq
- Julia
- Klingphix
- Kotlin
- Lambdatalk
- Lily
- Lingo
- Logo
- Lua
- Luck
- M2000 Interpreter
- Mathematica
- Wolfram Language
- MATLAB
- Octave
- Maxima
- MAXScript
- Metafont
- МК-61/52
- Modula-3
- Morfa
- Nanoquery
- Nemerle
- NewLISP
- Nim
- Oberon-2
- Objeck
- OCaml
- Odin
- Oforth
- Ol
- OoRexx
- Order
- OxygenBasic
- Oz
- PARI/GP
- Pascal
- Perl
- Phix
- Phix/basics
- Phixmonti
- PHP
- Picat
- PicoLisp
- PL/I
- Pop11
- PostScript
- PowerShell
- Prolog
- PureBasic
- Python
- Q
- Quackery
- R
- Racket
- Raku
- Raven
- REBOL
- Retro
- REXX
- Ring
- Ruby
- Rust
- Scala
- Scheme
- SenseTalk
- Sidef
- Slate
- Smalltalk
- Sparkling
- Standard ML
- SuperCollider
- Swift
- Tcl
- TI-89 BASIC
- Toka
- Trith
- TXR
- UBasic/4tH
- Ursa
- Ursala
- V
- VBA
- Visual Basic .NET
- Visual Prolog
- Wren
- Z80 Assembly
- Zkl
- ZX Spectrum Basic
- GUISS/Omit
- Functions and subroutines
- Pages with too many expensive parser function calls