First-class functions: Difference between revisions

m
imported>Arakov
(222 intermediate revisions by 89 users not shown)
Line 1:
{{task|Programming language concepts}}
 
A language has [[wp:First-class function|first-class functions]] if it can do each of the following without recursively invoking a compiler or interpreter or otherwise [[metaprogramming]]:
 
Line 7 ⟶ 8:
* Use functions as return values of other functions
 
 
<br>
;Task:
Write a program to create an ordered collection ''A'' of functions of a real number. At least one function should be built-in and at least one should be user-defined; try using the sine, cosine, and cubing functions. Fill another collection ''B'' with the inverse of each function in ''A''. Implement function composition as in [[Functional Composition]]. Finally, demonstrate that the result of applying the composition of each function in ''A'' and its inverse in ''B'' to a value, is the original value. <small>(Within the limits of computational accuracy)</small>.
 
(A solution need not actually call the collections "A" and "B". These names are only used in the preceding paragraph for clarity.)
 
;Related task:
C.f. [[First-class Numbers]]
[[First-class Numbers]]
<br><br>
 
=={{header|ActionScript}}==
 
{{trans|JavaScript}}
<syntaxhighlight lang="actionscript">
<lang ActionScript>function compose(f:Function, g:Function):Function {
var cube:Function = function(x) {
return Math.pow(x, 3);
};
var cuberoot:Function = function(x) {
return Math.pow(x, 1/3);
};
function compose(f:Function, g:Function):Function {
return function(x:Number) {return f(g(x));};
}
var functions:Array = [Math.cos, Math.tan, function(x:Number){return x*x;}cube];
var inverse:Array = [Math.acos, Math.atan, function(x:Number){return Math.sqrt(x);}cuberoot];
 
function test() {
for (var i:uint = 0; i < functions.length; i++) {
// Applying the composition to 0.5
trace(compose(functions[i], inverse[i])(0.5));
trace(compose(functions[i], inverse[i])(0.5));
}
}
}</lang>
 
test();</syntaxhighlight>
Output:
<pre>
0.5000000000000001
0.5000000000000001
0.5000000000000001
</pre>
 
=={{header|Ada}}==
 
<lang Ada>
Even if the example below solves the task, there are some limitations to how dynamically you can create, store and use functions in Ada, so it is debatable if Ada really has first class functions.
with Ada.Text_IO;
 
with Ada.Numerics.Generic_Elementary_Functions;
<syntaxhighlight lang="ada">with Ada.Float_Text_IO,
procedure Program is
Ada.Integer_Text_IO,
Ada.Text_IO,
Ada.Numerics.Elementary_Functions;
 
procedure First_Class_Functions is
use Ada.Float_Text_IO,
Ada.Integer_Text_IO,
Ada.Text_IO,
Ada.Numerics.Elementary_Functions;
 
function Sqr (X : Float) return Float is
begin
return X ** 2;
end Sqr;
 
type A_Function is access function (X : Float) return Float;
 
generic
F, G : A_Function;
type Number_Type is private;
with function FCompose (X : Number_TypeFloat) return Number_TypeFloat;
 
with function G(X : Number_Type) return Number_Type;
function Compose (X : Number_TypeFloat) return Number_Type;Float is
begin
function Compose(X : Number_Type) return Number_Type is begin return F(G(X)); end;
return F (G (X));
type Function_Type is access function(X : Float) return Float;
end Compose;
function sqr(X : Float) return Float is begin return X * X; end;
 
package Math is new Ada.Numerics.Generic_Elementary_Functions(Float);
typeFunctions Function_List is: array (NaturalPositive range <>) of Function_Type;A_Function := (Sin'Access,
Cos'Access,
functions : Function_List := (Math.sin'Access, Math.cos'Access, Program.sqr'Access);
Sqr'Access);
inverts : Function_List of Function_Type := (Math.arcsin'Access, Math.arccos'Access, Math.sqrt'Access);
Inverses : array (Positive range <>) of A_Function := (Arcsin'Access,
Arccos'Access,
Sqrt'Access);
begin
for iI in functionsFunctions'Range loop
declare
function CIdentity is new Compose (Float,Functions functions(iI).all, invertsInverses (iI).all);
Test_Value : Float := 0.5;
Result : Float;
begin
Result := Identity (Test_Value);
Ada.Text_IO.Put_Line(Float'Image(C(0.5)));
 
if Result = Test_Value then
Put ("Example ");
Put (I, Width => 0);
Put_Line (" is perfect for the given test value.");
else
Put ("Example ");
Put (I, Width => 0);
Put (" is off by");
Put (abs (Result - Test_Value));
Put_Line (" for the given test value.");
end if;
end;
end loop;
end First_Class_Functions;</syntaxhighlight>
end Program;
 
It is bad style (but an explicit requirement in the task description) to put the functions and their inverses in separate arrays rather than keeping each pair in a record and then having an array of that record type.
</lang>
 
=={{header|Aikido}}==
{{incomplete|Aikido|Fails to demonstrate that the result of applying the composition of each function in A and its inverse in B to a value, is the original value}}
{{trans|Javascript}}
<langsyntaxhighlight lang="aikido">
import math
 
Line 73 ⟶ 133:
}
 
</syntaxhighlight>
</lang>
 
=={{header|ALGOL 68}}==
Line 87 ⟶ 147:
violates standard '''ALGOL 68''''s scoping rules. [[ALGOL 68G]] warns about this during
parsing, and then - if run out of scope - rejects during runtime.
<langsyntaxhighlight lang="algol68">MODE F = PROC (REAL)REAL;
OP ** = (REAL x, power)REAL: exp(ln(x)*power);
 
Line 111 ⟶ 171:
STRUCT(F f, inverse f) this := (func list[index], arc func list[index]);
print(((inverse f OF this O f OF this)(.5), new line))
OD</langsyntaxhighlight>
Output:
<pre>+.500000000000000e +0
Line 117 ⟶ 177:
+.500000000000000e +0</pre>
 
=={{header|AutoHotkeyAppleScript}}==
AutoHotkey coreAppleScript does not supporthave newbuilt-in functionfunctions definitionslike atsine runor timecosine.<br>
However, functions can be called by name, so mapping functions is possible:
<lang AutoHotkey>forward := "sin,cube,cos"
inverse := "Asin,cuberoot,Acos"
StringSplit, forward, forward, `, ; store array length in forward0
StringSplit, inverse, inverse, `, ; array contents are in inverse1, inverse2...
Loop, % forward0
MsgBox % map(compose(forward%A_Index%, inverse%A_Index%), 0.500)
Return
 
<syntaxhighlight lang="applescript">-- Compose two functions, where each function is
compose(f, g){
-- a script object with a call(x) handler.
Return map(0, 0, f, g)
on compose(f, g)
script
on call(x)
f's call(g's call(x))
end call
end script
end compose
 
script increment
on call(n)
n + 1
end call
end script
 
script decrement
on call(n)
n - 1
end call
end script
 
script twice
on call(x)
x * 2
end call
end script
 
script half
on call(x)
x / 2
end call
end script
 
script cube
on call(x)
x ^ 3
end call
end script
 
script cuberoot
on call(x)
x ^ (1 / 3)
end call
end script
 
set functions to {increment, twice, cube}
set inverses to {decrement, half, cuberoot}
set answers to {}
repeat with i from 1 to 3
set end of answers to ¬
compose(item i of inverses, ¬
item i of functions)'s ¬
call(0.5)
end repeat
answers -- Result: {0.5, 0.5, 0.5}</syntaxhighlight>
 
Putting math libraries aside for the moment (we can always shell out to bash functions like '''bc'''), a deeper issue is that the architectural position of functions in the AppleScript type system is simply a little too incoherent and second class to facilitate really frictionless work with first-class functions. (This is clearly not what AppleScript was originally designed for).
 
Incoherent, in the sense that built-in functions and operators do not have the same place in the type system as user functions. The former are described as 'commands' in parser errors, and have to be wrapped in user handlers if they are to be used interchangeably with other functions.
 
Second class, in the sense that user functions (or 'handlers' in the terminology of Apple's documentation), are properties of scripts. The scripts are autonomous first class objects, but the handlers are not. Functions which accept other functions as arguments will internally need to use an '''mReturn''' or '''mInject''' function which 'lifts' handlers into script object types. Functions which return functions will similarly have to return them embedded in such script objects.
 
Once we have a function like mReturn, however, we can readily write higher order functions like '''map''', '''zipWith''' and '''mCompose''' below.
 
<syntaxhighlight lang="applescript">on run
set fs to {sin_, cos_, cube_}
set afs to {asin_, acos_, croot_}
-- Form a list of three composed function objects,
-- and map testWithHalf() across the list to produce the results of
-- application of each composed function (base function composed with inverse) to 0.5
script testWithHalf
on |λ|(f)
mReturn(f)'s |λ|(0.5)
end |λ|
end script
map(testWithHalf, zipWith(mCompose, fs, afs))
--> {0.5, 0.5, 0.5}
end run
 
-- Simple composition of two unadorned handlers into
-- a method of a script object
on mCompose(f, g)
script
on |λ|(x)
mReturn(f)'s |λ|(mReturn(g)'s |λ|(x))
end |λ|
end script
end mCompose
 
-- 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
 
-- 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
 
-- zipWith :: (a -> b -> c) -> [a] -> [b] -> [c]
on zipWith(f, xs, ys)
set lng to min(length of xs, length of ys)
set lst to {}
tell mReturn(f)
repeat with i from 1 to lng
set end of lst to |λ|(item i of xs, item i of ys)
end repeat
return lst
end tell
end zipWith
 
-- min :: Ord a => a -> a -> a
on min(x, y)
if y < x then
y
else
x
end if
end min
 
on sin:r
(do shell script "echo 's(" & r & ")' | bc -l") as real
end sin:
 
on cos:r
(do shell script "echo 'c(" & r & ")' | bc -l") as real
end cos:
 
on cube:x
x ^ 3
end cube:
 
on croot:x
x ^ (1 / 3)
end croot:
 
on asin:r
(do shell script "echo 'a(" & r & "/sqrt(1-" & r & "^2))' | bc -l") as real
end asin:
 
on acos:r
(do shell script "echo 'a(sqrt(1-" & r & "^2)/" & r & ")' | bc -l") as real
end acos:</syntaxhighlight>
{{Out}}
<syntaxhighlight lang="applescript">{0.5, 0.5, 0.5}</syntaxhighlight>
 
=={{header|Arturo}}==
 
<syntaxhighlight lang="rebol">cube: function [x] -> x^3
croot: function [x] -> x^(1//3)
 
names: ["sin/asin", "cos/acos", "cube/croot"]
funclist: @[var 'sin, var 'cos, var 'cube]
invlist: @[var 'asin, var 'acos, var 'croot]
 
num: 0.5
 
loop 0..2 'f [
result: call funclist\[f] @[num]
print [names\[f] "=>" call invlist\[f] @[result]]
]</syntaxhighlight>
 
{{out}}
 
<pre>sin/asin => 0.5
cos/acos => 0.4999999999999999
cube/croot => 0.5</pre>
 
=={{header|AutoHotkey}}==
By '''just me'''. [http://ahkscript.org/boards/viewtopic.php?f=17&t=1363&p=16454#p16454 Forum Post]
<syntaxhighlight lang="autohotkey">#NoEnv
; Set the floating-point precision
SetFormat, Float, 0.15
; Super-global variables for function objects
Global F, G
; User-defined functions
Cube(X) {
Return X ** 3
}
CubeRoot(X) {
Return X ** (1/3)
}
; Function arrays, Sin/ASin and Cos/ACos are built-in
FuncArray1 := [Func("Sin"), Func("Cos"), Func("Cube")]
FuncArray2 := [Func("ASin"), Func("ACos"), Func("CubeRoot")]
; Compose
Compose(FN1, FN2) {
Static FG := Func("ComposedFunction")
F := FN1, G:= FN2
Return FG
}
ComposedFunction(X) {
Return F.(G.(X))
}
; Run
X := 0.5 + 0
Result := "Input:`n" . X . "`n`nOutput:"
For Index In FuncArray1
Result .= "`n" . Compose(FuncArray1[Index], FuncArray2[Index]).(X)
MsgBox, 0, First-Class Functions, % Result
ExitApp</syntaxhighlight>
 
{{Output}}
<pre>Input:
0.500000000000000
 
Output:
0.500000000000000
0.500000000000000
0.500000000000001</pre>
 
=={{header|Axiom}}==
Using the interpreter:
<syntaxhighlight lang="axiom">fns := [sin$Float, cos$Float, (x:Float):Float +-> x^3]
inv := [asin$Float, acos$Float, (x:Float):Float +-> x^(1/3)]
[(f*g) 0.5 for f in fns for g in inv]</syntaxhighlight>
Using the Spad compiler:
<syntaxhighlight lang="axiom">)abbrev package TESTP TestPackage
TestPackage(T:SetCategory) : with
_*: (List((T->T)),List((T->T))) -> (T -> List T)
== add
import MappingPackage3(T,T,T)
fs * gs ==
((x:T):(List T) +-> [(f*g) x for f in fs for g in gs])</syntaxhighlight>
This would be called using:
<syntaxhighlight lang="axiom">(fns * inv) 0.5</syntaxhighlight>
Output:
<syntaxhighlight lang="axiom">[0.5,0.5,0.5]</syntaxhighlight>
 
=={{header|BBC BASIC}}==
{{works with|BBC BASIC for Windows}}
Strictly speaking you cannot return a ''function'', but you can return a ''function pointer'' which allows the task to be implemented.
<syntaxhighlight lang="bbcbasic"> REM Create some functions and their inverses:
DEF FNsin(a) = SIN(a)
DEF FNasn(a) = ASN(a)
DEF FNcos(a) = COS(a)
DEF FNacs(a) = ACS(a)
DEF FNcube(a) = a^3
DEF FNroot(a) = a^(1/3)
dummy = FNsin(1)
REM Create the collections (here structures are used):
DIM cA{Sin%, Cos%, Cube%}
DIM cB{Asn%, Acs%, Root%}
cA.Sin% = ^FNsin() : cA.Cos% = ^FNcos() : cA.Cube% = ^FNcube()
cB.Asn% = ^FNasn() : cB.Acs% = ^FNacs() : cB.Root% = ^FNroot()
REM Create some function compositions:
AsnSin% = FNcompose(cB.Asn%, cA.Sin%)
AcsCos% = FNcompose(cB.Acs%, cA.Cos%)
RootCube% = FNcompose(cB.Root%, cA.Cube%)
REM Test applying the compositions:
x = 1.234567 : PRINT x, FN(AsnSin%)(x)
x = 2.345678 : PRINT x, FN(AcsCos%)(x)
x = 3.456789 : PRINT x, FN(RootCube%)(x)
END
DEF FNcompose(f%,g%)
LOCAL f$, p%
f$ = "(x)=" + CHR$&A4 + "(&" + STR$~f% + ")(" + \
\ CHR$&A4 + "(&" + STR$~g% + ")(x))"
DIM p% LEN(f$) + 4
$(p%+4) = f$ : !p% = p%+4
= p%</syntaxhighlight>
'''Output:'''
<pre>
1.234567 1.234567
2.345678 2.345678
3.456789 3.456789
</pre>
 
=={{header|Bori}}==
<syntaxhighlight lang="bori">double acos (double d) { return Math.acos(d); }
double asin (double d) { return Math.asin(d); }
double cos (double d) { return Math.cos(d); }
double sin (double d) { return Math.sin(d); }
double croot (double d) { return Math.pow(d, 1/3); }
double cube (double x) { return x * x * x; }
 
map(abVar =compose 0, x = 0(Var f, aVar = 0g, bdouble = 0x)
{
Func ff = f;
Static
Func fg = g;
If (a And b)
return ff(fg(x));
Return a . "`n" . b
If ab
{
StringSplit, ab, ab, `n
Return %ab1%(%ab2%(x))
}
}
 
void button1_onClick (Widget widget)
cube(x){
{
Return x ** 3
Array arr1 = [ sin, cos, cube ];
}
Array arr2 = [ asin, acos, croot ];
str s;
for (int i = 1; i <= 3; i++)
{
s << compose(arr1.get(i), arr2.get(i), 0.5) << str.newline;
}
label1.setText(s);
}</syntaxhighlight>
Output on Android phone:
<syntaxhighlight lang="bori">0.5
0.4999999999999999
0.5000000000000001</syntaxhighlight>
 
=={{header|BQN}}==
cuberoot(x){
BQN has full support for first class functions in the context of this wiki page. A more detailed article on BQN's implementation of functional programming is discussed [https://mlochbaum.github.io/BQN/doc/functional.html here].
Return x ** (1 / 3)
 
}</lang>
<code>∘</code> (Atop) is used here to compose the two lists of functions given. Higher order functions are then used to apply the functions on a value. There is a slight change in value due to floating point inaccuracy.
 
BQN has provisions to invert builtin functions using <code>⁼</code> (Undo), and that can also be used for this demonstration, if we remove the block function (<code>funsB ← {𝕏⁼}¨ funsA</code>).
 
<syntaxhighlight lang="bqn">funsA ← ⟨⋆⟜2,-,•math.Sin,{𝕩×3}⟩
funsB ← ⟨√,-,•math.Asin,{𝕩÷3}⟩
 
comp ← funsA {𝕎∘𝕏}¨ funsB
 
•Show comp {𝕎𝕩}¨<0.5</syntaxhighlight>
<syntaxhighlight lang="bqn">⟨ 0.5000000000000001 0.5 0.5 0.5 ⟩</syntaxhighlight>
 
[https://mlochbaum.github.io/BQN/try.html#code=ZnVuc0Eg4oaQIOKfqOKLhuKfnDIsLSzigKJtYXRoLlNpbix78J2VqcOXM33in6kKZnVuc0Ig4oaQIOKfqOKImiwtLOKAom1hdGguQXNpbix78J2VqcO3M33in6kKCmNvbXAg4oaQIGZ1bnNBIHvwnZWO4oiY8J2Vj33CqCBmdW5zQgoK4oCiU2hvdyBjb21wIHvwnZWO8J2VqX3CqDwwLjU= Try It!]
 
=={{header|Bracmat}}==
Bracmat has no built-in functions of real values. To say the truth, Bracmat has no real values. The only pair of currently defined built-in functions for which inverse functions exist are <code>d2x</code> and <code>x2d</code> for decimal to hexadecimal conversion and vice versa. These functions also happen to be each other's inverse. Because these two functions only take non-negative integer arguments, the example uses the argument <code>3210</code> for each pair of functions.
 
The lists <code>A</code> and <code>B</code> contain a mix of function names and function definitions, which illustrates that they always can take each other's role, except when a function definition is assigned to a function name, as for example in the first and second lines.
 
The <code>compose</code> function uses macro substitution.
<syntaxhighlight lang="bracmat">( (sqrt=.!arg^1/2)
& (log=.e\L!arg)
& (A=x2d (=.!arg^2) log (=.!arg*pi))
& ( B
= d2x sqrt (=.e^!arg) (=.!arg*pi^-1)
)
& ( compose
= f g
. !arg:(?f.?g)
& '(.($f)$(($g)$!arg))
)
& whl
' ( !A:%?F ?A
& !B:%?G ?B
& out$((compose$(!F.!G))$3210)
)
)</syntaxhighlight>
Output:
<pre>3210
3210
3210
3210</pre>
 
=={{header|C}}==
Line 157 ⟶ 557:
Here goes.
 
<langsyntaxhighlight lang="c">#include <stdlib.h>
#include <stdio.h>
#include <math.h>
Line 228 ⟶ 628:
return 0;
}</langsyntaxhighlight>
===Non-portable function body duplication===
Following code generates true functions at run time. Extremely unportable, and [http://en.wikipedia.org/wiki/Considered_harmful should be considered harmful] in general, but it's one (again, harmful) way for the truly desperate (or perhaps for people supporting only one platform -- and note that some other languages only work on one platform).
<langsyntaxhighlight Clang="c">#include <stdio.h>
#include <stdlib.h>
#include <string.h>
Line 286 ⟶ 686:
}
return 0;
}</langsyntaxhighlight>(Boring) output<syntaxhighlight lang="text">C0(0.2) = 0.2
C0(0.4) = 0.4
C0(0.6) = 0.6
Line 302 ⟶ 702:
C2(0.6) = 0.6
C2(0.8) = 0.8
C2(1) = 1</langsyntaxhighlight>
 
=={{header|C sharp|C#}}==
<syntaxhighlight lang="csharp">using System;
{{works with|C sharp|4.0}}
 
<lang csharp>using System;
using System.Linq;
 
class Program
Line 314 ⟶ 711:
static void Main(string[] args)
{
var cube = new Func<double, double> cube = (x => Math.Pow(x, 3.0));
var croot = new Func<double, double> croot = (x => Math.Pow(x, (double) 1 / 3.0));
 
var funclistfunctionTuples = new[] {Math.Sin, Math.Cos, cube};
{
var funclisti = new[] {Math.Asin, Math.Acos, croot};
(forward: Math.Sin, backward: Math.Asin),
var composed = funclist.Zip(funclisti, (f, s) =>
(forward: Math.Cos, backward: {Math.Acos),
(forward: Func<doublecube, double> compose = x =>backward: f(s(x)croot);
return compose};
});
 
foreach (var composeft in composedfunctionTuples)
{
Console.WriteLine(compose(0.5));
Console.WriteLine(ft.backward(ft.forward(0.5)));
}
}
}
</syntaxhighlight>
</lang>
 
Output:
<pre>0.5
0.5
0.5</pre>
 
=={{header|C++}}==
{{works with|C++11}}
 
<langsyntaxhighlight lang="cpp">
#include <functional>
#include <vectoralgorithm>
#include <iostream>
#include <vector>
#include <cmath>
 
using std::vector;
using std::cout;
using std::endl;
using std::vector;
using std::function;
using std::transform;
using std::back_inserter;
 
vectortypedef function<double(*)(double)> A = {sin, cos, tan, [](double x) { return x*x*x; } }FunType;
vector<double(*)(double)> B = {asin, acos, atan, [](double x) { return exp(log(x)/3); } };
 
vector<FunType> A = {sin, cos, tan, [](double x) { return x*x*x; } };
template <typename A, typename B, typename... Params>
vector<FunType> B = {asin, acos, atan, [](double x) { return exp(log(x)/3); } };
function<A(Params...)> compose(A(*f)(B), B(*g)(Params...)){
 
return [=](Params... args){ return f(g(args...)); };
template <typename A, typename B, typename C>
function<C(A)> compose(function<C(B)> f, function<B(A)> g) {
return [f,g](A x) { return f(g(x)); };
}
 
#define PRINT(x) cout << #x ": " << (x) << endl;
int main() {
vector<FunType> composedFuns;
double num = 1 / 3.14159;
auto exNums = {0.0, 0.2, 0.4, 0.6, 0.8, 1.0};
 
PRINT(num);
PRINT(composetransform(B[0].begin(), A[0])B.end(num));,
PRINT(compose(B[1], A[1]).begin(num));,
back_inserter(composedFuns),
PRINT(compose(B[2], A[2])(num));
PRINT( compose(B[3]<double, double, A[3])(num)double>);
 
for (auto num: exNums)
for (auto fun: composedFuns)
cout << u8"f\u207B\u00B9.f(" << num << ") = " << fun(num) << endl;
 
auto identity = compose(log10, pow);
PRINT(identity(10, num));
return 0;
}
</syntaxhighlight>
</lang>
 
=={{header|Ceylon}}==
{{works with|Ceylon 1.2.1}}
First, you need to import the numeric module in you module.ceylon file
<syntaxhighlight lang="ceylon">module rosetta "1.0.0" {
import ceylon.numeric "1.2.1";
}</syntaxhighlight>
And then you can use the math functions in your run.ceylon file
<syntaxhighlight lang="ceylon">import ceylon.numeric.float {
 
sin, exp, asin, log
}
 
shared void run() {
function cube(Float x) => x ^ 3;
function cubeRoot(Float x) => x ^ (1.0 / 3.0);
value functions = {sin, exp, cube};
value inverses = {asin, log, cubeRoot};
for([func, inv] in zipPairs(functions, inverses)) {
print(compose(func, inv)(0.5));
}
}</syntaxhighlight>
 
=={{header|Clojure}}==
<langsyntaxhighlight lang="clojure">
(use 'clojure.contrib.math)
(let [fns [#(Math/sin %) #(Math/cos %) (fn [x] (* x x x))]
inv [#(Math/asin %) #(Math/acos %) #(expt % 1/3)]]
(map #(% 0.5) (map #(comp %1 %2) fns inv)))
</syntaxhighlight>
</lang>
Output:
<pre>(0.5 0.4999999999999999 0.5000000000000001)</pre>
Line 381 ⟶ 815:
=={{header|CoffeeScript}}==
{{trans|JavaScript}}
<langsyntaxhighlight lang="coffeescript">compose# =Functions (f,as g)values ->of a variable
cube = (x) -> Math.pow x, 3
cuberoot = (x) -> Math.pow x, 1 / f g x3
 
# Higher order function
fn = [Math.sin, Math.cos, (x) -> Math.pow(x, 3) ]
invcompose = [Math.asin(f, Math.acos,g) -> (x) -> Math.powf g(x, 1/3) ]
 
# Storing functions in a array
do ->
fun = [Math.sin, Math.cos, cube]
for i in [0..2]
inv = [Math.asin, Math.acos, cuberoot]
f = compose inv[i], fn[i]
 
console.log f 0.5 # 0.5</lang>
# Applying the composition to 0.5
console.log compose(inv[i], fun[i])(0.5) for i in [0..2]​​​​​​​</syntaxhighlight>
Output:
<pre>0.5
0.4999999999999999
0.5</pre>
 
=={{header|Common Lisp}}==
<langsyntaxhighlight lang="lisp">(defun compose (f g) (lambda (x) (funcall f (funcall g x))))
(defun cube (x) (expt x 3))
(defun cube-root (x) (expt x (/ 3)))
 
(loop with value = 0.5
for functionfunc in (list #'sin #'cos #'cube )
for inverse in (list #'asin #'acos #'cube-root)
for composed = (compose inverse functionfunc)
do (format t "~&(~A ∘ ~A)(~A) = ~A~%"
inverse
functionfunc
value
(funcall composed value)))</langsyntaxhighlight>
 
Output:
 
<langsyntaxhighlight lang="lisp">(#<FUNCTION ASIN> ∘ #<FUNCTION SIN>)(0.5) = 0.5
(#<FUNCTION ACOS> ∘ #<FUNCTION COS>)(0.5) = 0.5
(#<FUNCTION CUBE-ROOT> ∘ #<FUNCTION CUBE>)(0.5) = 0.5</langsyntaxhighlight>
 
=={{header|D}}==
===Using Standard Compose===
'''D 2.0 version''' of compose function (template).
<syntaxhighlight lang="d">void main() {
<lang D>import std.stdio;
import std.stdio, std.math, std.typetuple, std.functional;
 
alias dir = TypeTuple!(sin, cos, x => x ^^ 3);
T delegate(S) compose(T, U, S)(T delegate(U) f, U delegate(S) g) {
returnalias (Sinv s)= {TypeTuple!(asin, returnacos, f(g(scbrt)); };
// foreach (f, g; staticZip!(dir, inv))
}</lang>
foreach (immutable i, f; dir)
writefln("%6.3f", compose!(f, inv[i])(0.5));
}</syntaxhighlight>
{{out}}
<pre> 0.500
0.500
0.500</pre>
 
===Defining Compose===
Compose working both in D 1.0 and 2.0:
Here we need wrappers because the standard functions have different signatures (eg pure/nothrow). Same output.
<lang D>T delegate(S) compose(T, U, S)(T delegate(U) f, U delegate(S) g) {
<syntaxhighlight lang="d">void main() {
struct Wrapper {
import std.stdio, std.math, std.range;
typeof(f) fcp;
 
typeof(g) gcp;
static T foobardelegate(S s) {compose(T, returnU, fcpS)(gcpin T function(s)in U); }f,
in U function(in S) g) {
return s => f(g(s));
}
 
immutable sin = (in real x) pure nothrow => x.sin,
Wrapper* hold = new Wrapper;
asin = (in real x) pure nothrow => x.asin,
hold.fcp = f;
cos = (in real x) pure nothrow => x.cos,
hold.gcp = g;
acos = (in real x) pure nothrow => x.acos,
return &hold.foobar;
cube = (in real x) pure nothrow => x ^^ 3,
}</lang>
cbrt = (in real x) /*pure*/ nothrow => x.cbrt;
 
foreach (f, g; [sin, cos, cube].zip([asin, acos, cbrt]))
Example:
writefln("%6.3f", compose(f, g)(0.5));
}</syntaxhighlight>
 
=={{header|Dart}}==
<lang D>import std.stdio, std.math, std.range;
<syntaxhighlight lang="dart">import 'dart:math' as Math;
cube(x) => x*x*x;
cuberoot(x) => Math.pow(x, 1/3);
compose(f,g) => ((x)=>f(g(x)));
main(){
var functions = [Math.sin, Math.exp, cube];
var inverses = [Math.asin, Math.log, cuberoot];
for (int i = 0; i < 3; i++){
print(compose(functions[i], inverses[i])(0.5));
}
}</syntaxhighlight>
{{out}}
<pre>
0.49999999999999994
0.5
0.5000000000000001
</pre>
=={{header|Delphi}}==
{{libheader| System.SysUtils}}
{{libheader| System.Math}}
{{Trans|C#}}
<syntaxhighlight lang="delphi">
program First_class_functions;
 
{$APPTYPE CONSOLE}
T delegate(S) compose(T, U, S)(T delegate(U) f, U delegate(S) g) {
return (S s){ return f(g(s)); };
}
 
uses
void main() {
System.SysUtils,
// warper need as not all built-in real functions
System.Math;
// have same signature, eg pure/nothrow
auto sin = (real x){ return std.math.sin(x); };
auto asin = (real x){ return std.math.asin(x); };
auto cos = (real x){ return std.math.cos(x); };
auto acos = (real x){ return std.math.acos(x); };
auto cube = (real x){ return x ^^ 3; };
auto cbrt = (real x){ return std.math.cbrt(x); };
 
type
auto fun = [sin, cos, cube];
TFunctionTuple = record
auto inv = [asin, acos, cbrt];
forward, backward: TFunc<Double, Double>;
procedure Assign(forward, backward: TFunc<Double, Double>);
end;
 
TFunctionTuples = array of TFunctionTuple;
foreach (f2; zip(fun, inv))
writefln("%6.3f", compose(f2[0], f2[1])(0.5));
}</lang>
Using the compose() of the std lib, D v2:
<lang d>import std.stdio, std.math, std.typetuple, std.functional;
 
var
void main() {
cube, croot, fsin, fcos, faSin, faCos: TFunc<Double, Double>;
// wrappers needed as not all built-in functions
FunctionTuples: TFunctionTuples;
// have same signature, eg pure/nothrow
ft: TFunctionTuple;
auto sin = (real x){ return std.math.sin(x); };
auto asin = (real x){ return std.math.asin(x); };
auto cos = (real x){ return std.math.cos(x); };
auto acos = (real x){ return std.math.acos(x); };
auto cube = (real x){ return x ^^ 3; };
auto cbrt = (real x){ return std.math.cbrt(x); };
 
{ TFunctionTuple }
alias TypeTuple!(sin, cos, cube) dir;
alias TypeTuple!(asin, acos, cbrt) inv;
 
procedure TFunctionTuple.Assign(forward, backward: TFunc<Double, Double>);
foreach (i, f; dir)
begin
writefln("%6.3f", compose!(f, inv[i])(0.5));
self.forward := forward;
}</lang>
self.backward := backward;
end;
 
begin
=={{header|Dart}}==
cube :=
<lang dart>cube(x) { return x * x * x; }
function(x: Double): Double
inv_cube(x) { return Math.pow(x, 1/3); }
begin
result := x * x * x;
end;
 
croot :=
compo(f1, f2) {
function(x: Double): Double
return func(x) { return f1(f2(x));};
begin
result := Power(x, 1 / 3.0);
end;
 
fsin :=
function(x: Double): Double
begin
result := Sin(x);
end;
 
fcos :=
function(x: Double): Double
begin
result := Cos(x);
end;
 
faSin :=
function(x: Double): Double
begin
result := ArcSin(x);
end;
 
faCos :=
function(x: Double): Double
begin
result := ArcCos(x);
end;
 
SetLength(FunctionTuples, 3);
FunctionTuples[0].Assign(fsin, faSin);
FunctionTuples[1].Assign(fcos, faCos);
FunctionTuples[2].Assign(cube, croot);
 
for ft in FunctionTuples do
Writeln(ft.backward(ft.forward(0.5)):2:2);
 
readln;
end.</syntaxhighlight>
{{out}}
<pre>0.50
0.50
0.50</pre>
 
=={{header|Dyalect}}==
 
===Create new functions from preexisting functions at run-time===
 
Using partial application:
 
<syntaxhighlight lang="dyalect">func apply(fun, x) { y => fun(x, y) }
 
func sum(x, y) { x + y }
 
let sum2 = apply(sum, 2)</syntaxhighlight>
 
===Store functions in collections===
 
<syntaxhighlight lang="dyalect">func sum(x, y) { x + y }
func doubleMe(x) { x + x }
 
var arr = []
arr.Add(sum)
arr.Add(doubleMe)
arr.Add(arr.ToString)</syntaxhighlight>
 
===Use functions as arguments to other functions===
 
<syntaxhighlight lang="dyalect">func Iterator.Filter(pred) {
for x in this when pred(x) {
yield x
}
}
 
[1,2,3,4,5].Iterate().Filter(x => x % 2 == 0)</syntaxhighlight>
main() {
 
var funcs = [Math.sin, Math.exp, cube];
===Use functions as return values of other functions===
var invs = [Math.asin, Math.log, inv_cube];
 
for (int i = 0; i < 3; i++)
<syntaxhighlight lang="dyalect">func flip(fun, x, y) {
print(compo(funcs[i], invs[i])(1));
(y, x) => fun(x, y)
}</lang>
}</syntaxhighlight>
 
=={{header|Déjà Vu}}==
<syntaxhighlight lang="dejavu">negate:
- 0
 
set :A [ @++ $ @negate @-- ]
 
set :B [ @-- $ @++ @negate ]
 
test n:
for i range 0 -- len A:
if /= n call compose @B! i @A! i n:
return false
true
 
test to-num !prompt "Enter a number: "
if:
!print "f^-1(f(x)) = x"
else:
!print "Something went wrong."
</syntaxhighlight>
 
{{out}}
<pre>Enter a number: 23
f^-1(f(x)) = x</pre>
 
=={{header|E}}==
Line 502 ⟶ 1,064:
The relevant mathematical operations are provided as methods on floats, so the first thing we must do is define them as functions.
 
<langsyntaxhighlight lang="e">def sin(x) { return x.sin() }
def cos(x) { return x.cos() }
def asin(x) { return x.asin() }
Line 510 ⟶ 1,072:
 
def forward := [sin, cos, cube]
def reverse := [asin, acos, curt]</langsyntaxhighlight>
 
There are no built-in functions in this list, since the original author couldn't easily think of any which had one parameter and were inverses of each other, but composition would work just the same with them.
 
Defining composition. <code>fn ''params'' { ''expr'' }</code> is shorthand for an anonymous function returning a value.
<langsyntaxhighlight lang="e">def compose(f, g) {
return fn x { f(g(x)) }
}</langsyntaxhighlight>
 
<langsyntaxhighlight lang="e">? def x := 0.5 \
> for i => f in forward {
> def g := reverse[i]
Line 527 ⟶ 1,089:
x = 0.5, f = <sin>, g = <asin>, compose(<sin>, <asin>)(0.5) = 0.5
x = 0.5, f = <cos>, g = <acos>, compose(<cos>, <acos>)(0.5) = 0.4999999999999999
x = 0.5, f = <cube>, g = <curt>, compose(<cube>, <curt>)(0.5) = 0.5000000000000001</langsyntaxhighlight>
 
Note: <code>def g := reverse[i]</code> is needed here because E as yet has no defined protocol for iterating over collections in parallel. [http://wiki.erights.org/wiki/Parallel_iteration Page for this issue.]
 
=={{header|EchoLisp}}==
<syntaxhighlight lang="scheme">
;; adapted from Racket
;; (compose f g h ... ) is a built-in defined as :
;; (define (compose f g) (λ (x) (f (g x))))
 
(define (cube x) (expt x 3))
(define (cube-root x) (expt x (// 1 3)))
(define funlist (list sin cos cube))
(define ifunlist (list asin acos cube-root))
 
(for ([f funlist] [i ifunlist])
(writeln ((compose i f) 0.5)))
0.5
0.4999999999999999
0.5
</syntaxhighlight>
 
=={{header|Ela}}==
Translation of Haskell:
 
<syntaxhighlight lang="ela">open number //sin,cos,asin,acos
open list //zipWith
 
cube x = x ** 3
croot x = x ** (1/3)
 
funclist = [sin, cos, cube]
funclisti = [asin, acos, croot]
 
zipWith (\f inversef -> (inversef << f) 0.5) funclist funclisti</syntaxhighlight>
 
Function (<<) is defined in standard prelude as:
 
<syntaxhighlight lang="ela">(<<) f g x = f (g x)</syntaxhighlight>
 
Output (calculations are performed on 32-bit floats):
 
<syntaxhighlight lang="ela">[0.5,0.5,0.499999989671302]</syntaxhighlight>
 
=={{header|Elena}}==
ELENA 6.x :
<syntaxhighlight lang="elena">import system'routines;
import system'math;
import extensions'routines;
import extensions'math;
extension op
{
compose(f,g)
= f(g(self));
}
public program()
{
var fs := new object[]{ mssgconst sin<mathOp>[1], mssgconst cos<mathOp>[1], (x => power(x, 3.0r)) };
var gs := new object[]{ mssgconst arcsin<mathOp>[1], mssgconst arccos<mathOp>[1], (x => power(x, 1.0r / 3)) };
fs.zipBy(gs, (f,g => 0.5r.compose(f,g)))
.forEach(printingLn)
}</syntaxhighlight>
{{out}}
<pre>
0.5
0.5
0.5
</pre>
 
=={{header|Elixir}}==
<syntaxhighlight lang="elixir">defmodule First_class_functions do
def task(val) do
as = [&:math.sin/1, &:math.cos/1, fn x -> x * x * x end]
bs = [&:math.asin/1, &:math.acos/1, fn x -> :math.pow(x, 1/3) end]
Enum.zip(as, bs)
|> Enum.each(fn {a,b} -> IO.puts compose([a,b], val) end)
end
defp compose(funs, x) do
Enum.reduce(funs, x, fn f,acc -> f.(acc) end)
end
end
 
First_class_functions.task(0.5)</syntaxhighlight>
 
{{out}}
<pre>
0.5
0.4999999999999999
0.5
</pre>
 
=={{header|Erlang}}==
<syntaxhighlight lang="erlang">
-module( first_class_functions ).
 
-export( [task/0] ).
 
task() ->
As = [fun math:sin/1, fun math:cos/1, fun cube/1],
Bs = [fun math:asin/1, fun math:acos/1, fun square_inverse/1],
[io:fwrite( "Value: 1.5 Result: ~p~n", [functional_composition([A, B], 1.5)]) || {A, B} <- lists:zip(As, Bs)].
 
 
 
functional_composition( Funs, X ) -> lists:foldl( fun(F, Acc) -> F(Acc) end, X, Funs ).
 
square( X ) -> math:pow( X, 2 ).
 
square_inverse( X ) -> math:sqrt( X ).
</syntaxhighlight>
{{out}}
<pre>
93> first_class_functions:task().
Value: 1.5 Result: 1.5000000000000002
Value: 1.5 Result: 1.5
Value: 1.5 Result: 1.5
</pre>
 
=={{header|F_Sharp|F#}}==
<langsyntaxhighlight lang="fsharp">open System
 
let cube x = x ** 3.0
Line 543 ⟶ 1,224:
let main() = for f in composed do printfn "%f" (f 0.5)
 
main()</langsyntaxhighlight>
 
Output:
Line 551 ⟶ 1,232:
 
=={{header|Factor}}==
The constants A and B consist of arrays containing quotations (aka anonymous functions).
<lang factor>USING: assocs combinators kernel math.functions prettyprint
<syntaxhighlight lang="factor">USING: assocs combinators kernel math.functions prettyprint sequences ;
sequences ;
IN: rosettacode.first-class-functions
 
CONSTANT: A { [ sin ] [ cos ] [ 3 ^ ] }
CONSTANT: B { [ asin ] [ acos ] [ 1/3 ^ ] }
 
: compose-all ( seq1 seq2 -- seq ) [ compose ] 2map ;
 
: test1 ( -- )
: test-fcf ( -- )
0.5 A B compose-all
[ call( x -- y ) ] with map . ;</langsyntaxhighlight>
{{out}}
<pre>{ 0.5 0.4999999999999999 0.5 }</pre>
 
=={{header|Fantom}}==
Line 566 ⟶ 1,251:
Methods defined for classes can be pulled out into functions, e.g. "Float#sin.func" pulls the sine method for floats out into a function accepting a single argument. This function is then a first-class value.
 
<langsyntaxhighlight lang="fantom">
class FirstClassFns
{
Line 586 ⟶ 1,271:
}
}
</syntaxhighlight>
</lang>
 
Output:
Line 596 ⟶ 1,281:
 
=={{header|Forth}}==
<langsyntaxhighlight lang="forth">: compose ( xt1 xt2 -- xt3 )
>r >r :noname
r> compile,
Line 617 ⟶ 1,302:
loop ;
 
main \ 0.5 0.5 0.5</langsyntaxhighlight>
 
=={{header|FreeBASIC}}==
Like C, FreeBASIC doesn't have first class functions so I've contented myself by translating their code:
{{trans|C}}
<syntaxhighlight lang="freebasic">' FB 1.05.0 Win64
 
#Include "crt/math.bi" '' include math functions in C runtime library
 
' Declare function pointer type
' This implicitly assumes default StdCall calling convention on Windows
Type Class2Func As Function(As Double) As Double
' A couple of functions with the above prototype
Function functionA(v As Double) As Double
Return v*v*v '' cube of v
End Function
 
Function functionB(v As Double) As Double
Return Exp(Log(v)/3) '' same as cube root of v which would normally be v ^ (1.0/3.0) in FB
End Function
' A function taking a function as an argument
Function function1(f2 As Class2Func, val_ As Double) As Double
Return f2(val_)
End Function
' A function returning a function
Function whichFunc(idx As Long) As Class2Func
Return IIf(idx < 4, @functionA, @functionB)
End Function
 
' Additional function needed to treat CDecl function pointer as StdCall
' Get compiler warning otherwise
Function cl2(f As Function CDecl(As Double) As Double) As Class2Func
Return CPtr(Class2Func, f)
End Function
 
' A list of functions
' Using C Runtime library versions of trig functions as it doesn't appear
' to be possible to apply address operator (@) to FB's built-in versions
Dim funcListA(0 To 3) As Class2Func = {@functionA, cl2(@sin_), cl2(@cos_), cl2(@tan_)}
Dim funcListB(0 To 3) As Class2Func = {@functionB, cl2(@asin_), cl2(@acos_), cl2(@atan_)}
 
' Composing Functions
Function invokeComposed(f1 As Class2Func, f2 As Class2Func, val_ As double) As Double
Return f1(f2(val_))
End Function
 
Type Composition
As Class2Func f1, f2
End Type
 
Function compose(f1 As Class2Func, f2 As Class2Func) As Composition Ptr
Dim comp As Composition Ptr = Allocate(SizeOf(Composition))
comp->f1 = f1
comp->f2 = f2
Return comp
End Function
Function callComposed(comp As Composition Ptr, val_ As Double ) As Double
Return comp->f1(comp->f2(val_))
End Function
 
Dim ix As Integer
Dim c As Composition Ptr
Print "function1(functionA, 3.0) = "; CSng(function1(whichFunc(0), 3.0))
Print
For ix = 0 To 3
c = compose(funcListA(ix), funcListB(ix))
Print "Composition"; ix; "(0.9) = "; CSng(callComposed(c, 0.9))
Next
Deallocate(c)
Print
Print "Press any key to quit"
Sleep</syntaxhighlight>
 
{{out}}
<pre>
function1(functionA, 3.0) = 27
 
Composition 0(0.9) = 0.9
Composition 1(0.9) = 0.9
Composition 2(0.9) = 0.9
Composition 3(0.9) = 0.9
</pre>
 
=={{header|GAP}}==
<langsyntaxhighlight lang="gap"># Function composition
Composition := function(f, g)
local h;
Line 640 ⟶ 1,412:
end;
 
# Inverse and Sqrt are in the built-in library. Note that GAP doesn't have real numbers nor floating point numbers. Therefore, Sqrt yields values in cyclotomic fields.
# For example,
# gap> Sqrt(7);
Line 655 ⟶ 1,427:
# Now a test
ApplyList(z, 3);
[ 3, 3, 3 ]</langsyntaxhighlight>
 
=={{header|Go}}==
<langsyntaxhighlight lang="go">package main
 
import "math"
Line 684 ⟶ 1,456:
fmt.Println(compose(funclisti[i], funclist[i])(.5))
}
}</langsyntaxhighlight>
Output:
<pre>
Line 694 ⟶ 1,466:
=={{header|Groovy}}==
Solution:
<langsyntaxhighlight lang="groovy">def compose = { f, g -> { x -> f(g(x)) } }</langsyntaxhighlight>
 
Test program:
<langsyntaxhighlight lang="groovy">def cube = { it * it * it }
def cubeRoot = { it ** (1/3) }
 
Line 703 ⟶ 1,475:
inverseList = [ Math.&asin, Math.&acos, cubeRoot ]
 
println ([funcList, inverseList].transpose().collect { f, finv -> compose(it[0]f,it[1] finv) }.collect{ it(0.5) })
println ([inverseList, funcList].transpose().collect { finv, f -> compose(it[0]finv,it[1] f) }.collect{ it(0.5) })</langsyntaxhighlight>
 
Output:
Line 711 ⟶ 1,483:
 
=={{header|Haskell}}==
<langsyntaxhighlight lang="haskell">Prelude>cube let:: cubeFloating xa => xa ^-> 3a
Prelude> let crootcube x = x ** (1/3).0
 
Prelude> let compose f g = \x -> f (g x) -- this is already implemented in Haskell as the "." operator
croot :: Floating a => a -> a
Prelude> -- we could have written "let compose f g x = f (g x)" but we show this for clarity
croot x = x ** (1/3)
Prelude> let funclist = [sin, cos, cube]
 
Prelude> let funclisti = [asin, acos, croot]
-- compose already exists in Haskell as the `.` operator
Prelude> zipWith (\f inversef -> (compose inversef f) 0.5) funclist funclisti
-- compose :: (a -> b) -> (b -> c) -> a -> c
[0.5,0.4999999999999999,0.5]</lang>
-- compose f g = \x -> g (f x)
 
funclist :: Floating a => [a -> a]
funclist = [sin, cos, cube ]
 
invlist :: Floating a => [a -> a]
invlist = [asin, acos, croot]
 
main :: IO ()
main = print $ zipWith (\f i -> f . i $ 0.5) funclist invlist </syntaxhighlight>
{{output}}
<pre>[0.5,0.4999999999999999,0.5000000000000001]</pre>
 
=={{header|Icon}} and {{header|Unicon}}==
The Unicon solution can be modified to work in Icon. See [[Function_composition#Icon_and_Unicon]].
<langsyntaxhighlight Uniconlang="unicon">link compose
procedure main(arglist)
 
Line 738 ⟶ 1,522:
procedure cuberoot(x)
return x ^ (1./3)
end</langsyntaxhighlight>
Please refer to See [[Function_composition#Icon_and_Unicon]] for 'compose'.
 
Line 747 ⟶ 1,531:
 
=={{header|J}}==
 
J has some subtleties which are not addressed in this specification (J functions have grammatical character and their [[wp:Gerund|gerundial form]] may be placed in data structures where the spec sort of implies that there be no such distinction).
===Explicit version===
 
J has some subtleties which are not addressed in this specification (J functions have grammatical character and their [[wp:Gerund|gerundial form]] may be placed in data structures where the spec sort of implies that there be no such distinction - for those uncomfortable with this terminology it is best to think of these as type distinctions - the type which appears in data structures and the type which may be applied are distinct though each may be directly derived from the other).
 
However, here are the basics which were requested:
<langsyntaxhighlight lang="j"> sin=: 1&o.
cos=: 2&o.
cube=: ^&3
Line 759 ⟶ 1,546:
A=: sin`cos`cube`square
B=: monad def'y unqo inv quot'"0 A
BA=. A dyad def'x unqo@(y unqo) quot'"0 B</langsyntaxhighlight>
 
<syntaxhighlight lang="text"> A unqcol 0.5
0.479426 0.877583 0.125 0.25
BA unqcol 0.5
0.5 0.5 0.5 0.5</langsyntaxhighlight>
 
===Tacit (unorthodox) version===
In J only adverbs and conjunctions (functionals) can produce verbs (functions)... Unless they are forced to cloak as verbs (functions). (Note that this takes advantage of a bug/feature of the interpreter ; see [http://rosettacode.org/wiki/Closures/Value_capture#Tacit_.28unorthodox.29_version unorthodox tacit] .) The resulting functions (which correspond to functionals) can take and produce functions:
 
<syntaxhighlight lang="j"> train =. (<'`:')(0:`)(,^:)&6 NB. Producing the function train corresponding to the functional `:6
inverse=. (<'^:')(0:`)(,^:)&_1 NB. Producing the function inverse corresponding to the functional ^:_1
compose=. (<'@:')(0:`)(,^:) NB. Producing the function compose corresponding to the functional @:
an =. <@:((,'0') ; ]) NB. Producing the atomic representation of a noun
of =. train@:([ ; an) NB. Evaluating a function for an argument
box =. < @: train"0 NB. Producing a boxed list of the trains of the components
]A =. box (1&o.)`(2&o.)`(^&3) NB. Producing a boxed list containing the Sin, Cos and Cubic functions
┌────┬────┬───┐
│1&o.│2&o.│^&3│
└────┴────┴───┘
]B =. inverse &.> A NB. Producing their inverses
┌────────┬────────┬───────┐
│1&o.^:_1│2&o.^:_1│^&3^:_1│
└────────┴────────┴───────┘
]BA=. B compose &.> A NB. Producing the compositions of the functions and their inverses
┌────────────────┬────────────────┬──────────────┐
│1&o.^:_1@:(1&o.)│2&o.^:_1@:(2&o.)│^&3^:_1@:(^&3)│
└────────────────┴────────────────┴──────────────┘
BA of &> 0.5 NB. Evaluating the compositions at 0.5
0.5 0.5 0.5
</syntaxhighlight>
 
=={{header|Java}}==
Java doesn't technically have first-class functions. Java can simulate first-class functions to a certain extent, with anonymous classes and generic function interface.
{{works with|Java|1.5+}}
<syntaxhighlight lang="java5">import java.util.ArrayList;
 
public class FirstClass{
<lang java>
public static Function<Double, Double> compose(
public interface Function<A,B>{
final Function<Double, Double> f, final Function<Double, Double> g) {
B apply(A x);
return new Function<Double, Double>() {
}
@Override public Double apply(Double x) {
return f.apply(g.apply(x));
public static <A,B,C> Function<A, C> compose(
final Function<B, C> f, final Function<A, B> g) {
return new Function<A, C>() {
@Override public C apply(A x) {
return f.apply(g.apply(x));
}
};
}
public static void main(String[] args){
ArrayList<Function<Double, Double>> functions =
new ArrayList<Function<Double,Double>>();
functions.add(
new Function<Double, Double>(){
@Override public Double apply(Double x){
return Math.cos(x);
}
});
functions.add(
new Function<Double, Double>(){
@Override public Double apply(Double x){
return Math.tan(x);
}
});
functions.add(
new Function<Double, Double>(){
@Override public Double apply(Double x){
return x * x;
}
});
ArrayList<Function<Double, Double>> inverse = new ArrayList<Function<Double,Double>>();
inverse.add(
new Function<Double, Double>(){
@Override public Double apply(Double x){
return Math.acos(x);
}
});
inverse.add(
new Function<Double, Double>(){
@Override public Double apply(Double x){
return Math.atan(x);
}
});
inverse.add(
new Function<Double, Double>(){
@Override public Double apply(Double x){
return Math.sqrt(x);
}
});
System.out.println("Compositions:");
for(int i = 0; i < functions.size(); i++){
System.out.println(compose(functions.get(i), inverse.get(i)).apply(0.5));
}
System.out.println("Hard-coded compositions:");
};
System.out.println(Math.cos(Math.acos(0.5)));
}
System.out.println(Math.tan(Math.atan(0.5)));
System.out.println(Math.pow(Math.sqrt(0.5), 2));
}
}</syntaxhighlight>
Output:
<pre>Compositions:
0.4999999999999999
0.49999999999999994
0.5000000000000001
Hard-coded compositions:
0.4999999999999999
0.49999999999999994
0.5000000000000001</pre>
 
{{works with|Java|8+}}
@SuppressWarnings("unchecked") public static void main(String[] args) {
<syntaxhighlight lang="java5">import java.util.ArrayList;
ArrayList<Function<Double, Double>> functions = Lists.newArrayList(
import java.util.function.Function;
new Function<Double, Double>() {
 
@Override public Double apply(Double x) {
public class FirstClass{
return Math.cos(x);
}
public static void main(String... arguments){
}, new Function<Double, Double>() {
@Override public ArrayList<Function<Double, apply(Double>> x)functions {= new ArrayList<>();
return Math.tan(x);
functions.add(Math::cos);
}
functions.add(Math::tan);
}, new Function<Double, Double>() {
functions.add(x -> x * x);
@Override public Double apply(Double x) {
return x * x;
ArrayList<Function<Double, Double>> inverse = new ArrayList<>();
}
});
inverse.add(Math::acos);
ArrayList<Function<Double, Double>> inverse = Lists.newArrayList(
inverse.add(Math::atan);
new Function<Double, Double>() {
inverse.add(Math::sqrt);
@Override public Double apply(Double x) {
System.out.println("Compositions:");
return Math.acos(x);
for (int i = 0; i < functions.size(); i++){
}
System.out.println(functions.get(i).compose(inverse.get(i)).apply(0.5));
}, new Function<Double, Double>() {
}
@Override public Double apply(Double x) {
System.out.println("Hard-coded compositions:");
return Math.atan(x);
System.out.println(Math.cos(Math.acos(0.5)));
}
System.out.println(Math.tan(Math.atan(0.5)));
}, new Function<Double, Double>() {
System.out.println(Math.pow(Math.sqrt(0.5), 2));
@Override public Double apply(Double x) {
return Math.sqrt(x);
}
});
for (int i = 0; i < functions.size(); i++) {
System.out.println(compose(functions.get(i), inverse.get(i)).apply(0.5));
}
}</syntaxhighlight>
}
 
</lang>
=={{header|JavaScript}}==
===ES5===
assuming the print function is provided by the environment, like a stand-alone shell. In browsers, use alert(), document.write() or similar
<syntaxhighlight lang="javascript">// Functions as values of a variable
var cube = function (x) {
return Math.pow(x, 3);
};
var cuberoot = function (x) {
return Math.pow(x, 1 / 3);
};
 
<lang// javascript>varHigher compose =order function (f, g) {
var compose return= function (xf, g) {
return function return f(g(x)); {
};return f(g(x));
};
};
 
// Storing functions in a array
var fn = [Math.sin, Math.cos, function (x) { return Math.pow(x, 3); }];
var invfun = [Math.asinsin, Math.acoscos, function (x) { return Math.pow(x, 1/3); }cube];
var inv = [Math.asin, Math.acos, cuberoot];
 
for (var i = 0; i < 3; i++) {
(function () {
// Applying the composition to 0.5
for (var i = 0; i < 3; i++) {
var f = console.log(compose(inv[i], fnfun[i])(0.5));
}</syntaxhighlight>
print(f(0.5)); // 0.5
}
})();
 
===ES6===
</lang>
<syntaxhighlight lang="javascript">// Functions as values of a variable
var cube = x => Math.pow(x, 3);
 
var cuberoot = x => Math.pow(x, 1 / 3);
 
 
// Higher order function
var compose = (f, g) => (x => f(g(x)));
 
// Storing functions in a array
var fun = [ Math.sin, Math.cos, cube ];
var inv = [ Math.asin, Math.acos, cuberoot ];
 
for (var i = 0; i < 3; i++) {
// Applying the composition to 0.5
console.log(compose(inv[i], fun[i])(0.5));
}</syntaxhighlight>
 
 
Result is always:
<pre>0.5
0.4999999999999999
0.5</pre>
 
=={{header|jq}}==
{{works with|jq}}
'''Also works with gojq, the Go implementation of jq'''
 
'''Also works with fq, a Go implementation of a large subset of jq'''
 
jq does not support functions as "first class objects" in the sense specified in the task description
but it does give near-first-class status to functions and functional expressions, which can
for example, be passed as arguments to functions. In fact, it is quite straightforward, though possibly misleading,
to transcribe the [[#Wren|Wren]] entry to jq, as follows:
<syntaxhighlight lang=jq>
# Apply g first
def compose(f; g): g | f;
 
def A: [sin, cos, .*.*.];
 
def B: [asin, acos, pow(.; 1/3) ];
 
0.5
| range(0;3) as $i
| compose( A[$i]; B[$i] )
</syntaxhighlight>
However this transcription is inefficient because at each iteration (i.e. for each $i), all three components of A and of B are computed.
To avoid this, one would have to ignore A and B, and instead write:
<pre>
0.5
| compose(sin; asin), compose(cos; acos), compose(pow(.;3); pow(.; 1/3))
</pre>
{{output}}
Using gojq:
<pre>
0.5
0.5000000000000001
0.5000000000000001
</pre>
 
=={{header|Julia}}==
<syntaxhighlight lang="julia">#!/usr/bin/julia
 
function compose(f::Function, g::Function)
return x -> f(g(x))
end
 
value = 0.5
for pair in [(sin, asin), (cos, acos), (x -> x^3, x -> x^(1/3))]
func, inverse = pair
println(compose(func, inverse)(value))
end</syntaxhighlight>
 
Output:
<pre>0.5
0.4999999999999999
0.5000000000000001
</pre>
 
=={{header|Kotlin}}==
 
<syntaxhighlight lang="kotlin">
import kotlin.math.*
 
fun compose(f: (Double) -> Double, g: (Double) -> Double ): (Double) -> Double = { f(g(it)) }
 
fun cube(d: Double) = d * d * d
 
fun main() {
val listA = listOf(::sin, ::cos, ::cube)
val listB = listOf(::asin, ::acos, ::cbrt)
val x = 0.5
for (i in 0..2) println(compose(listA[i], listB[i])(x))
}</syntaxhighlight>
 
{{out}}
<pre>
0.5
0.4999999999999999
0.5000000000000001
</pre>
 
=={{header|Lambdatalk}}==
Tested in [http://epsilonwiki.free.fr/ELS_YAW/?view=p227]
<syntaxhighlight lang="scheme">
{def cube {lambda {:x} {pow :x 3}}}
{def cuberoot {lambda {:x} {pow :x {/ 1 3}}}}
{def compose {lambda {:f :g :x} {:f {:g :x}}}}
{def fun sin cos cube}
{def inv asin acos cuberoot}
{def display {lambda {:i}
{br}{compose {nth :i {fun}}
{nth :i {inv}} 0.5}}}
{map display {serie 0 2}}
 
Output:
0.5
0.49999999999999994
0.5000000000000001
</syntaxhighlight>
 
=={{header|Lang}}==
<syntaxhighlight lang="lang">
fp.cube = ($x) -> return parser.op($x ** 3)
 
fp.cuberoot = ($x) -> return parser.op($x ** (1/3))
 
# fn.concat can be used as compose
 
&funcs $= [fn.sin, fn.cos, fp.cube]
&invFuncs $= [fn.asin, fn.acos, fp.cuberoot]
 
$pair
foreach($[pair], fn.arrayZip(&funcs, &invFuncs)) {
parser.op(fn.println(($pair[0] ||| $pair[1])(.5)))
}
</syntaxhighlight>
 
=={{header|Lasso}}==
<syntaxhighlight lang="lasso">#!/usr/bin/lasso9
 
define cube(x::decimal) => {
return #x -> pow(3.0)
}
 
define cuberoot(x::decimal) => {
return #x -> pow(1.0/3.0)
}
 
define compose(f, g, v) => {
return {
return #f -> detach -> invoke(#g -> detach -> invoke(#1))
} -> detach -> invoke(#v)
}
 
 
local(functions = array({return #1 -> sin}, {return #1 -> cos}, {return cube(#1)}))
local(inverse = array({return #1 -> asin}, {return #1 -> acos}, {return cuberoot(#1)}))
 
loop(3)
stdoutnl(
compose(
#functions -> get(loop_count),
#inverse -> get(loop_count),
0.5
)
)
 
/loop</syntaxhighlight>
 
Output:
<pre>0.500000
0.500000
0.500000
</pre>
 
=={{header|Lingo}}==
Lingo does not support functions as first-class objects. But with the limitations described under [https://www.rosettacode.org/wiki/Function_composition#Lingo Function composition] the task can be solved:
<syntaxhighlight lang="lingo">-- sin, cos and sqrt are built-in, square, asin and acos are user-defined
A = [#sin, #cos, #square]
B = [#asin, #acos, #sqrt]
 
testValue = 0.5
 
repeat with i = 1 to 3
-- for implementation details of compose() see https://www.rosettacode.org/wiki/Function_composition#Lingo
f = compose(A[i], B[i])
res = call(f, _movie, testValue)
put res = testValue
end repeat</syntaxhighlight>
 
{{out}}
<pre>
-- 1
-- 1
-- 1
</pre>
 
User-defined arithmetic functions used in code above:
<syntaxhighlight lang="lingo">on square (x)
return x*x
end
 
on asin (x)
res = atan(sqrt(x*x/(1-x*x)))
if x<0 then res = -res
return res
end
 
on acos (x)
return PI/2 - asin(x)
end</syntaxhighlight>
 
=={{header|Lua}}==
<syntaxhighlight lang ="lua"> function compose(f,g) return function(...) return f(g(...)) end end
 
fn = {math.sin, math.cos, function(x) return x^3 end}
inv = {math.asin, math.acos, function(x) return x^(1/3) end}
 
for i, v in ipairs(fn) do
local f = compose(v, inv[i])
print(f(0.5)) --> 0.5
end</langsyntaxhighlight>
 
Output:
<syntaxhighlight lang="text">0.5
0.5
0.5</syntaxhighlight>
 
=={{header|M2000 Interpreter}}==
Cos, Sin works with degrees, Number pop number from stack of values, so we didn't use a variable like this POW3INV =Lambda (x)->x**(1/3)
<syntaxhighlight lang="m2000 interpreter">
Module CheckFirst {
RAD = lambda -> number/180*pi
ASIN = lambda RAD -> {
Read x : x=Round(x,10)
If x>=0 and X<1 Then {
=RAD(abs(2*Round(ATN(x/(1+SQRT(1-x**2))))))
} Else.if x==1 Then {
=RAD(90)
} Else error "asin exit limit"
}
ACOS=lambda ASIN (x) -> PI/2 - ASIN(x)
POW3 = Lambda ->number**3
POW3INV =Lambda ->number**(1/3)
COSRAD =lambda ->Cos(number*180/pi)
SINRAD=lambda ->Sin(number*180/pi)
Composed=lambda (f1, f2) -> {
=lambda f1, f2 (x)->{
=f1(f2(x))
}
}
Dim Base 0, A(3), B(3), C(3)
A(0)=ACOS, ASIN, POW3INV
B(0)=COSRAD, SINRAD, POW3
C(0)=Composed(ACOS, COSRAD), Composed(ASIN, SINRAD), Composed(POW3INV, POW3)
Print $("0.00")
For i=0 To 2 {
Print A(i)(B(i)(.5)), C(i)(.5)
}
}
CheckFirst
</syntaxhighlight>
 
=={{header|Maple}}==
The composition operator in Maple is denoted by "@". We use "zip" to produce the list of compositions. The cubing procedure and its inverse are each computed.
<syntaxhighlight lang="maple">
> A := [ sin, cos, x -> x^3 ]:
> B := [ arcsin, arccos, rcurry( surd, 3 ) ]:
> zip( `@`, A, B )( 2/3 );
[2/3, 2/3, 2/3]
 
> zip( `@`, B, A )( 2/3 );
[2/3, 2/3, 2/3]
</syntaxhighlight>
 
=={{header|Mathematica}} / {{header|Wolfram Language}}==
The built-in function Composition can do composition, a custom function that does the same would be compose[f_,g_]:=f[g[#]]&. However the latter only works with 2 arguments, Composition works with any number of arguments.
<langsyntaxhighlight Mathematicalang="mathematica">funcs = {Sin, Cos, #^3 &};
funcsi = {ArcSin, ArcCos, #^(1/3) &};
compositefuncs = Composition @@@ Transpose[{funcs, funcsi}];
Table[i[0.666], {i, compositefuncs}]</langsyntaxhighlight>
gives back:
<langsyntaxhighlight Mathematicalang="mathematica">{0.666, 0.666, 0.666}</langsyntaxhighlight>
Note that I implemented cube and cube-root as pure functions. This shows that Mathematica is fully able to handle functions as variables, functions can return functions, and functions can be given as an argument. Composition can be done in more than 1 way:
<langsyntaxhighlight Mathematicalang="mathematica">Composition[f,g,h][x]
f@g@h@x
x//h//g//f</langsyntaxhighlight>
all give back:
<syntaxhighlight lang Mathematica="mathematica">f[g[h[x]]]</langsyntaxhighlight>
 
=={{header|Maxima}}==
<syntaxhighlight lang="maxima">a: [sin, cos, lambda([x], x^3)]$
b: [asin, acos, lambda([x], x^(1/3))]$
compose(f, g) := buildq([f, g], lambda([x], f(g(x))))$
map(lambda([fun], fun(x)), map(compose, a, b));
[x, x, x]</syntaxhighlight>
 
=={{header|Mercury}}==
Line 868 ⟶ 2,024:
 
===firstclass.m===
<syntaxhighlight lang="mercury">
<lang Mercury>:- module firstclass.
:- module firstclass.
 
:- interface.
Line 878 ⟶ 2,035:
 
main(!IO) :-
Forward = [math.sin, math. cos, (func(X) = math.ln(X))],
Reverse = [math.asin, math.acos, (func(X) = math.exp(X))],
Results = list.map_corresponding(
(func(F, R) = compose(R, F, 0.5)),
compose(RForward, FReverse), 0.5)
write_list(Results, ", )", Forwardwrite_float, Reverse!IO),
io.write_listwrite_string(Results, ", \n", io.write_float, !IO),.
</syntaxhighlight>
io.write_string("\n", !IO).</lang>
 
===Use and output===
Line 892 ⟶ 2,049:
 
(Limitations of the IEEE floating point representation make the cos/acos pairing lose a little bit of accuracy.)
 
=={{header|min}}==
{{works with|min|0.19.3}}
Note <code>concat</code> is what performs the function composition, as functions are lists in min.
<syntaxhighlight lang="min">('sin 'cos (3 pow)) =A
('asin 'acos (1 3 / pow)) =B
 
(A bool) (
0.5 A first B first concat -> puts!
A rest #A
B rest #B
) while</syntaxhighlight>
{{out}}
<pre>
0.5
0.4999999999999999
0.5
</pre>
 
=={{header|Nemerle}}==
 
{{trans|Python}}
<langsyntaxhighlight Nemerlelang="nemerle">using System;
using System.Console;
using System.Math;
Line 911 ⟶ 2,087:
WriteLine($[compose(f, g)(0.5) | (f, g) in ZipLazy(funcs, ifuncs)]);
}
}</langsyntaxhighlight>
 
===Use and Output===
C:\Rosetta>ncc -o:FirstClassFunc FirstClassFunc.n
C:Rosetta>FirstClassFunc
[0.5, 0.5, 0.5]
 
=={{header|newLISP}}==
<langsyntaxhighlight newLISPlang="newlisp">> (define (compose f g) (expand (lambda (x) (f (g x))) 'f 'g))
(lambda (f g) (expand (lambda (x) (f (g x))) 'f 'g))
> (define (cube x) (pow x 3))
Line 926 ⟶ 2,108:
> (map (fn (f g) ((compose f g) 0.5)) functions inverses)
(0.5 0.5 0.5)
</syntaxhighlight>
</lang>
 
=={{header|Nim}}==
{{trans|ES6}}
 
Note that when defining a sequence <code>@[a, b, c]</code>, “a” defines the type of the elements. So, if there is an ambiguity, we need to precise the type.
 
For instance <code>@[math.sin, cos]</code> wouldn’t compile as there exists two “sin” functions, one for “float32” and one for “float64”.
 
So, we have to write either <code>@[(proc(x: float64): float64]) math.sin, cos]</code> to avoid the ambiguity or make sure there is no ambiguity as regards the first element.
 
Here, in first sequence, we put in first position our function “sin” defined only for “float64” and in second position the standard one “math.cos”. And in second sequence, we used the type <code>MF64 = proc(x: float64): float64</code> to suppress the ambiguity.
 
<syntaxhighlight lang="nim">from math import nil # Require qualifier to access functions.
 
type MF64 = proc(x: float64): float64
 
proc cube(x: float64) : float64 =
math.pow(x, 3)
 
proc cuberoot(x: float64) : float64 =
math.pow(x, 1/3)
 
proc compose[A](f: proc(x: A): A, g: proc(x: A): A) : (proc(x: A): A) =
proc c(x: A): A =
f(g(x))
return c
 
proc sin(x: float64) : float64 =
math.sin(x)
 
proc acos(x: float64) : float64 =
math.arccos(x)
 
var fun = @[sin, math.cos, cube]
var inv = @[MF64 math.arcsin, acos, cuberoot]
 
for i in 0..2:
echo compose(inv[i], fun[i])(0.5)</syntaxhighlight>
Output:
<pre>0.5
0.4999999999999999
0.5</pre>
 
=={{header|Objeck}}==
<syntaxhighlight lang="objeck">use Collection.Generic;
 
lambdas Func {
Double : (FloatHolder) ~ FloatHolder
}
 
class FirstClass {
function : Main(args : String[]) ~ Nil {
vector := Vector->New()<Func2Holder <FloatHolder, FloatHolder> >;
# store functions in collections
vector->AddBack(Func2Holder->New(\Func->Double : (v)
=> v * v)<FloatHolder, FloatHolder>);
# new function from preexisting function at run-time
vector->AddBack(Func2Holder->New(\Func->Double : (v)
=> Float->SquareRoot(v->Get()))<FloatHolder, FloatHolder>);
# process collection
each(i : vector) {
# return value of other functions and pass argument to other function
Show(vector->Get(i)<Func2Holder>->Get()<FloatHolder, FloatHolder>);
};
}
function : Show(func : (FloatHolder) ~ FloatHolder) ~ Nil {
func(13.5)->Get()->PrintLine();
}
}</syntaxhighlight>
 
=={{header|OCaml}}==
<langsyntaxhighlight lang="ocaml"># let cube x = x ** 3. ;;
val cube : float -> float = <fun>
 
Line 945 ⟶ 2,197:
 
# List.map2 (fun f inversef -> (compose inversef f) 0.5) funclist funclisti ;;
- : float list = [0.5; 0.499999999999999889; 0.5]</langsyntaxhighlight>
 
=={{header|Octave}}==
<langsyntaxhighlight lang="octave">function r = cube(x)
r = x.^3;
endfunction
Line 963 ⟶ 2,215:
for i = 1:3
disp(compose(f1{i}, f2{i})(.5))
endfor</langsyntaxhighlight>
 
{{Out}}
<pre> 0.50000
0.50000
0.50000</pre>
 
=={{header|Oforth}}==
<syntaxhighlight lang="oforth">: compose(f, g) #[ g perform f perform ] ;
 
[ #cos, #sin, #[ 3 pow ] ] [ #acos, #asin, #[ 3 inv powf ] ] zipWith(#compose)
map(#[ 0.5 swap perform ]) conform(#[ 0.5 == ]) println
</syntaxhighlight>
{{Out}}
<pre>
1
</pre>
 
=={{header|Ol}}==
<syntaxhighlight lang="scheme">
; creation of new function from preexisting functions at run-time
(define (compose f g) (lambda (x) (f (g x))))
 
; storing functions in collection
(define (quad x) (* x x x x))
(define (quad-root x) (sqrt (sqrt x)))
 
(define collection (tuple quad quad-root))
 
; use functions as arguments to other functions
; and use functions as return values of other functions
(define identity (compose (ref collection 2) (ref collection 1)))
(print (identity 11211776))
</syntaxhighlight>
 
=={{header|Oz}}==
This is now also compatible with Oz v 2.0
To be executed in the REPL.
(To be executed in the Oz OPI, by typing ctl+. ctl+b)
 
<langsyntaxhighlight lang="oz">declare
 
fun {Compose F G}
fun {$ X}
{F {G X}}
end
end
 
fun {Cube X} {Number.pow X*X*X 3.0} end
 
fun {CubeRoot X} {Number.pow X 1.0/3.0} end
Line 989 ⟶ 2,274:
{Show {{Compose I F} 0.5}}
end
</syntaxhighlight>
</lang>
This will output the following in the Emulator output window
<syntaxhighlight lang="oz">
0.5
0.5
0.5
</syntaxhighlight>
 
=={{header|PARI/GP}}==
{{works with|PARI/GP|2.4.2 and above}}
<langsyntaxhighlight lang="parigp">compose(f,g)={
x -> f(g(x))
};
Line 1,004 ⟶ 2,295:
print(compose(A[i],B[i])(.5))
)
};</langsyntaxhighlight>
Usage note: In Pari/GP 2.4.3 the vectors can be written as
<langsyntaxhighlight lang="parigp"> A=[sin, cos, x->x^2];
B=[asin, acos, x->sqrt(x)];</langsyntaxhighlight>
 
Output:
<pre>0.5000000000000000000000000000
0.5000000000000000000000000000
0.5000000000000000000000000000</pre>
 
=={{header|Perl}}==
<langsyntaxhighlight lang="perl">use Math::Complex ':trig';
 
sub compose {
Line 1,028 ⟶ 2,324:
print join "\n", map {
compose($flist1[$_], $flist2[$_]) -> (0.5)
} 0..2;</langsyntaxhighlight>
 
=={{header|Perl 6}}==
{{works with|Rakudo|2011.06}}
 
<lang perl6>sub compose (&g, &f) { return { g f $^x } }
 
my $x = *.sin;
my $xi = *.asin;
my $y = *.cos;
my $yi = *.acos;
my $z = * ** 3;
my $zi = * ** (1/3);
my @functions = $x, $y, $z;
my @inverses = $xi, $yi, $zi;
for @functions Z @inverses { say compose($^g, $^f)(.5) }</lang>
Output:
<pre>0.5
Line 1,051 ⟶ 2,330:
0.5</pre>
 
=={{header|Phix}}==
There is not really any direct support for this sort of thing in Phix, but it is all pretty trivial to manage explicitly.<br>
In the following, as it stands, constant m cannot be used the same way as a routine_id, and a standard routine_id cannot be passed to the first argument of call_composite, but tagging ctable entries so that you know exactly what to do with them does not sound difficult to me.
<!--<syntaxhighlight lang="phix">(phixonline)-->
<span style="color: #004080;">sequence</span> <span style="color: #000000;">ctable</span> <span style="color: #0000FF;">=</span> <span style="color: #0000FF;">{}</span>
<span style="color: #008080;">function</span> <span style="color: #000000;">compose</span><span style="color: #0000FF;">(</span><span style="color: #004080;">integer</span> <span style="color: #000000;">f</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">g</span><span style="color: #0000FF;">)</span>
<span style="color: #000000;">ctable</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">append</span><span style="color: #0000FF;">(</span><span style="color: #000000;">ctable</span><span style="color: #0000FF;">,{</span><span style="color: #000000;">f</span><span style="color: #0000FF;">,</span><span style="color: #000000;">g</span><span style="color: #0000FF;">})</span>
<span style="color: #004080;">integer</span> <span style="color: #000000;">cdx</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">length</span><span style="color: #0000FF;">(</span><span style="color: #000000;">ctable</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">return</span> <span style="color: #000000;">cdx</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">function</span>
<span style="color: #008080;">function</span> <span style="color: #000000;">call_composite</span><span style="color: #0000FF;">(</span><span style="color: #004080;">integer</span> <span style="color: #000000;">cdx</span><span style="color: #0000FF;">,</span> <span style="color: #004080;">atom</span> <span style="color: #000000;">x</span><span style="color: #0000FF;">)</span>
<span style="color: #004080;">integer</span> <span style="color: #0000FF;">{</span><span style="color: #000000;">f</span><span style="color: #0000FF;">,</span><span style="color: #000000;">g</span><span style="color: #0000FF;">}</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">ctable</span><span style="color: #0000FF;">[</span><span style="color: #000000;">cdx</span><span style="color: #0000FF;">]</span>
<span style="color: #008080;">return</span> <span style="color: #000000;">f</span><span style="color: #0000FF;">(</span><span style="color: #000000;">g</span><span style="color: #0000FF;">(</span><span style="color: #000000;">x</span><span style="color: #0000FF;">))</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">function</span>
<span style="color: #008080;">function</span> <span style="color: #000000;">plus1</span><span style="color: #0000FF;">(</span><span style="color: #004080;">atom</span> <span style="color: #000000;">x</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">return</span> <span style="color: #000000;">x</span><span style="color: #0000FF;">+</span><span style="color: #000000;">1</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">function</span>
<span style="color: #008080;">function</span> <span style="color: #000000;">halve</span><span style="color: #0000FF;">(</span><span style="color: #004080;">atom</span> <span style="color: #000000;">x</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">return</span> <span style="color: #000000;">x</span><span style="color: #0000FF;">/</span><span style="color: #000000;">2</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">function</span>
<span style="color: #008080;">constant</span> <span style="color: #000000;">m</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">compose</span><span style="color: #0000FF;">(</span><span style="color: #000000;">halve</span><span style="color: #0000FF;">,</span><span style="color: #000000;">plus1</span><span style="color: #0000FF;">)</span>
<span style="color: #0000FF;">?</span><span style="color: #000000;">call_composite</span><span style="color: #0000FF;">(</span><span style="color: #000000;">m</span><span style="color: #0000FF;">,</span><span style="color: #000000;">1</span><span style="color: #0000FF;">)</span> <span style="color: #000080;font-style:italic;">-- displays 1</span>
<span style="color: #0000FF;">?</span><span style="color: #000000;">call_composite</span><span style="color: #0000FF;">(</span><span style="color: #000000;">m</span><span style="color: #0000FF;">,</span><span style="color: #000000;">4</span><span style="color: #0000FF;">)</span> <span style="color: #000080;font-style:italic;">-- displays 2.5</span>
<!--</syntaxhighlight>-->
 
=={{header|PHP}}==
 
{{trans|JavaScript}}
Non-anonymous functions can only be passed around by name, but the syntax for calling them is identical in both cases. Object or class methods require a different syntax involving array pseudo-types and <tt>call_user_func</tt>. So PHP could be said to have ''some'' first class functionality.
 
{{works with|PHP|5.3+}}
 
Non-anonymous functions can only be passed around by name, but the syntax for calling them is identical in both cases. Object or class methods require a different syntax involving array pseudo-types and <tt>call_user_func</tt>. So PHP could be said to have ''some'' first class functionality.
<lang php>$compose = function ($f, $g) {
 
<syntaxhighlight lang="php">$compose = function ($f, $g) {
return function ($x) use ($f, $g) {
return $f($g($x));
Line 1,070 ⟶ 2,380:
$f = $compose($inv[$i], $fn[$i]);
echo $f(0.5), PHP_EOL;
}</langsyntaxhighlight>
 
Output:
Line 1,079 ⟶ 2,389:
 
=={{header|PicoLisp}}==
<langsyntaxhighlight PicoLisplang="picolisp">(load "@lib/math.l")
 
(de compose (F G)
Line 1,095 ⟶ 2,405:
(prinl (format ((compose Inv Fun) 0.5) *Scl)) )
'(sin cos cube)
'(asin acos cubeRoot) )</langsyntaxhighlight>
Output:
<pre>0.500001
0.499999
0.500000</pre>
 
=={{header|PostScript}}==
 
<syntaxhighlight lang="ps">
% PostScript has 'sin' and 'cos', but not these
/asin { dup dup 1. add exch 1. exch sub mul sqrt atan } def
/acos { dup dup 1. add exch 1. exch sub mul sqrt exch atan } def
 
/cube { 3 exp } def
/cuberoot { 1. 3. div exp } def
 
/compose { % f g -> { g f }
[ 3 1 roll exch
% procedures are not executed when encountered directly
% insert an 'exec' after procedures, but not after operators
1 index type /operatortype ne { /exec cvx exch } if
dup type /operatortype ne { /exec cvx } if
] cvx
} def
 
/funcs [ /sin load /cos load /cube load ] def
/ifuncs [ /asin load /acos load /cuberoot load ] def
 
0 1 funcs length 1 sub { /i exch def
ifuncs i get funcs i get compose
.5 exch exec ==
} for
</syntaxhighlight>
 
=={{header|Prolog}}==
Works with SWI-Prolog and module lambda, written by <b>Ulrich Neumerkel</b> found here: http://www.complang.tuwien.ac.at/ulrich/Prolog-inedit/lambda.pl
 
<langsyntaxhighlight Prologlang="prolog">:- use_module(library(lambda)).
 
 
Line 1,128 ⟶ 2,466:
% we display the results
maplist(writeln, R).
</syntaxhighlight>
</lang>
Output :
<pre> ?- first_class.
Line 1,139 ⟶ 2,477:
=={{header|Python}}==
 
<langsyntaxhighlight lang="python">>>> # Some built in functions and their inverses
>>> from math import sin, cos, acos, asin
>>> # Add a user defined function and its inverse
Line 1,153 ⟶ 2,491:
>>> [compose(inversef, f)(.5) for f, inversef in zip(funclist, funclisti)]
[0.5, 0.4999999999999999, 0.5]
>>></langsyntaxhighlight>
 
 
Or, equivalently:
{{Works with|Python|3.7}}
<syntaxhighlight lang="python">'''First-class functions'''
 
from math import (acos, cos, asin, sin)
from inspect import signature
 
 
# main :: IO ()
def main():
'''Composition of several functions.'''
 
pwr = flip(curry(pow))
 
fs = [sin, cos, pwr(3.0)]
ifs = [asin, acos, pwr(1 / 3.0)]
 
print([
f(0.5) for f in
zipWith(compose)(fs)(ifs)
])
 
 
# GENERIC FUNCTIONS ------------------------------
 
 
# compose (<<<) :: (b -> c) -> (a -> b) -> a -> c
def compose(g):
'''Right to left function composition.'''
return lambda f: lambda x: g(f(x))
 
 
# curry :: ((a, b) -> c) -> a -> b -> c
def curry(f):
'''A curried function derived
from an uncurried function.'''
return lambda a: lambda b: f(a, b)
 
 
# flip :: (a -> b -> c) -> b -> a -> c
def flip(f):
'''The (curried or uncurried) function f with its
two arguments reversed.'''
if 1 < len(signature(f).parameters):
return lambda a, b: f(b, a)
else:
return lambda a: lambda b: f(b)(a)
 
 
# zipWith :: (a -> b -> c) -> [a] -> [b] -> [c]
def zipWith(f):
'''A list constructed by zipping with a
custom function, rather than with the
default tuple constructor.'''
return lambda xs: lambda ys: [
f(a)(b) for (a, b) in zip(xs, ys)
]
 
 
if __name__ == '__main__':
main()</syntaxhighlight>
{{Out}}
<pre>[0.49999999999999994, 0.5000000000000001, 0.5000000000000001]</pre>
 
=={{header|Quackery}}==
 
Preamble. Quackery has first class functions, but it doesn't have floating point numbers.
 
However, as it is implemented in Python, we can drop down into Python for that functionality, and represent floating point numbers as strings in Quackery. This code implements that, with a light sprinkle of syntactic sugar for the compiler so we can use <code>f 0.5</code> rather than <code>$ "0.5"</code> to represent the floating point number <code>0.5</code>
 
<syntaxhighlight lang="Quackery"> [ $ \
try:
float(string_from_stack())
except:
to_stack(False)
else:
to_stack(True)
\ python ] is isfloat ( $ --> b )
 
[ nextword
dup isfloat not if
[ $ '"f" needs to be followed by a number.'
message put bail ]
' [ ' ] swap nested join
nested swap dip join ] builds f ( [ $ --> [ $ )
 
[ $ \
import math
a = string_from_stack()
a = str(math.sin(float(a)))
string_to_stack(a) \ python ] is sin ( $ --> $ )
 
[ $ \
import math
a = string_from_stack()
a = str(math.asin(float(a)))
string_to_stack(a) \ python ] is asin ( $ --> $ )
 
[ $ \
import math
a = string_from_stack()
a = str(math.cos(float(a)))
string_to_stack(a) \ python ] is cos ( $ --> $ )
 
[ $ \
import math
a = string_from_stack()
a = str(math.acos(float(a)))
string_to_stack(a) \ python ] is acos ( $ --> $ )
 
[ $ \
a = string_from_stack()
b = string_from_stack()
c = str(float(b) * float(a))
string_to_stack(c) \ python ] is f* ( $ $ --> $ )
 
[ $ \
a = string_from_stack()
b = string_from_stack()
c = str(float(b) / float(a))
string_to_stack(c) \ python ] is f/ ( $ $ --> $ )
 
[ $ \
a = string_from_stack()
b = string_from_stack()
c = str(float(b) ** float(a))
string_to_stack(c) \ python ] is f** ( $ $ --> $ )</syntaxhighlight>
 
…and now the task…
 
<syntaxhighlight lang="Quackery"> [ dup dup f* f* ] is cubed ( $ --> $ )
 
[ f 1 f 3 f/ f** ] is cuberoot ( $ --> $ )
 
[ table sin cos cubed ] is A ( n --> [ )
 
[ table asin acos cuberoot ] is B ( n --> [ )
 
[ dip nested nested join ] is compose ( x x --> [ )
 
[ dup dip A B compose do ] is ->A->B-> ( f n --> f )
 
' [ f 0.5 f 1.234567 ]
witheach
[ do 3 times
[ dup echo$
say " -> "
i^ A echo
say " -> "
i^ B echo
say " -> "
dup i^ ->A->B-> echo$
cr ]
drop cr ]</syntaxhighlight>
 
{{out}}
 
<pre>0.5 -> sin -> asin -> 0.5
0.5 -> cos -> acos -> 0.4999999999999999
0.5 -> cubed -> cuberoot -> 0.5
 
1.234567 -> sin -> asin -> 1.234567
1.234567 -> cos -> acos -> 1.234567
1.234567 -> cubed -> cuberoot -> 1.234567</pre>
 
=={{header|R}}==
<langsyntaxhighlight Rlang="r">cube <- function(x) x^3
croot <- function(x) x^(1/3)
compose <- function(f, g) function(x){f(g(x))}
Line 1,165 ⟶ 2,669:
for(i in 1:3) {
print(compose(f1[[i]], f2[[i]])(.5))
}</langsyntaxhighlight>
 
{{Out}}
<pre>[1] 0.5
[1] 0.5
[1] 0.5</pre>
 
Alternatively:
 
<syntaxhighlight lang="r">sapply(mapply(compose,f1,f2),do.call,list(.5))</syntaxhighlight>
<lang R>
 
sapply(mapply(compose,f1,f2),do.call,list(.5))
{{Out}}
</lang>
<pre>[1] 0.5 0.5 0.5</pre>
 
=={{header|Racket}}==
<syntaxhighlight lang="racket">#lang racket
 
(define (compose f g) (λ (x) (f (g x))))
(define (cube x) (expt x 3))
(define (cube-root x) (expt x (/ 1 3)))
(define funlist (list sin cos cube))
(define ifunlist (list asin acos cube-root))
(for ([f funlist] [i ifunlist])
(displayln ((compose i f) 0.5)))</syntaxhighlight>
 
{{out}}
<pre>
0.5
0.4999999999999999
0.5
</pre>
 
=={{header|Raku}}==
(formerly Perl 6)
Here we use the <tt>Z</tt> ("zipwith") metaoperator to zip the 𝐴 and 𝐵 lists with builtin composition operator, <tt>∘</tt> (or just <tt>o</tt>). The <tt>.()</tt> construct invokes the function contained in the <tt>$_</tt> (current topic) variable.
 
<syntaxhighlight lang="raku" line>my \𝐴 = &sin, &cos, { $_ ** <3/1> }
my \𝐵 = &asin, &acos, { $_ ** <1/3> }
 
say .(.5) for 𝐴 Z∘ 𝐵</syntaxhighlight>
 
{{output}}
<pre>0.5
0.4999999999999999
0.5000000000000001
</pre>
 
It is not clear why we don't get exactly 0.5, here.
 
Operators, both builtin and user-defined, are first class too.
 
<syntaxhighlight lang="raku" line>my @a = 1,2,3;
my @op = &infix:<+>, &infix:<->, &infix:<*>;
for flat @a Z @op -> $v, &op { say 42.&op($v) }</syntaxhighlight>
 
{{output}}
<pre>43
40
126</pre>
 
=={{header|REBOL}}==
{{incomplete|REBOL|Fails to demonstrate that the result of applying the composition of each function in A and its inverse in B to a value, is the original value}}
<lang REBOL>REBOL [
<syntaxhighlight lang="rebol">REBOL [
Title: "First Class Functions"
Author: oofoe
Date: 2009-12-05
URL: http://rosettacode.org/wiki/First-class_functions
]
Line 1,204 ⟶ 2,760:
 
A: next A B: next B ; Advance to next pair.
]</langsyntaxhighlight>
 
=={{header|REXX}}==
The REXX language doesn't have any trigonometric functions built-in, nor the square root function, so several higher-math functions are included herein as RYO functions.
 
The only REXX functions that have an inverse are:
::::* &nbsp; d2x &nbsp; ◄──► &nbsp; x2d
::::* &nbsp; d2c &nbsp; ◄──► &nbsp; c2d
::::* &nbsp; c2x &nbsp; ◄──► &nbsp; x2c
These six functions (generally) only support non-negative integers, so a special test in the program below only
<br>supplies appropriate integers when testing the first function listed in the &nbsp; '''A''' &nbsp; collection.
<syntaxhighlight lang="rexx">/*REXX program demonstrates first─class functions (as a list of the names of functions).*/
A = 'd2x square sin cos' /*a list of functions to demonstrate.*/
B = 'x2d sqrt Asin Acos' /*the inverse functions of above list. */
w=digits() /*W: width of numbers to be displayed.*/
/* [↓] collection of A & B functions*/
do j=1 for words(A); say; say /*step through the list; 2 blank lines*/
say center("number",w) center('function', 3*w+1) center("inverse", 4*w)
say copies("─" ,w) copies("─", 3*w+1) copies("─", 4*w)
if j<2 then call test j, 20 60 500 /*functions X2D, D2X: integers only. */
else call test j, 0 0.5 1 2 /*all other functions: floating point.*/
end /*j*/
exit /*stick a fork in it, we're all done. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
Acos: procedure; parse arg x; if x<-1|x>1 then call AcosErr; return .5*pi()-Asin(x)
r2r: return arg(1) // (pi()*2) /*normalize radians ──► 1 unit circle*/
square: return arg(1) ** 2
pi: pi=3.14159265358979323846264338327950288419716939937510582097494459230; return pi
tellErr: say; say '*** error! ***'; say; say arg(1); say; exit 13
tanErr: call tellErr 'tan(' || x") causes division by zero, X=" || x
AsinErr: call tellErr 'Asin(x), X must be in the range of -1 ──► +1, X=' || x
AcosErr: call tellErr 'Acos(x), X must be in the range of -1 ──► +1, X=' || x
/*──────────────────────────────────────────────────────────────────────────────────────*/
Asin: procedure; parse arg x; if x<-1 | x>1 then call AsinErr; s=x*x
if abs(x)>=.7 then return sign(x)*Acos(sqrt(1-s)); z=x; o=x; p=z
do j=2 by 2; o=o*s*(j-1)/j; z=z+o/(j+1); if z=p then leave; p=z; end
return z
/*──────────────────────────────────────────────────────────────────────────────────────*/
cos: procedure; parse arg x; x=r2r(x); a=abs(x); Hpi=pi*.5
numeric fuzz min(6,digits()-3); if a=pi() then return -1
if a=Hpi | a=Hpi*3 then return 0 ; if a=pi()/3 then return .5
if a=pi()*2/3 then return -.5; return .sinCos(1,1,-1)
/*──────────────────────────────────────────────────────────────────────────────────────*/
sin: procedure; parse arg x; x=r2r(x); numeric fuzz min(5, digits()-3)
if abs(x)=pi() then return 0; return .sinCos(x,x,1)
/*──────────────────────────────────────────────────────────────────────────────────────*/
.sinCos: parse arg z 1 p,_,i; x=x*x
do k=2 by 2; _=-_*x/(k*(k+i)); z=z+_; if z=p then leave; p=z; end; return z
/*──────────────────────────────────────────────────────────────────────────────────────*/
invoke: parse arg fn,v; q='"'; if datatype(v,"N") then q=
_=fn || '('q || v || q")"; interpret 'func='_; return func
/*──────────────────────────────────────────────────────────────────────────────────────*/
sqrt: procedure; parse arg x; if x=0 then return 0; d=digits(); m.=9; numeric form
numeric digits; parse value format(x,2,1,,0) 'E0' with g 'E' _ .; g=g*.5'e'_%2
h=d+6; do j=0 while h>9; m.j=h; h=h%2+1; end /*j*/
do k=j+5 to 0 by -1; numeric digits m.k; g=(g+x/g)*.5; end /*k*/
numeric digits d; return g/1
/*──────────────────────────────────────────────────────────────────────────────────────*/
test: procedure expose A B w; parse arg fu,xList; d=digits() /*xList: numbers. */
do k=1 for words(xList); x=word(xList, k)
numeric digits d+5 /*higher precision.*/
fun=word(A, fu); funV=invoke(fun, x) ; fun@=_
inv=word(B, fu); invV=invoke(inv, funV); inv@=_
numeric digits d /*restore precision*/
if datatype(funV, 'N') then funV=funV/1 /*round to digits()*/
if datatype(invV, 'N') then invV=invV/1 /*round to digits()*/
say center(x, w) right(fun@, 2*w)'='left(left('', funV>=0)funV, w),
right(inv@, 3*w)'='left(left('', invV>=0)invV, w)
end /*k*/
return</syntaxhighlight>
'''output'''
<pre>
number function inverse
───────── ──────────────────────────── ────────────────────────────────────
20 d2x(20)= 14 x2d(14)= 20
60 d2x(60)= 3C x2d("3C")= 60
500 d2x(500)= 1F4 x2d("1F4")= 500
 
 
number function inverse
───────── ──────────────────────────── ────────────────────────────────────
0 square(0)= 0 sqrt(0)= 0
0.5 square(0.5)= 0.25 sqrt(0.25)= 0.5
1 square(1)= 1 sqrt(1)= 1
2 square(2)= 4 sqrt(4)= 2
 
 
number function inverse
───────── ──────────────────────────── ────────────────────────────────────
0 sin(0)= 0 Asin(0)= 0
0.5 sin(0.5)= 0.479425 Asin(0.47942553860419)= 0.5
1 sin(1)= 0.841470 Asin(0.84147098480862)= 1
2 sin(2)= 0.909297 Asin(0.90929742682567)= 1.141592
 
 
number function inverse
───────── ──────────────────────────── ────────────────────────────────────
0 cos(0)= 1 Acos(1)= 0
0.5 cos(0.5)= 0.877582 Acos(0.87758256188987)= 0.5
1 cos(1)= 0.540302 Acos(0.54030230586810)= 1
2 cos(2)=-0.416146 Acos(-0.41614683650659)= 2
</pre>
The reason why &nbsp; '''Asin[sin(n)]''' &nbsp; may not equal &nbsp; '''n''':
 
Each of the trigonometric functions is periodic in the real part of its argument, running through all its values twice in each interval of &nbsp; <big>2<big><math>\pi</math></big></big>.
 
'''Sine''' and '''cosecant''' &nbsp; begin their period at &nbsp; <big>2<big><math>\pi</math></big>k − <big><math>\pi</math></big>/2</big> &nbsp; (where &nbsp; <big>k</big> &nbsp; is an integer), &nbsp; finish it at &nbsp; <big>2<big><math>\pi</math></big>k + <big><math>\pi</math></big>/2</big>, &nbsp; and then reverse themselves over &nbsp; <big>2<big><math>\pi</math></big>k + <big><math>\pi</math></big>/2</big> &nbsp; ───► &nbsp; <big>2<big><math>\pi</math></big>k + 3<big><math>\pi</math></big>/2</big>.
 
'''Cosine''' &nbsp; and &nbsp; '''secant''' &nbsp; begin their period at &nbsp; <big>2<big><math>\pi</math></big>k</big>, &nbsp; finish it at &nbsp; <big>2<big><math>\pi</math></big>k + <big><math>\pi</math></big></big>, &nbsp; and then reverse themselves over &nbsp; <big>2<big><math>\pi</math></big>k + <big><math>\pi</math></big></big> &nbsp; ───► &nbsp; <big>2<big><math>\pi</math></big>k + 2<big><math>\pi</math></big></big>.
 
'''Tangent''' &nbsp; begins its period at &nbsp; <big>2<big><math>\pi</math></big>k − <big><math>\pi</math></big>/2</big>, &nbsp; &nbsp; finishes it at &nbsp; <big>2<big><math>\pi</math></big>k + <big><math>\pi</math></big>/2</big>, &nbsp; and then repeats it (forward) over <big>2<big><math>\pi</math></big>k + <big><math>\pi</math></big>/2</big> &nbsp; ───► &nbsp; <big>2<big><math>\pi</math></big>k + 3<big><math>\pi</math></big>/2</big>.
 
'''Cotangent''' &nbsp; begins its period at &nbsp; <big>2<big><math>\pi</math></big>k</big>, &nbsp; finishes it at &nbsp; <big>2<big><math>\pi</math></big>k + <big><math>\pi</math></big></big>, &nbsp; and then repeats it (forward) over <big>2<big><math>\pi</math></big>k + <big><math>\pi</math></big></big> &nbsp; ───► &nbsp; <big>2<big><math>\pi</math></big>k + 2<big><math>\pi</math></big></big>.
 
<br>The above text is from the Wikipedia webpage: &nbsp; http://en.wikipedia.org/wiki/Inverse_trigonometric_functions
<br><br>
 
=={{header|Ruby}}==
<syntaxhighlight lang ="ruby">irb(main):001:0> cube = proc{|x| x ** 3}
croot = proc{|x| x ** (1.quo 3)}
=> #<Proc:0x0000020c66b878@(irb):1>
irb(main):002:0> crootcompose = proc {|xf,g| proc {|x| ** (1.quo 3)f[g[x]]}}
funclist = [Math.method(:sin), Math.method(:cos), cube]
=> #<Proc:0x00000201f6a6c8@(irb):2>
invlist = [Math.method(:asin), Math.method(:acos), croot]
irb(main):003:0> compose = proc {|f,g| proc {|x| f[g[x]]}}
 
=> #<Proc:0x00000205e4e768@(irb):3>
puts funclist.zip(invlist).map {|f, invf| compose[invf, f][0.5]}</syntaxhighlight>
irb(main):004:0> funclist = [Math.method(:sin), Math.method(:cos), cube]
 
=> [#<Method: Math.sin>, #<Method: Math.cos>, #<Proc:0x0000020c66b878@(irb):1>]
{{out}}
irb(main):005:0> invlist = [Math.method(:asin), Math.method(:acos), croot]
<pre>
=> [#<Method: Math.asin>, #<Method: Math.acos>, #<Proc:0x00000201f6a6c8@(irb):2>]
0.5
irb(main):006:0> funclist.zip(invlist).map {|f, invf| compose[invf, f][0.5]}
=> [0.5, 0.4999999999999999, 0.5]</lang>
0.5
</pre>
 
=={{header|Rust}}==
This solution uses a feature of Nightly Rust that allows us to return a closure from a function without using the extra indirection of a pointer. Stable Rust can also accomplish this challenge -- the only difference being that compose would return a <code>Box<Fn(T) -> V></code> which would result in an extra heap allocation.
 
<syntaxhighlight lang="rust">#![feature(conservative_impl_trait)]
fn main() {
let cube = |x: f64| x.powi(3);
let cube_root = |x: f64| x.powf(1.0 / 3.0);
 
let flist : [&Fn(f64) -> f64; 3] = [&cube , &f64::sin , &f64::cos ];
let invlist: [&Fn(f64) -> f64; 3] = [&cube_root, &f64::asin, &f64::acos];
 
let result = flist.iter()
.zip(&invlist)
.map(|(f,i)| compose(f,i)(0.5))
.collect::<Vec<_>>();
 
println!("{:?}", result);
 
}
 
fn compose<'a, F, G, T, U, V>(f: F, g: G) -> impl 'a + Fn(T) -> V
where F: 'a + Fn(T) -> U,
G: 'a + Fn(U) -> V,
{
move |x| g(f(x))
 
}</syntaxhighlight>
 
=={{header|Scala}}==
<syntaxhighlight lang="scala">import math._
<lang scala>
import math._
 
// functions as values
Line 1,239 ⟶ 2,939:
 
// output results of applying the functions
comp foreach {f => printlnprint(f(0.5) + " ")}</syntaxhighlight>
Output:
</lang>
<pre>0.5 0.4999999999999999 0.5000000000000001</pre>
<!--
Here's how you could add a composition operator to make that syntax prettier:
 
<langsyntaxhighlight lang="scala">class SweetFunction[B,C](f: B => C) {
def o[A](g: A => B) = (x: A) => f(g(x))
}
Line 1,249 ⟶ 2,951:
 
// now functions can be composed thus
println((cube o cube o cuberoot)(0.5)) </langsyntaxhighlight>-->
 
=={{header|Scheme}}==
<langsyntaxhighlight lang="scheme">(define (compose f g) (lambda (x) (f (g x))))
(define (cube x) (expt x 3))
(define (cube-root x) (expt x (/ 1 3)))
Line 1,267 ⟶ 2,969:
(go (cdr f) (cdr g)))))
 
(go function inverse)</langsyntaxhighlight>
Output:
0.5
Line 1,273 ⟶ 2,975:
0.5
 
=={{header|SlateSidef}}==
{{trans|Perl}}
<syntaxhighlight lang="ruby">func compose(f,g) {
func (*args) {
f(g(args...))
}
}
 
var cube = func(a) { a.pow(3) }
var croot = func(a) { a.root(3) }
 
var flist1 = [Num.method(:sin), Num.method(:cos), cube]
var flist2 = [Num.method(:asin), Num.method(:acos), croot]
 
for a,b (flist1 ~Z flist2) {
say compose(a, b)(0.5)
}</syntaxhighlight>
{{out}}
<pre>
0.5
0.5
0.5
</pre>
 
=={{header|Slate}}==
{{incomplete|Slate|Fails to demonstrate that the result of applying the composition of each function in A and its inverse in B to a value, is the original value}}
Compose is already defined in slate as (note the examples in the comment):
 
<langsyntaxhighlight lang="slate">m@(Method traits) ** n@(Method traits)
"Answers a new Method whose effect is that of calling the first method
on the results of the second method applied to whatever arguments are passed.
Line 1,298 ⟶ 3,024:
].
 
#**`er asMethod: #compose: on: {Method traits. Method traits}.</langsyntaxhighlight>
used as:
<langsyntaxhighlight lang="slate">n@(Number traits) cubed [n raisedTo: 3].
n@(Number traits) cubeRoot [n raisedTo: 1 / 3].
define: #forward -> {#cos `er. #sin `er. #cube `er}.
Line 1,306 ⟶ 3,032:
 
define: #composedMethods -> (forward with: reverse collect: #compose: `er).
composedMethods do: [| :m | inform: (m applyWith: 0.5)].</langsyntaxhighlight>
 
=={{header|Smalltalk}}==
{{works with|GNU Smalltalk}}
<langsyntaxhighlight lang="smalltalk">|forward reverse composer compounds|
"commodities"
Number extend [
Line 1,332 ⟶ 3,058:
].
 
compounds do: [ :r | (r value: 0.5) displayNl ].</langsyntaxhighlight>
 
Output:
Line 1,341 ⟶ 3,067:
 
=={{header|Standard ML}}==
<langsyntaxhighlight lang="sml">- fun cube x = Math.pow(x, 3.0);
val cube = fn : real -> real
- fun croot x = Math.pow(x, 1.0 / 3.0);
Line 1,353 ⟶ 3,079:
val funclisti = [fn,fn,fn] : (real -> real) list
- ListPair.map (fn (f, inversef) => (compose (inversef, f)) 0.5) (funclist, funclisti);
val it = [0.5,0.5,0.500000000001] : real list</langsyntaxhighlight>
 
=={{header|Stata}}==
 
In Mata it's not possible to get the address of a builtin function, so here we define user functions.
 
<syntaxhighlight lang="stata">function _sin(x) {
return(sin(x))
}
 
function _asin(x) {
return(asin(x))
}
 
function _cos(x) {
return(cos(x))
}
 
function _acos(x) {
return(acos(x))
}
 
function cube(x) {
return(x*x*x)
}
 
function cuberoot(x) {
return(sign(x)*abs(x)^(1/3))
}
 
function compose(f,g,x) {
return((*f)((*g)(x)))
}
 
a=&_sin(),&_cos(),&cube()
b=&_asin(),&_acos(),&cuberoot()
 
for(i=1;i<=length(a);i++) {
printf("%10.5f\n",compose(a[i],b[i],0.5))
}</syntaxhighlight>
 
=={{header|SuperCollider}}==
<syntaxhighlight lang="supercollider">
a = [sin(_), cos(_), { |x| x ** 3 }];
b = [asin(_), acos(_), { |x| x ** (1/3) }];
c = a.collect { |x, i| x <> b[i] };
c.every { |x| x.(0.5) - 0.5 < 0.00001 }
</syntaxhighlight>
 
=={{header|Swift}}==
{{works with|Swift|1.2+}}
<syntaxhighlight lang="swift">import Darwin
func compose<A,B,C>(f: (B) -> C, g: (A) -> B) -> (A) -> C {
return { f(g($0)) }
}
let funclist = [ { (x: Double) in sin(x) }, { (x: Double) in cos(x) }, { (x: Double) in pow(x, 3) } ]
let funclisti = [ { (x: Double) in asin(x) }, { (x: Double) in acos(x) }, { (x: Double) in cbrt(x) } ]
println(map(zip(funclist, funclisti)) { f, inversef in compose(f, inversef)(0.5) })</syntaxhighlight>
{{out}}
<pre>
[0.5, 0.5, 0.5]
</pre>
 
=={{header|Tcl}}==
The following is a transcript of an interactive session:<br>
{{works with|tclsh|8.5}}
<langsyntaxhighlight Tcllang="tcl">% namespace path tcl::mathfunc ;# to import functions like abs() etc.
% proc cube x {expr {$x**3}}
% proc croot x {expr {$x**(1/3.)}}
Line 1,374 ⟶ 3,161:
0.8372297964617733
% {*}$backward [{*}$forward 0.5]
0.5000000000000017</langsyntaxhighlight>
Obviously, the ([[C]]) library implementation of some of the trigonometric functions (on which Tcl depends for its implementation) on the platform used for testing is losing a little bit of accuracy somewhere.
 
Line 1,385 ⟶ 3,172:
(Note: The names of the inverse functions may not display as intended unless you have the “TI Uni” font.)
 
<langsyntaxhighlight lang="ti89b">Prgm
Local funs,invs,composed,x,i
 
Line 1,401 ⟶ 3,188:
 
DelVar rc_cube,rc_curt © Clean up our globals
EndPrgm</langsyntaxhighlight>
 
=={{header|TXR}}==
 
{{trans|Racket}}
 
Translation notes: we use <code>op</code> to create cube and inverse cube anonymously and succinctly.
<code>chain</code> composes a variable number of functions, but unlike <code>compose</code>, from left to right, not right to left.
 
<syntaxhighlight lang="txrlisp">(defvar funlist [list sin
cos
(op expt @1 3)])
 
(defvar invlist [list asin
acos
(op expt @1 (/ 1 3))])
 
(each ((f funlist) (i invlist))
(prinl [(chain f i) 0.5]))</syntaxhighlight>
 
{{out}}
 
<pre>0.5
0.5
0.5
0.5</pre>
 
=={{header|Ursala}}==
Line 1,408 ⟶ 3,220:
functions into a single function returning a list, and apply it to the
argument 0.5.
<langsyntaxhighlight Ursalalang="ursala">#import std
#import flo
 
Line 1,416 ⟶ 3,228:
#cast %eL
 
main = (gang (+)*p\functions inverses) 0.5</langsyntaxhighlight>
In more detail,
* <code>(+)*p\functions inverses</code> evaluates to <code>(+)*p(inverses,functions)</code> by definition of the reverse binary to unary combinator (<code>\</code>)
Line 1,426 ⟶ 3,238:
output:
<pre><5.000000e-01,5.000000e-01,5.000000e-01></pre>
 
=={{header|Wren}}==
In Wren, there is a distinction between functions and methods. Essentially, the former are independent objects which can do all the things required of 'first class functions' and the latter are subroutines which are tied to a particular class. As sin, cos etc. are instance methods of the Num class, we need to wrap them in functions to complete this task.
<syntaxhighlight lang="wren">var compose = Fn.new { |f, g| Fn.new { |x| f.call(g.call(x)) } }
 
var A = [
Fn.new { |x| x.sin },
Fn.new { |x| x.cos },
Fn.new { |x| x * x * x }
]
 
var B = [
Fn.new { |x| x.asin },
Fn.new { |x| x.acos },
Fn.new { |x| x.pow(1/3) }
]
 
var x = 0.5
for (i in 0..2) {
System.print(compose.call(A[i], B[i]).call(x))
}</syntaxhighlight>
 
{{out}}
<pre>
0.5
0.5
0.5
</pre>
 
=={{header|XBS}}==
<syntaxhighlight lang="xbs">func cube(x:number):number{
send x^3;
}
func cuberoot(x:number):number{
send x^(1/3);
}
 
func compose(f:function,g:function):function{
send func(n:number){
send f(g(n));
}
}
 
const a:[function]=[math.sin,math.cos,cube];
const b:[function]=[math.asin,math.acos,cuberoot];
 
each a as k,v{
log(compose(v,b[k])(0.5))
}</syntaxhighlight>
{{out}}
<pre>
0.5
0.4999999999999999
0.5000000000000001
</pre>
 
=={{header|zkl}}==
In zkl, methods bind their instance so something like x.sin is the sine method bound to x (whatever real number x is). eg var a=(30.0).toRad().sin; is a method and a() will always return 0.5 (ie basically a const in this case). Which means you can't just use the word "sin", it has to be used in conjunction with an instance.
<syntaxhighlight lang="zkl">var a=T(fcn(x){ x.toRad().sin() }, fcn(x){ x.toRad().cos() }, fcn(x){ x*x*x} );
var b=T(fcn(x){ x.asin().toDeg() }, fcn(x){ x.acos().toDeg() }, fcn(x){ x.pow(1.0/3) });
 
var H=Utils.Helpers;
var ab=b.zipWith(H.fcomp,a); //-->list of deferred calculations
ab.run(True,5.0); //-->L(5.0,5.0,5.0)
 
a.run(True,5.0) //-->L(0.0871557,0.996195,125)</syntaxhighlight>
fcomp is the function composition function, fcomp(b,a) returns the function (x)-->b(a(x)). List.run(True,x) is inverse of List.apply/map, it returns a list of list[i](x). The True is to return the result, False is just do it for the side effects.
 
{{Omit From|AWK}}
{{Omit From|Fortran}}
{{omit from|gnuplot}}
{{omit from|LaTeX}}
{{omit from|Make}}
{{Omit From|Pascal}}
{{omit from|PlainTeX}}
{{omit from|PureBasic}}
{{omit from|Scratch}}
{{omit from|TI-83 BASIC|Cannot define functions.}}
 
[[Category:Functions and subroutines]]
Anonymous user