Higher-order functions: Difference between revisions
m
→{{header|Fōrmulæ}}
(101 intermediate revisions by 35 users not shown) | |||
Line 2:
;Task:
Pass a function ''as an argument'' to another function.
Line 8:
* [[First-class functions]]
<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}}==
<
: pass-me
"I was passed\n" . ;
Line 17 ⟶ 86:
\ pass 'pass-me' to 'passer'
' pass-me passer
</syntaxhighlight>
{{out}}
I was passed
=={{header|ActionScript}}==
<
public class MyClass {
Line 39 ⟶ 109:
}
}
}</
=={{header|Ada}}==
===Simple Example===
<
procedure Subprogram_As_Argument is
Line 59 ⟶ 129:
begin
First(Second'Access);
end Subprogram_As_Argument;</
===Complex Example===
<
procedure Subprogram_As_Argument_2 is
Line 112 ⟶ 182:
Int_Ptr := Complex_Func(F_Ptr, 3);
Put_Line(Integer'Image(Int_Ptr.All));
end Subprogram_As_Argument_2;</
=={{header|Aime}}==
<
average(integer p, integer q)
{
Line 139 ⟶ 209:
return 0;
}</
=={{header|ALGOL 68}}==
Line 150 ⟶ 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]}}
{{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}}
<
(
f(1) + 2
Line 162 ⟶ 228:
main: (
printf(($xg(5,2)l$,first(second)))
)</
Output:
<pre>
Line 170 ⟶ 236:
=={{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.
<
DEF s[10] : STRING
WriteF('\s\n', RealF(s,func(val),4))
Line 181 ⟶ 247:
compute({sin_wrap}, 0.0)
compute({cos_wrap}, 3.1415)
ENDPROC</
=={{header|AntLang}}==
<syntaxhighlight lang="antlang">twice:{x[x[y]]}
echo twice "Hello!"</syntaxhighlight>
=={{header|AppleScript}}==
<
-- with another handler (call).
on sing about topic by singer
Line 207 ⟶ 278:
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.
Line 213 ⟶ 284:
We could, for example, write '''map''', '''fold/reduce''' and '''filter''' functions for AppleScript as follows:
<
-- PASSING FUNCTIONS AS ARGUMENTS TO
-- MAP, FOLD/REDUCE, AND FILTER, ACROSS A LIST
Line 327 ⟶ 398:
on isEven(x)
x mod 2 = 0
end isEven</
{{Out}}
<
{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 …
<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}}==
<syntaxhighlight lang="ats">
#include
"share/atspre_staload.hats"
Line 348 ⟶ 466:
//
} (* end of [main0] *)
</syntaxhighlight>
=={{header|AutoHotkey}}==
<syntaxhighlight lang="autohotkey">
f(x) {
return "This " . x
Line 367 ⟶ 485:
show("g") ; or just name the function
return
</syntaxhighlight>
=={{header|BBC BASIC}}==
{{works with|BBC BASIC for Windows}}
<
PRINT FNtwo(FNone(), 10, 11)
END
Line 379 ⟶ 497:
REM Function taking a function as an argument:
DEF FNtwo(RETURN f%, x, y) = FN(^f%)(x, y)</
'''Output:'''
<pre>
441
</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}}==
<
& ( print
= text a b func
Line 399 ⟶ 531:
. multiply
)
);</
Output:
<pre>add(3,7)=10
Line 405 ⟶ 537:
=={{header|Brat}}==
<
doit = { f, a, b | f a, b }
p doit ->add 1 2 #prints 3</
=={{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}}==
Line 416 ⟶ 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):
<
blsq ) {1 2 3 4}{5.+}m[
{6 7 8 9}
</syntaxhighlight>
=={{header|C}}==
Line 429 ⟶ 572:
Definition of a function whose only parameter is a pointer to a function with no parameters and no return value:
<
{
/* ... */
Line 437 ⟶ 580:
/* ... */
}</
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 443 ⟶ 586:
Call:
<
/* ... */
myFuncSimple(&funcToBePassed);</
'''Complex example'''
Line 453 ⟶ 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.
<
{
long inLong;
Line 465 ⟶ 608:
/* ... */
}</
Call:
<
/* ... */
Line 474 ⟶ 617:
int* outInt;
outInt = myFuncComplex(&funcToBePassed);</
'''Pointer'''
Line 480 ⟶ 623:
Finally, declaration of a pointer variable of the proper type to hold such a function as myFunc:
<
/* ... */
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.
=={{header|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.
{{out|note=for each example}}
<pre>
f=Add, f(6, 2) = 8
Line 564 ⟶ 642:
</pre>
===
This implementation works
<
// A delegate declaration. Because delegates are types, they can exist directly in namespaces.
delegate int Func2(int a, int b);
class Program
{
Line 588 ⟶ 669:
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);
}
Line 595 ⟶ 677:
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);
Line 604 ⟶ 687:
Console.WriteLine("f=Div, f({0}, {1}) = {2}", a, b, Call(div, a, b));
}
}</
===
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.
<syntaxhighlight lang="csharp">using System;
delegate int Func2(int a, int b);
class Program
{
Line 624 ⟶ 707:
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));
}
}</
==={{anchor|C#: Lambda expressions}}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 <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+}}
<
class Program
{
Line 649 ⟶ 737:
int b = 2;
// No lengthy delegate keyword.
Console.WriteLine("f=
// 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));
}
}</
=={{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}}==
Take a function as an argument and apply it to all elements in a list:
<
map f [] = []</
Pass a function as an argument:
<
Start = map incr [1..10]</
Do the same using a anonymous function:
<
Do the same using currying:
<
=={{header|Clojure}}==
<
(defn append-hello [s]
(str "Hello " s))
Line 678 ⟶ 838:
(println (modify-string append-hello "World!"))
</syntaxhighlight>
=={{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}}==
Line 684 ⟶ 873:
Passing an anonymous function to built-in map/reduce functions:
<
Using a function stored in a variable:
<
sum = (a, b) -> a() + b()
sum(fn, fn) # => 16
</syntaxhighlight>
List comprehension with a function argument:
<
smash = (ingredient) ->
Line 702 ⟶ 891:
contents = smash ingredient for ingredient in bowl
# => ["Smashed Cheese", "Smashed Tomato"]
</syntaxhighlight>
Nested function passing:
<
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:
<
A function that takes a function that takes a function argument:
<
2 + x(-> 5)
)((y) -> y()+3)
# result: 10</
=={{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:
<
ADD
CL-USER> (add 1 2)
Line 734 ⟶ 923:
CALL-IT
CL-USER> (call-it #'add 1 2)
3</
The Common Lisp library makes extensive use of higher-order functions:
<pre>CL-USER> (funcall #'+ 1 2 3)
Line 747 ⟶ 936:
(1 2 4 8 16 32)
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}}==
<
return f(a, b);
}
Line 757 ⟶ 1,008:
writeln("Add: ", hof(2, 3, (a, b) => a + b));
writeln("Multiply: ", hof(2, 3, (a, b) => a * b));
}</
{{out}}
<pre>Add: 5
Multiply: 6</pre>
This longer and more systematic example shows D functions/delegates by passing each type of function/delegate to _test_ as argument.
<
// Test the function argument.
Line 822 ⟶ 1,073:
"Literal".test(function string() { return "literal.F"; })
.test(delegate string() { return "literal.D"; });
}</
{{out}}}
<pre>Hi, Function : scope: Global (function) : immutable(char)[]()*
Line 839 ⟶ 1,090:
=={{header|Delphi}}==
:''See [[#Pascal|Pascal]]''
=={{header|DWScript}}==
<
function First(f : TFnType) : Float;
Line 866 ⟶ 1,104:
end;
PrintLn(First(Second));</
=={{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}}==
<
var out := []
for x in list {
Line 885 ⟶ 1,185:
? def foo(x) { return -(x.size()) }
> map(foo, ["", "a", "bc"])
# value: [0, -1, -2]</
=={{header|ECL}}==
<syntaxhighlight lang="text">//a Function prototype:
INTEGER actionPrototype(INTEGER v1, INTEGER v2) := 0;
Line 939 ⟶ 1,238:
OUTPUT(doMany(2, applyValue4, applyValue2,multiValues));
// produces "24:12"</
=={{header|Efene}}==
<
F()
}
Line 966 ⟶ 1,265:
first(F2)
}
</syntaxhighlight>
=={{header|Elena}}==
{{trans|Smalltalk}}
ELENA
<
public program()
{
var first :=
var second :=
console
}</syntaxhighlight>
{{out}}
<pre>second</pre>
=={{header|Elixir}}==
<
...(1)> def first(f), do: f.()
...(1)> def second, do: :hello
Line 996 ⟶ 1,298:
#Function<20.54118792/0 in :erl_eval.expr/5>
iex(5)> RC.first(f)
:world</
=={{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:
<
-export([first/1, second/0]).
first(F) -> F().
second() -> hello.</
Testing it:
<
{ok, tests}
2> tests:first(fun tests:second/0).
hello
3> tests:first(fun() -> anonymous_function end).
anonymous_function</
=={{header|ERRE}}==
ERRE function are limited to one-line FUNCTION, but you can write:
<syntaxhighlight lang="erre">
PROGRAM FUNC_PASS
Line 1,030 ⟶ 1,332:
PRINT(TWO(10,11))
END PROGRAM
</syntaxhighlight>
Answer is 442
=={{header|Euler Math Toolbox}}==
<syntaxhighlight lang="euler math toolbox">
>function f(x,a) := x^a-a^x
>function dof (f$:string,x) := f$(x,args());
Line 1,041 ⟶ 1,343:
[ -1 0 1 0 -7 ]
>plot2d("f",1,5;2):
</syntaxhighlight>
=={{header|Euphoria}}==
<
print(1,call_func(fi,{a,b}))
end procedure
Line 1,052 ⟶ 1,354:
end function
use(routine_id("add"),23,45)</
=={{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:
<
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:
<
val it : int list = [4; 4; 4]</
=={{header|Factor}}==
Using words (factor's functions) :
<
IN: rosetacode
: argument-function1 ( -- ) "Hello World!" print ;
Line 1,082 ⟶ 1,384:
! Stack effect has to be written for runtime computed values :
: calling-function3 ( bool -- ) \ argument-function1 \ argument-function2 ? execute( -- ) ;
</syntaxhighlight>
( scratchpad )
Line 1,097 ⟶ 1,399:
=={{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.
<
1 2 3 4 0 4[+]r;!." " { 10 }
1 2 3 4 1 4[*]r;!." " { 24 }
1 2 3 4 0 4[$*+]r;!. { 30 }</
=={{header|Fantom}}==
<
class Main
{
Line 1,120 ⟶ 1,422:
}
}
</syntaxhighlight>
=={{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.
<
: cube dup dup * * ;
: map. ( xt addr len -- )
Line 1,133 ⟶ 1,435:
' 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</
=={{header|Fortran}}==
{{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.
<
REAL, EXTERNAL :: FUNC1, FUNC2
REAL :: FUNC3
Line 1,144 ⟶ 1,446:
FUNC3 = FUNC1(x) * FUNC2(y)
END FUNCTION FUNC3</
Another way is to put the functions you want to pass in a module:
<
implicit none
contains
Line 1,197 ⟶ 1,499:
end subroutine asubroutine
end program FuncArg</
=={{header|FreeBASIC}}==
<
Function square(n As Integer) As Integer
Line 1,222 ⟶ 1,524:
Print
Print "Press any key to quit"
Sleep</
{{out}}
Line 1,233 ⟶ 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.
<
cmpFunc = {|a,b| length[a] <=> length[b]}
a = ["tree", "apple", "bee", "monkey", "z"]
sort[a, cmpFunc]
</syntaxhighlight>
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]
Line 1,248 ⟶ 1,550:
a = ["tree", "apple", "bee", "monkey", "z"]
sort[a, func]
</syntaxhighlight>
=={{header|FutureBasic}}==
<
dim as pointer functionOneAddress
Line 1,262 ⟶ 1,563:
print fn FunctionTwo( 12, 12 )
HandleEvents</syntaxhighlight>
Output:
Line 1,268 ⟶ 1,570:
576
</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}}==
<
return f(x);
end;
Eval(x -> x^3, 7);
# 343</
=={{header|Go}}==
<
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)) }</
=={{header|Groovy}}==
As [[closures]]:
<
second = { println "second" }
first(second)</
As functions:
<
def second() { println "second" }
first(this.&second)</
=={{header|Haskell}}==
Line 1,302 ⟶ 1,662:
A function is just a value that wants arguments:
<
func2 s = "func2 called with " ++ s
main = putStrLn $ func1 func2</
Or, with an anonymous function:
<
main = print $ func (\x y -> x+y)
-- output: 3</
Note that <tt>func (\x y -> x+y)</tt> is equivalent to <tt>func (+)</tt>. (Operators are functions too.)
=={{header|Icon}} and {{header|Unicon}}==
<
local lst
lst := [10, 20, 30, 40]
Line 1,326 ⟶ 1,686:
procedure callback(arg)
write("->", arg)
end</
=={{header|Inform 6}}==
As in C, functions in Inform 6 are not first-class, but pointers to functions can be used.
<
print "Hello^";
];
Line 1,340 ⟶ 1,700:
[ Main;
call_func(func);
];</
=={{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.
<
To decide which number is (N - number) added to (M - number) (this is addition):
Line 1,358 ⟶ 1,718:
demonstrate addition as "Add";
demonstrate multiplication as "Mul";
end the story.</
=={{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}}==
Line 1,364 ⟶ 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.
<
23
>./ 3 1 4 1 5 9 NB. max
Line 1,394 ⟶ 1,774:
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 'v' -
Line 1,405 ⟶ 1,785:
110
^ conjunction def '10 v 2 u y' * 11
20480</
=={{header|Java}}==
Line 1,411 ⟶ 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.
<
public NewClass() {
Line 1,436 ⟶ 1,816:
interface AnEventOrCallback {
public void call();
}</
From Java 8, lambda expressions may be used. Example (from Oracle):
<
public static void main(String[] args) {
JButton testButton = new JButton("Test Button");
Line 1,457 ⟶ 1,837:
frame.setVisible(true);
}
}</
=={{header|JavaScript}}==
<
return func();
}
Line 1,470 ⟶ 1,850:
var result = first(second);
result = first(function () { return "third"; });</
An example with anonymous functions and uses in the core library
Line 1,476 ⟶ 1,856:
{{works with|Firefox|1.5}} for methods <code>filter</code> and <code>map</code>.
<
>>> array
[2, 4, 5, 13, 18, 24, 34, 97]
Line 1,502 ⟶ 1,882:
// sort the array from largest to smallest
>>> array.sort(function (a, b) { return a < b });
[97, 34, 24, 18, 13, 5, 4, 2]</
=={{header|Joy}}==
This example is taken from V.
Define first as multiplying two numbers on the stack.
<
There will be a warning about overwriting builtin first.
Define second as interpreting the passed quotation on the stack.
<
Pass first enclosed in quotes to second
<syntaxhighlight lang
The program prints 6.
Line 1,525 ⟶ 1,905:
====Example 1: "hello blue world"====
<
("world" | filter) as $str
| "hello \($str)" ;
Line 1,533 ⟶ 1,913:
foo( blue ) # prints "hello blue world"
</syntaxhighlight>
====Example 2: g(add; 2; 3)====
<syntaxhighlight lang="jq">
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:
<
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
Line 1,570 ⟶ 1,950:
false
true
false</
=={{header|Julia}}==
<syntaxhighlight lang="julia">
function foo(x)
str = x("world")
Line 1,579 ⟶ 1,960:
end
foo(y -> "blue $y") # prints "hello blue world"
</syntaxhighlight>
The above code snippet defines a named function, <tt>foo</tt>, which takes a single argument, which is a <tt>Function</tt>.
Line 1,585 ⟶ 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.
<syntaxhighlight lang="julia">
function g(x,y,z)
x(y,z)
end
println(g(+,2,3)) # prints 5
</syntaxhighlight>
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,596 ⟶ 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.
<
false
Line 1,617 ⟶ 1,998:
true
false
</syntaxhighlight>
=={{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}}==
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:
<
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()
Line 1,627 ⟶ 2,019:
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):
<
fun main(args: Array<String>) {
val result = higherOrderFunction(3, 5) { x, y -> x + y }
println(result)
}</
{{out}}
<pre>8</pre>
=={{header|Lambdatalk}}==
<syntaxhighlight lang="scheme">
{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
</syntaxhighlight>
=={{header|Lily}}==
<syntaxhighlight lang="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)</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
<
----------------------------------------
-- Runs provided function (of some object) on all elements of the provided list, returns results as new list
Line 1,659 ⟶ 2,095:
end repeat
return res
end</
<
-- passes the built-in function 'sin' (which is a method of the _movie object) as argument to map
Line 1,667 ⟶ 2,103:
put res
-- [0.8415, 0.9093, 0.1411]</
=={{header|Logo}}==
You can pass the quoted symbol for the function and invoke it with RUN.
<
print "stuff
end
Line 1,678 ⟶ 2,114:
end
runstuff "printstuff ; stuff
runstuff [print [also stuff]] ; also stuff</
=={{header|Lua}}==
Lua functions are first-class:
<
b = function(r) print( r() ) end
b(a)</
=={{header|Luck}}==
Higher-order functions can be used to implement conditional expressions:
<
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") );;</
=={{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}}==
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[Tan, Cos, Sin, x]
% /. x -> 0.12
PassFunc[Tan, Cos, Sin, 0.12]</
gives back:
<
0.119414
0.119414</
=={{header|MATLAB}} / {{header|Octave}}==
<
F2=@cos; % F2 refers to function cos()
% varios ways to call the
F1(pi/4)
F2(pi/4)
Line 1,751 ⟶ 2,212:
F4 = 'cos';
feval(F3,pi/4)
feval(F4,pi/4)</
=={{header|Maxima}}==
<
caller(f, n) := sum(f(i), i, 1, n)$
caller(callee, 3);
"called with 1"
"called with 2"
"called with 3"</
=={{header|MAXScript}}==
<
(
print "Second"
Line 1,772 ⟶ 2,233:
)
first second</
=={{header|Metafont}}==
Line 1,778 ⟶ 2,239:
We can simulate this by using <code>scantokens</code>, which ''digests'' a string as if it would be a source input.
<
t := calcit(100.4, "sind");
show t;
end</
=={{header|МК-61/52}}==
<syntaxhighlight lang="text">6 ПП 04
П7 КПП7 В/О
1 В/О</
''Note'': as the receiver of argument used register ''Р7''; the result is "1" on the indicator.
=={{header|Modula-3}}==
<
IMPORT IO;
Line 1,810 ⟶ 2,271:
BEGIN
First(Second);
END Proc.</
=={{header|Morfa}}==
{{trans|D}}
<
func g(a: int, b: int, f: func(int,int): int): int
{
Line 1,827 ⟶ 2,288:
println("Multiply: ", g(2, 3, func(a: int, b: int) { return a * b; }));
}
</syntaxhighlight>
=={{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}}==
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.
<
=={{header|NewLISP}}==
<
(lambda (a b) (* a b))
> (define (call-it f x y) (f x y))
Line 1,840 ⟶ 2,316:
> (call-it my-multiply 2 3)
6
</syntaxhighlight>
=={{header|Nim}}==
<
return fn()
Line 1,849 ⟶ 2,325:
return "second"
echo first(second)</
=={{header|Oberon-2}}==
Works with oo2c version 2
<
MODULE HOFuns;
IMPORT
Line 1,888 ⟶ 2,364:
PrintWords(words,Tools.AdjustRight)
END HOFuns.
</syntaxhighlight>
=={{header|Objeck}}==
<
bundle Default {
class HighOrder {
Line 1,908 ⟶ 2,384:
}
}
</syntaxhighlight>
=={{header|OCaml}}==
A function is just a value that wants arguments:
<
val func1 : (string -> 'a) -> 'a = <fun>
# let func2 s = "func2 called with " ^ s;;
Line 1,920 ⟶ 2,396:
# print_endline (func1 func2);;
func2 called with a string
- : unit = ()</
Or, with an anonymous function:
<
val func : (int -> int -> 'a) -> 'a = <fun>
# Printf.printf "%d\n" (func (fun x y -> x + y));;
3
- : unit = ()</
Note that <tt>func (fun x y -> x + y)</tt> is equivalent to <tt>func (+)</tt>. (Operators are functions too.)
Line 1,935 ⟶ 2,411:
We can pass a function handle (<code>@function_name</code>)
<
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 <code>feval</code> primitive.
<
r = f(feval(g, v));
endfunction
computeit2(@exp, "sin", pi/3)</
=={{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}}==
Line 1,954 ⟶ 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.
Here we pass #1+ to map :
<
=={{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}}==
routines are first class ooRexx objects that can be passed to other routines or methods and invoked.
<
say callit(.routines~fact, 6)
say callit(.routines~square, 13)
Line 2,013 ⟶ 2,520:
next = current
end
return current</
{{out}}
<pre>55
Line 2,027 ⟶ 2,534:
Functions in Order can accept any other named function, local variable, or anonymous function as arguments:
<syntaxhighlight lang="c">
#include <order/interpreter.h>
Line 2,056 ⟶ 2,563:
)
// -> 16
</syntaxhighlight>
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}}==
<
'FUNCTION TO BE PASSED
'=====================
Line 2,090 ⟶ 2,597:
print g(@f#double#double) 'result '42'
</syntaxhighlight>
=={{header|Oz}}==
Functions are just regular values in Oz.
<
fun {Twice Function X}
{Function {Function X}}
end
in
{Show {Twice Sqrt 81.0}} %% prints 3.0</
=={{header|PARI/GP}}==
{{works with|PARI/GP|2.4.2 and above}} <!-- requires closures -->
<
e = eps() * 2;
aval=ff(a);
Line 2,121 ⟶ 2,628:
precision(2. >> (32 * ceil(default(realprecision) * 38539962 / 371253907)), 9)
};
addhelp(eps,"Returns machine epsilon for the current precision.");</
=={{header|Pascal}}==
Standard Pascal (will not work with Turbo Pascal):
<
function first(function f(x: real): real): real;
Line 2,139 ⟶ 2,646:
begin
writeln(first(second));
end.</
[[Turbo Pascal]] (will not work with Standard Pascal):
<
type
Line 2,162 ⟶ 2,669:
begin
writeln(first(second));
end.</
=== 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}}==
<
# take a function and a value
my $func = shift;
Line 2,191 ⟶ 3,429:
);
print another $dispatch{$_}, 123 for qw(square cube rev);</
<
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
Line 2,200 ⟶ 3,438:
print join ", " => apply {tr/aeiou/AEIOU/} qw/one two three four/;
# OnE, twO, thrEE, fOUr</
<
sub second {'second'}
Line 2,208 ⟶ 3,446:
print first \&second;
print first sub{'sub'};</
=={{header|Phix}}==
{{libheader|Phix/basics}}
<!--<syntaxhighlight lang="phix">(phixonline)-->
<span style="color: #008080;">procedure</span> <span style="color: #000000;">use</span><span style="color: #0000FF;">(</span><span style="color: #004080;">integer</span> <span style="color: #000000;">fi</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">a</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">b</span><span style="color: #0000FF;">)</span>
<span style="color: #0000FF;">?</span><span style="color: #000000;">fi</span><span style="color: #0000FF;">(</span><span style="color: #000000;">a</span><span style="color: #0000FF;">,</span><span style="color: #000000;">b</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">procedure</span>
<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>
<span style="color: #008080;">return</span> <span style="color: #000000;">a</span> <span style="color: #0000FF;">+</span> <span style="color: #000000;">b</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">function</span>
<span style="color: #000000;">use</span><span style="color: #0000FF;">(</span><span style="color: #000000;">add</span><span style="color: #0000FF;">,</span><span style="color: #000000;">23</span><span style="color: #0000FF;">,</span><span style="color: #000000;">45</span><span style="color: #0000FF;">)</span>
<!--</syntaxhighlight>-->
{{out}}
<pre>
68
</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}}==
<
return $func();
}
Line 2,259 ⟶ 3,492:
}
$result = first('second');</
Or, with an anonymous function in PHP 5.3+:
<
return $func();
}
$result = first(function() { return 'second'; });</
=={{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}}==
<
(Fun) )
-> first
Line 2,300 ⟶ 3,603:
: (mapcar add (1 2 3) (4 5 6))
-> (5 7 9)</
=={{header|PL/I}}==
<syntaxhighlight lang="pl/i">
f: procedure (g) returns (float);
declare g entry (float);
Line 2,313 ⟶ 3,615:
x = f(p); /* where "p" is the name of a function. */
</syntaxhighlight>
=={{header|Pop11}}==
<
define x_times_three_minus_1(x);
return(3*x-1);
Line 2,322 ⟶ 3,624:
;;; Pass it as argument to built-in function map and print the result
mapdata({0 1 2 3 4}, x_times_three_minus_1) =></
=={{header|PostScript}}==
Postscript functions are either built-in operators or executable arrays (procedures). Both can take either as arguments.
<syntaxhighlight lang="text">
% operator example
% 'ifelse' is passed a boolean and two procedures
Line 2,337 ⟶ 3,639:
/bar { (Hello, world!) } def
/bar load foo ==
</syntaxhighlight>
=={{header|PowerShell}}==
{{works with|PowerShell|4.0}}
<syntaxhighlight lang="powershell">
function f ($y) {
$y*$y
Line 2,348 ⟶ 3,650:
(f $y)
}
</syntaxhighlight>
You can implement a function inside a function.
<syntaxhighlight lang="powershell">
function g2($y) {
function f2($y) {
Line 2,359 ⟶ 3,661:
(f2 $y)
}
</syntaxhighlight>
<b>Calling:</b>
<syntaxhighlight lang="powershell">
g f 5
g2 9
</syntaxhighlight>
<b>Output:</b>
<pre>
Line 2,372 ⟶ 3,674:
=={{header|Prolog}}==
<
first(Predicate) :- call(Predicate).
second(Argument) :- write(Argument).
:-first(second('Hello World!')).
</syntaxhighlight>
=={{header|PureBasic}}==
<
Procedure NumberTwo(arg$)
Line 2,391 ⟶ 3,693:
EndProcedure
NumberOne(@NumberTwo(),"Hello Worldy!")</
=={{header|Python}}==
{{works with|Python|2.5}}
<
return function()
Line 2,402 ⟶ 3,704:
return "second"
result = first(second)</
or
<
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,414 ⟶ 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.
<syntaxhighlight lang="q">
q)sayHi:{-1"Hello ",x;}
q)callFuncWithParam:{x["Peter"]}
Line 2,420 ⟶ 3,722:
Hello Peter
q)callFuncWithParam[sayHi]
Hello Peter</
=={{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}}==
<
tf <- function(x) x^pi # a func. just to test
print(f(sin))
print(f(cos))
print(f(tf))</
=={{header|Racket}}==
<syntaxhighlight lang="racket">
#lang racket/base
(define (add f g x)
(+ (f x) (g x)))
(add sin cos 10)
</syntaxhighlight>
=={{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}}==
This is not strictly passing a function, but the string representing the function name.
<
"doit called with " print $v1 print "\n" print
Line 2,447 ⟶ 3,837:
$v2 call
23.54 "doit" callit</
{{out}}
<pre>callit called with doit
doit called with 23.54
</pre>
=={{header|REBOL}}==
<
Title: "Function Argument"
URL: http://rosettacode.org/wiki/Function_as_an_Argument
]
Line 2,484 ⟶ 3,873:
print ["Squared:" mold map :square x]
print ["Cubed: " mold map :cube x]
print ["Unnamed:" mold map func [i][i * 2 + 1] x]</
Output:
Line 2,494 ⟶ 3,883:
=={{header|Retro}}==
<
#31 [ (
</syntaxhighlight>
=={{header|REXX}}==
<
call function 'fact' , 6; say right( 'fact{'$"} = ", 30) result
call function 'square' , 13; say right( 'square{'$"} = ", 30) result
Line 2,512 ⟶ 3,900:
function: arg ?.; parse arg ,$; signal value (?.)
reverse: return 'REVERSE'($)
square: return $**2</
{{out|output|text= when using the default input:}}
<pre>
Line 2,519 ⟶ 3,907:
cube{3} = 27
reverse{721} = 127
</pre>
=={{header|Ring}}==
<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>
=={{header|Ruby}}==
With a proc (procedure):
<
def to2(&f)
f[2]
Line 2,529 ⟶ 3,965:
to2(&succ) #=> 3
to2{|x| x+1} #=> 3</
With a method:
<
n+1
end
Line 2,540 ⟶ 3,976:
meth = method(:succ)
to2(meth) #=> 3</
=={{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.
<
f(10)
}
Line 2,556 ⟶ 3,991:
println!("{}", execute_with_10(|n| n*n )); // closure
println!("{}", execute_with_10(square)); // function
}</
{{out}}
<pre>100
100</pre>
=={{header|Scala}}==
<
Call:
<
=={{header|Scheme}}==
A function is just a value that wants arguments:
<
> (define (func2 s) (string-append "func2 called with " s))
> (begin (display (func1 func2)) (newline))
func2 called with a string</
Or, with an anonymous function:
<
> (begin (display (func (lambda (x y) (+ x y)))) (newline))
3</
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}}==
<
return f();
}
Line 2,589 ⟶ 4,038:
say first(second); # => "second"
say first(func { "third" }); # => "third"</
=={{header|Slate}}==
Methods and blocks can both be passed as arguments to functions (other methods and blocks):
<
#(1 1 2 3 5 8) collect: function.</
=={{header|Smalltalk}}==
<
second := [ 'second' ].
Transcript show: (first value: second).</
<
#(1 1 2 3 5 8) collect: function.</
=={{header|Sparkling}}==
<
return func(arg);
}
let answer = call_me(function(x) { return 6 * x; }, 7);
print(answer);</
=={{header|Standard ML}}==
<
val func1 = fn : (string -> 'a) -> 'a
- fun func2 s = "func2 called with " ^ s;
Line 2,621 ⟶ 4,070:
- print (func1 func2 ^ "\n");
func2 called with a string
val it = () : unit</
Or, with an anonymous function:
<
val func = fn : (int * int -> 'a) -> 'a
- print (Int.toString (func (fn (x, y) => x + y)) ^ "\n");
3
val it = () : unit</
Note that <tt>func (fn (x, y) => x + y)</tt> is equivalent to <tt>func op+</tt>. (Operators are functions too.)
=={{header|SuperCollider}}==
<
f.({ |x| x + 1 }, 5); // returns 5</
=={{header|Swift}}==
<
func func2(s: String) -> String { return "func2 called with " + s }
println(func1(func2)) // prints "func2 called with a string"</
Or, with an anonymous function:
<
println(func3 {(x, y) in x + y}) // prints "3"</
Note that <tt>{(x, y) in x + y}</tt> can also be written as <tt>{$0 + $1}</tt> or just <tt>+</tt>.
=={{header|Tcl}}==
<
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 <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.
<
proc demoFrag {fragment} {
{*}$fragment 2
Line 2,672 ⟶ 4,121:
demoScript {
parray tcl_platform
}</
=={{header|TI-89 BASIC}}==
Line 2,680 ⟶ 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.
<
Define map(f,l)=Func
Return seq(#f(l[i]),i,1,dim(l))
EndFunc
Disp map("sin", {0, π/6, π/4, π/3, π/2})</
=={{header|Toka}}==
Toka allows obtaining a function pointer via the '''`''' (''backtick'') word. The pointers are passed on the stack, just like all other data.
<
[ invoke ] is second
` first second</
=={{header|Trith}}==
Due to the homoiconic program representation and the [[concatenative]] nature of the language, higher-order functions are as simple as:
<
: hello "Hello, world!" print ;
[hello] twice</
=={{header|TXR}}==
Line 2,703 ⟶ 4,152:
<code>lambda</code> passed to <code>mapcar</code> with environment capture:
<
(mapcar (lambda (x y) (list (inc counter) x y))
'(a b c) '(t r s))))
Line 2,710 ⟶ 4,159:
@ (rep)@a:@(last)@a@(end)
@ (end)
@(end)</
<pre>1:a:t
Line 2,716 ⟶ 4,165:
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}}==
{{trans|Python}}
Functions are first-class objects in Ursa.
<
return (f)
end
Line 2,728 ⟶ 4,192:
out (first second) endl console
# "second" is output to the console</
=={{header|Ursala}}==
Line 2,736 ⟶ 4,200:
equivalent to the given functon composed with itself.
<
test program:
<
#cast %e
example = autocomposition(sqrt) 16.0</
output:
<pre>2.000000e+00</pre>
=={{header|V}}==
Define first as multiplying two numbers on stack
<syntaxhighlight lang
Define second as applying the passed quote on stack
<syntaxhighlight lang
Pass the first enclosed in quote to second which applies it on stack.
<syntaxhighlight lang
=6
=={{header|VBA}}==
Based on the Pascal solution
<
Dim result As Single
result = first("second")
Line 2,767 ⟶ 4,230:
Function second(x As Single) As Single
second = x / 2
End Function</
=={{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}}==
<syntaxhighlight lang="prolog">
domains
intFunction = (integer In) -> integer Out procedure (i).
Line 2,788 ⟶ 4,336:
write(dotwice(addone,2)),
succeed().
</syntaxhighlight>
=={{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}}==
Everything is a first class object so
<
{{out}}
<pre>
Line 2,799 ⟶ 4,405:
</pre>
or
<
fcn(g){ g() }(fcn{ "Hello World!".println() } )</
=={{header|ZX Spectrum Basic}}==
{{trans|BBC_BASIC}}
Input "FN " token first, then enclose it in double quotation marks.
<
20 DEF FN n(x,y)=(x+y)^2
30 PRINT FN f("n",10,11)</
{{omit from|GUISS}}
|