Function composition: Difference between revisions
(36 intermediate revisions by 20 users not shown) | |||
Line 20: | Line 20: | ||
{{trans|Python}} |
{{trans|Python}} |
||
< |
<syntaxhighlight lang="11l">V compose = (f, g) -> (x -> @f(@g(x))) |
||
V sin_asin = compose(x -> sin(x), x -> asin(x)) |
V sin_asin = compose(x -> sin(x), x -> asin(x)) |
||
print(sin_asin(0.5))</ |
print(sin_asin(0.5))</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 31: | Line 31: | ||
=={{header|ActionScript}}== |
=={{header|ActionScript}}== |
||
ActionScript supports closures, making function composition very straightforward. |
ActionScript supports closures, making function composition very straightforward. |
||
< |
<syntaxhighlight lang="actionscript">function compose(f:Function, g:Function):Function { |
||
return function(x:Object) {return f(g(x));}; |
return function(x:Object) {return f(g(x));}; |
||
} |
} |
||
function test() { |
function test() { |
||
trace(compose(Math.atan, Math.tan)(0.5)); |
trace(compose(Math.atan, Math.tan)(0.5)); |
||
}</ |
}</syntaxhighlight> |
||
=={{header|Ada}}== |
=={{header|Ada}}== |
||
The interface of a generic functions package. The package can be instantiated with any type that has value semantics. Functions are composed using the operation '*'. The same operation applied to an argument evaluates it there: f * x. Functions can be composed with pointers to [[Ada]] functions. (In [[Ada]] functions are not first-class): |
The interface of a generic functions package. The package can be instantiated with any type that has value semantics. Functions are composed using the operation '*'. The same operation applied to an argument evaluates it there: f * x. Functions can be composed with pointers to [[Ada]] functions. (In [[Ada]] functions are not first-class): |
||
< |
<syntaxhighlight lang="ada">generic |
||
type Argument is private; |
type Argument is private; |
||
package Functions is |
package Functions is |
||
Line 52: | Line 52: | ||
private |
private |
||
type Func is array (Positive range <>) of Primitive_Operation; |
type Func is array (Positive range <>) of Primitive_Operation; |
||
end Functions;</ |
end Functions;</syntaxhighlight> |
||
Here is an implementation; |
Here is an implementation; |
||
< |
<syntaxhighlight lang="ada">package body Functions is |
||
function "*" (Left : Func; Right : Argument) return Argument is |
function "*" (Left : Func; Right : Argument) return Argument is |
||
Result : Argument := Right; |
Result : Argument := Right; |
||
Line 78: | Line 78: | ||
return (Left, Right); |
return (Left, Right); |
||
end "*"; |
end "*"; |
||
end Functions;</ |
end Functions;</syntaxhighlight> |
||
The following is an example of use: |
The following is an example of use: |
||
< |
<syntaxhighlight lang="ada">with Ada.Numerics.Elementary_Functions; use Ada.Numerics.Elementary_Functions; |
||
with Ada.Text_IO; use Ada.Text_IO; |
with Ada.Text_IO; use Ada.Text_IO; |
||
with Functions; |
with Functions; |
||
Line 91: | Line 91: | ||
begin |
begin |
||
Put_Line (Float'Image (Sin_Arcsin * 0.5)); |
Put_Line (Float'Image (Sin_Arcsin * 0.5)); |
||
end Test_Compose;</ |
end Test_Compose;</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 98: | Line 98: | ||
=={{header|Agda}}== |
=={{header|Agda}}== |
||
< |
<syntaxhighlight lang="agda">compose : ∀ {a b c} {A : Set a} {B : Set b} {C : Set c} |
||
→ (B → C) |
→ (B → C) |
||
→ (A → B) |
→ (A → B) |
||
→ A → C |
→ A → C |
||
compose f g x = f (g x)</ |
compose f g x = f (g x)</syntaxhighlight> |
||
=={{header|Aikido}}== |
=={{header|Aikido}}== |
||
< |
<syntaxhighlight lang="aikido"> |
||
import math |
import math |
||
Line 115: | Line 115: | ||
println (func(0.5)) // 0.5 |
println (func(0.5)) // 0.5 |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|Aime}}== |
=={{header|Aime}}== |
||
< |
<syntaxhighlight lang="aime">compose_i(,,) |
||
{ |
{ |
||
($0)(($1)($2)); |
($0)(($1)($2)); |
||
Line 143: | Line 143: | ||
0; |
0; |
||
}</ |
}</syntaxhighlight> |
||
{{Out}} |
{{Out}} |
||
<pre>6400</pre> |
<pre>6400</pre> |
||
Line 154: | Line 154: | ||
violates standard '''ALGOL 68''''s scoping rules. [[ALGOL 68G]] warns about this during |
violates standard '''ALGOL 68''''s scoping rules. [[ALGOL 68G]] warns about this during |
||
parsing, and then rejects during runtime. |
parsing, and then rejects during runtime. |
||
< |
<syntaxhighlight lang="algol68">MODE F = PROC(REAL)REAL; # ALGOL 68 is strong typed # |
||
# As a procedure for real to real functions # |
# As a procedure for real to real functions # |
||
Line 163: | Line 163: | ||
# Example use: # |
# Example use: # |
||
F sin arc sin = compose(sin, arc sin); |
F sin arc sin = compose(sin, arc sin); |
||
print((sin arc sin(0.5), (sin O arc sin)(0.5), new line))</ |
print((sin arc sin(0.5), (sin O arc sin)(0.5), new line))</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 172: | Line 172: | ||
{{works with|ALGOL 68|Standard - Jan 1975 Boston SC allowed Partial Parametrization. }} |
{{works with|ALGOL 68|Standard - Jan 1975 Boston SC allowed Partial Parametrization. }} |
||
{{works with|ALGOL 68G|Any - tested with release mk15-0.8b.fc9.i386}} |
{{works with|ALGOL 68G|Any - tested with release mk15-0.8b.fc9.i386}} |
||
< |
<syntaxhighlight lang="algol68">MODE F = PROC(REAL)REAL; # ALGOL 68 is strong typed # |
||
# As a procedure for real to real functions # |
# As a procedure for real to real functions # |
||
Line 182: | Line 182: | ||
# Example use: # |
# Example use: # |
||
F sin arc sin = compose(sin, arc sin); |
F sin arc sin = compose(sin, arc sin); |
||
print((sin arc sin(0.5), (sin O arc sin)(0.5), new line))</ |
print((sin arc sin(0.5), (sin O arc sin)(0.5), new line))</syntaxhighlight> |
||
=={{header|Amazing Hopper}}== |
|||
VERSION 1: |
|||
<syntaxhighlight lang="c"> |
|||
#defn Compose(_FX_,_FY_) _FX_,_FY_ |
|||
main: |
|||
0.5,Compose(sin,arcsin) |
|||
"\n", print |
|||
{0}return |
|||
</syntaxhighlight> |
|||
{{out}} |
|||
<pre> |
|||
$ hopper3 basica/compose1.hop |
|||
0.500000 |
|||
</pre> |
|||
VERSION 2: |
|||
<syntaxhighlight lang="c"> |
|||
#define-a «(_X_) _X_ ) |
|||
#define Compose(_FX_,_FY_) _FC_(_FX_,_FY_, |
|||
#define _FC_(_X_,_Y_,*) *,_X_,_Y_ |
|||
main: |
|||
Compose(sin,arcsin)«( 0.5) |
|||
"\n", print |
|||
{0}return |
|||
</syntaxhighlight> |
|||
{{out}} |
|||
<pre> |
|||
$ hopper3 basica/compose2.hop |
|||
0.500000 |
|||
</pre> |
|||
VERSION 3: |
|||
<syntaxhighlight lang="c"> |
|||
#define «(_X_) _X_ ) |
|||
#define Compose(_FX_,_FY_) _FC_(_FX_,_FY_, |
|||
#define _FC_(_X_,_Y_,*) *,_X_,_Y_ |
|||
main: |
|||
Compose(sin,arcsin)«( 0.5, mul by '2' ) |
|||
"\n", print |
|||
{0}return |
|||
</syntaxhighlight> |
|||
{{out}} |
|||
<pre> |
|||
$ hopper3 basica/compose2.hop |
|||
1.000000 |
|||
</pre> |
|||
<p>The power of macro-substitution, by Hopper!</p> |
|||
=={{header|AntLang}}== |
=={{header|AntLang}}== |
||
< |
<syntaxhighlight lang="antlang">/Apply g to exactly one argument |
||
compose1: {f: x; g: y; {f[g[x]]}} |
compose1: {f: x; g: y; {f[g[x]]}} |
||
/Extra: apply to multiple arguments |
/Extra: apply to multiple arguments |
||
compose: {f: x; g: y; {f[g apply args]}}</ |
compose: {f: x; g: y; {f[g apply args]}}</syntaxhighlight> |
||
=={{header|AppleScript}}== |
=={{header|AppleScript}}== |
||
< |
<syntaxhighlight lang="applescript">-- Compose two functions where each function is |
||
-- a script object with a call(x) handler. |
-- a script object with a call(x) handler. |
||
on compose(f, g) |
on compose(f, g) |
||
Line 214: | Line 267: | ||
compose(sqrt, twice)'s call(32) |
compose(sqrt, twice)'s call(32) |
||
-- Result: 8.0</ |
-- Result: 8.0</syntaxhighlight> |
||
A limitation of AppleScript's handlers (functions), which can be seen in the example above, is that they are not in themselves composable first class objects, and have to be lifted into script objects before they can be composed or passed as arguments. |
A limitation of AppleScript's handlers (functions), which can be seen in the example above, is that they are not in themselves composable first class objects, and have to be lifted into script objects before they can be composed or passed as arguments. |
||
Line 220: | Line 273: | ||
We can generalise this lifting with an '''mReturn''' or '''mInject''' function, which injects a handler into a script for us. This allows use to write higher-order composition and pipelining functions which take a pair (or sequence of) ordinary handlers as arguments, and return a first class script object. (We can also use mReturn to equip AppleScript with '''map''' and '''fold''' functions which take a list and an ordinary handler as arguments). |
We can generalise this lifting with an '''mReturn''' or '''mInject''' function, which injects a handler into a script for us. This allows use to write higher-order composition and pipelining functions which take a pair (or sequence of) ordinary handlers as arguments, and return a first class script object. (We can also use mReturn to equip AppleScript with '''map''' and '''fold''' functions which take a list and an ordinary handler as arguments). |
||
< |
<syntaxhighlight lang="applescript">------------ COMPOSITION OF A LIST OF FUNCTIONS ---------- |
||
-- compose :: [(a -> a)] -> (a -> a) |
-- compose :: [(a -> a)] -> (a -> a) |
||
Line 285: | Line 338: | ||
end script |
end script |
||
end if |
end if |
||
end mReturn</ |
end mReturn</syntaxhighlight> |
||
{{Out}} |
{{Out}} |
||
<pre>1.61803398875</pre> |
<pre>1.61803398875</pre> |
||
=={{header|Applesoft BASIC}}== |
=={{header|Applesoft BASIC}}== |
||
< |
<syntaxhighlight lang="applesoftbasic">10 F$ = "SIN" |
||
20 DEF FN A(P) = ATN(P/SQR(-P*P+1)) |
20 DEF FN A(P) = ATN(P/SQR(-P*P+1)) |
||
30 G$ = "FN A" |
30 G$ = "FN A" |
||
Line 307: | Line 360: | ||
220 PRINT D$"OPEN"FI$M$D$"WRITE"FI$ |
220 PRINT D$"OPEN"FI$M$D$"WRITE"FI$ |
||
230 PRINT "CALL-998:CALL-958:R="E$":CONT" |
230 PRINT "CALL-998:CALL-958:R="E$":CONT" |
||
240 PRINT D$"CLOSE"FI$M$D$"EXEC"FI$:CALL-998:END:RETURN</ |
240 PRINT D$"CLOSE"FI$M$D$"EXEC"FI$:CALL-998:END:RETURN</syntaxhighlight> |
||
=={{header|Argile}}== |
=={{header|Argile}}== |
||
Only works for functions taking real and returning real (double precision, 64 bits) |
Only works for functions taking real and returning real (double precision, 64 bits) |
||
{{works with|Argile|1.0.0}} |
{{works with|Argile|1.0.0}} |
||
< |
<syntaxhighlight lang="argile">use std, math |
||
let my_asin = new Function (.:<any,real x>:. -> real {asin x}) |
let my_asin = new Function (.:<any,real x>:. -> real {asin x}) |
||
Line 354: | Line 407: | ||
f.func = func |
f.func = func |
||
f.data = data |
f.data = data |
||
f</ |
f</syntaxhighlight> |
||
=={{header|Arturo}}== |
=={{header|Arturo}}== |
||
< |
<syntaxhighlight lang="rebol">compose: function [f,g] -> |
||
return function [x].import:[f,g][ |
return function [x].import:[f,g][ |
||
call f @[call g @[x]] |
call f @[call g @[x]] |
||
Line 365: | Line 418: | ||
splitupper: compose 'split 'upper |
splitupper: compose 'split 'upper |
||
print call 'splitupper ["done"]</ |
print call 'splitupper ["done"]</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre>D O N E</pre> |
<pre>D O N E</pre> |
||
=={{header|ATS}}== |
|||
If I may state in greater detail what the task requires, it is this: |
|||
That '''compose''' should return ''a new function'', which will exist independently of '''compose''' once created. A person should never have to call '''compose''' merely to get the result of the composed computation. |
|||
Thus it is probably impossible, for instance, to ''really'' satisfy the requirement in standard C, if the result of composition is to be called like an ordinary function. However, [[#C|the C solution]] shows it is possible, ''if'' the notion of a function is expanded to include structures requiring more than just a plain C function call. Also, there is at least one platform-dependent library for creating a "true" closure in C. |
|||
In ATS we have closures, but of more than one kind. |
|||
<syntaxhighlight lang="ats">(* |
|||
The task: |
|||
Create a function, compose, whose two arguments f and g, are |
|||
both functions with one argument. |
|||
The result of compose is to be a function of one argument, |
|||
(let's call the argument x), which works like applying function |
|||
f to the result of applying function g to x. |
|||
In ATS, we have to choose whether to use non-linear closures |
|||
(cloref) or linear closures (cloptr). In the latter case, we also |
|||
have to choose between closures allocated with malloc (or similar) |
|||
and closures allocated on the stack. |
|||
For simplicity, we will use non-linear closures and assume there is |
|||
a garbage collector, or that the memory allocated for the closures |
|||
can be allowed to leak. (This is often the case in a program that |
|||
does not run continuously.) |
|||
*) |
|||
#include "share/atspre_staload.hats" |
|||
(* The following is actually a *template function*, rather than a |
|||
function proper. It is expanded during template processing. *) |
|||
fn {t1, t2, t3 : t@ype} |
|||
compose (f : t2 -<cloref1> t3, |
|||
g : t1 -<cloref1> t2) : t1 -<cloref1> t3 = |
|||
lam x => f (g (x)) |
|||
implement |
|||
main0 () = |
|||
let |
|||
val one_hundred = 100.0 |
|||
val char_zero = '0' |
|||
val f = (lam y =<cloref1> add_double_int (one_hundred, y)) |
|||
val g = (lam x =<cloref1> char2i x - char2i char_zero) |
|||
val z = compose (f, g) ('5') |
|||
val fg = compose (f, g) |
|||
val w = fg ('7') |
|||
in |
|||
println! (z : double); |
|||
println! (w : double) |
|||
end</syntaxhighlight> |
|||
{{out}} |
|||
<pre>$ patscc -O2 -DATS_MEMALLOC_GCBDW function_composition.dats -lgc && ./a.out |
|||
105.000000 |
|||
107.000000</pre> |
|||
Incidentally, it is possible to instantiate the template function and obtain a true function that does the composition. What the template does for us is give us compile-time type polymorphism. In the following, the template is instantiated as a true function for specific types: |
|||
<syntaxhighlight lang="ats">#include "share/atspre_staload.hats" |
|||
fn {t1, t2, t3 : t@ype} |
|||
compose (f : t2 -<cloref1> t3, |
|||
g : t1 -<cloref1> t2) : t1 -<cloref1> t3 = |
|||
lam x => f (g (x)) |
|||
fn |
|||
compose_char2int2double |
|||
(f : int -<cloref1> double, |
|||
g : char -<cloref1> int) : |
|||
char -<cloref1> double = |
|||
compose<char, int, double> (f, g) |
|||
implement |
|||
main0 () = |
|||
let |
|||
val one_hundred = 100.0 |
|||
val char_zero = '0' |
|||
val f = (lam y =<cloref1> add_double_int (one_hundred, y)) |
|||
val g = (lam x =<cloref1> char2i x - char2i char_zero) |
|||
val z = compose_char2int2double (f, g) ('5') |
|||
val fg = compose_char2int2double (f, g) |
|||
val w = fg ('7') |
|||
in |
|||
println! (z : double); |
|||
println! (w : double) |
|||
end</syntaxhighlight> |
|||
{{out}} |
|||
<pre>$ patscc -O2 -DATS_MEMALLOC_GCBDW function_composition_2.dats -lgc && ./a.out |
|||
105.000000 |
|||
107.000000</pre> |
|||
One could even make the composition procedures themselves be closures: |
|||
<syntaxhighlight lang="ats">#include "share/atspre_staload.hats" |
|||
fn {t1, t2, t3 : t@ype} |
|||
compose (f : t2 -<cloref1> t3, |
|||
g : t1 -<cloref1> t2) :<cloref1> |
|||
t1 -<cloref1> t3 = |
|||
lam x => f (g (x)) |
|||
fn |
|||
compose_char2int2double |
|||
(f : int -<cloref1> double, |
|||
g : char -<cloref1> int) :<cloref1> |
|||
char -<cloref1> double = |
|||
compose<char, int, double> (f, g) |
|||
implement |
|||
main0 () = |
|||
let |
|||
val one_hundred = 100.0 |
|||
val char_zero = '0' |
|||
val f = (lam y =<cloref1> add_double_int (one_hundred, y)) |
|||
val g = (lam x =<cloref1> char2i x - char2i char_zero) |
|||
val z = compose_char2int2double (f, g) ('5') |
|||
val fg = compose_char2int2double (f, g) |
|||
val w = fg ('7') |
|||
in |
|||
println! (z : double); |
|||
println! (w : double) |
|||
end</syntaxhighlight> |
|||
{{out}} |
|||
<pre>$ patscc -O2 -DATS_MEMALLOC_GCBDW function_composition_3.dats -lgc && ./a.out |
|||
105.000000 |
|||
107.000000</pre> |
|||
=={{header|AutoHotkey}}== |
=={{header|AutoHotkey}}== |
||
contributed by Laszlo on the ahk [http://www.autohotkey.com/forum/post-276379.html#276379 forum] |
contributed by Laszlo on the ahk [http://www.autohotkey.com/forum/post-276379.html#276379 forum] |
||
< |
<syntaxhighlight lang="autohotkey">MsgBox % compose("sin","cos",1.5) |
||
compose(f,g,x) { ; function composition |
compose(f,g,x) { ; function composition |
||
Return %f%(%g%(x)) |
Return %f%(%g%(x)) |
||
}</ |
}</syntaxhighlight> |
||
=={{header|BBC BASIC}}== |
=={{header|BBC BASIC}}== |
||
{{works with|BBC BASIC for Windows}} |
{{works with|BBC BASIC for Windows}} |
||
< |
<syntaxhighlight lang="bbcbasic"> REM Create some functions for testing: |
||
DEF FNsqr(a) = SQR(a) |
DEF FNsqr(a) = SQR(a) |
||
DEF FNabs(a) = ABS(a) |
DEF FNabs(a) = ABS(a) |
||
Line 397: | Line 585: | ||
\ CHR$&A4 + "(&" + STR$~(p%+4) + ")(x))" |
\ CHR$&A4 + "(&" + STR$~(p%+4) + ")(x))" |
||
DIM p% LEN(f$) + 4 : $(p%+4) = f$ : !p% = p%+4 |
DIM p% LEN(f$) + 4 : $(p%+4) = f$ : !p% = p%+4 |
||
= p%</ |
= p%</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 404: | Line 592: | ||
=={{header|Bori}}== |
=={{header|Bori}}== |
||
< |
<syntaxhighlight lang="bori">double sin (double v) { return Math.sin(v); } |
||
double asin (double v) { return Math.asin(v); } |
double asin (double v) { return Math.asin(v); } |
||
Var compose (Func f, Func g, double d) { return f(g(d)); } |
Var compose (Func f, Func g, double d) { return f(g(d)); } |
||
Line 412: | Line 600: | ||
double d = compose(sin, asin, 0.5); |
double d = compose(sin, asin, 0.5); |
||
label1.setText(d.toString(9)); |
label1.setText(d.toString(9)); |
||
}</ |
}</syntaxhighlight> |
||
{{out}} on Android phone: |
{{out}} on Android phone: |
||
<lang |
<syntaxhighlight lang="bori">0.500000000</syntaxhighlight> |
||
=={{header|Binary Lambda Calculus}}== |
|||
In lambda calculus, the compose functions happens to coincide with multiplication on Church numerals, namely <code>compose = \f \g \x. f (g x)</code> which in BLC is |
|||
<pre>00 00 00 01 1110 01 110 10</pre> |
|||
=={{header|BQN}}== |
=={{header|BQN}}== |
||
Line 420: | Line 614: | ||
As a 2-modifier: |
As a 2-modifier: |
||
<lang |
<syntaxhighlight lang="bqn">_compose_ ← ∘</syntaxhighlight> |
||
Or: |
Or: |
||
<lang |
<syntaxhighlight lang="bqn">_compose_ ← {𝔽𝔾𝕩}</syntaxhighlight> |
||
As a dyadic function: |
As a dyadic function: |
||
<lang |
<syntaxhighlight lang="bqn">Compose ← {𝕏∘𝕎}</syntaxhighlight> |
||
This is how you can use it: |
This is how you can use it: |
||
Line 443: | Line 637: | ||
Function composition is illustrated with a conversion from Fahrenheit to Celsius in two steps, followed by a conversion of the resulting rational number to a floating point expression. This shows that the returned value from the <code>compose</code> function indeed is a function and can be used as an argument to another call to <code>compose</code>. |
Function composition is illustrated with a conversion from Fahrenheit to Celsius in two steps, followed by a conversion of the resulting rational number to a floating point expression. This shows that the returned value from the <code>compose</code> function indeed is a function and can be used as an argument to another call to <code>compose</code>. |
||
< |
<syntaxhighlight lang="bracmat">( ( compose |
||
= f g |
= f g |
||
. !arg:(?f.?g)&'(.($f)$(($g)$!arg)) |
. !arg:(?f.?g)&'(.($f)$(($g)$!arg)) |
||
Line 462: | Line 656: | ||
& FahrenheitToCelsiusExample$0 |
& FahrenheitToCelsiusExample$0 |
||
& FahrenheitToCelsiusExample$100 |
& FahrenheitToCelsiusExample$100 |
||
)</ |
)</syntaxhighlight> |
||
<pre>0 °F in °C = -1,78*10E1 |
<pre>0 °F in °C = -1,78*10E1 |
||
Line 468: | Line 662: | ||
=={{header|Brat}}== |
=={{header|Brat}}== |
||
< |
<syntaxhighlight lang="brat">compose = { f, g | { x | f g x } } |
||
#Test |
#Test |
||
Line 474: | Line 668: | ||
double = { x | x * 2 } |
double = { x | x * 2 } |
||
b = compose(->double ->add1) |
b = compose(->double ->add1) |
||
p b 1 #should print 4</ |
p b 1 #should print 4</syntaxhighlight> |
||
=={{header|Bruijn}}== |
|||
Composition operators as defined in <code>std/Combinator</code>: |
|||
<syntaxhighlight lang="bruijn"> |
|||
:import std/Number . |
|||
# 1x composition, bluebird combinator |
|||
…∘… [[[2 (1 0)]]] |
|||
:test (((inc ∘ (mul (+2))) (+3)) =? (+7)) ([[1]]) |
|||
# 2x composition, blackbird combinator |
|||
…∘∘… [[[[3 (2 1 0)]]]] |
|||
:test (((inc ∘∘ mul) (+2) (+3)) =? (+7)) ([[1]]) |
|||
# 3x composition, bunting combinator |
|||
…∘∘∘… [[[[[4 (3 2 1 0)]]]]] |
|||
:test (((inc ∘∘∘ (add ∘∘ mul)) (+1) (+2) (+4)) =? (+7)) ([[1]]) |
|||
# reverse composition, queer bird combinator |
|||
…→… [[[1 (2 0)]]] |
|||
:test ((((mul (+2)) → inc) (+3)) =? (+7)) ([[1]]) |
|||
</syntaxhighlight> |
|||
=={{header|C}}== |
=={{header|C}}== |
||
Only works for functions taking a double and returning a double: |
Only works for functions taking a double and returning a double: |
||
< |
<syntaxhighlight lang="c">#include <stdlib.h> |
||
/* generic interface for functors from double to double */ |
/* generic interface for functors from double to double */ |
||
Line 541: | Line 761: | ||
return 0; |
return 0; |
||
}</ |
}</syntaxhighlight> |
||
=={{header|C sharp|C#}}== |
=={{header|C sharp|C#}}== |
||
< |
<syntaxhighlight lang="csharp">using System; |
||
class Program |
class Program |
||
{ |
{ |
||
Line 561: | Line 781: | ||
} |
} |
||
} |
} |
||
}</ |
}</syntaxhighlight> |
||
=={{header|C++}}== |
=={{header|C++}}== |
||
< |
<syntaxhighlight lang="cpp">#include <functional> |
||
#include <cmath> |
#include <cmath> |
||
#include <iostream> |
#include <iostream> |
||
Line 598: | Line 818: | ||
return 0; |
return 0; |
||
}</ |
}</syntaxhighlight> |
||
{{works with|C++11}} composing <code>std::function</code> |
{{works with|C++11}} composing <code>std::function</code> |
||
< |
<syntaxhighlight lang="cpp">#include <iostream> |
||
#include <functional> |
#include <functional> |
||
#include <cmath> |
#include <cmath> |
||
Line 614: | Line 834: | ||
std::function<double(double)> g = asin; |
std::function<double(double)> g = asin; |
||
std::cout << compose(f, g)(0.5) << std::endl; |
std::cout << compose(f, g)(0.5) << std::endl; |
||
}</syntaxhighlight> |
|||
return 0; |
|||
}</lang> |
|||
{{Works with|C++14}} |
{{Works with|C++14}} |
||
This much simpler version uses <code>decltype(auto)</code>. |
This much simpler version uses <code>decltype(auto)</code>. |
||
< |
<syntaxhighlight lang="cpp">#include <iostream> |
||
#include <cmath> |
#include <cmath> |
||
Line 630: | Line 848: | ||
int main() { |
int main() { |
||
std::cout << compose(sin, asin)(0.5) << "\n"; |
std::cout << compose(sin, asin)(0.5) << "\n"; |
||
}</syntaxhighlight> |
|||
return 0; |
|||
}</lang> |
|||
{{untested|cpp}} |
|||
{{works with|GCC}} |
{{works with|GCC}} Not standard C++, but GCC has a built-in compose function |
||
< |
<syntaxhighlight lang="cpp">#include <iostream> |
||
#include <cmath> |
#include <cmath> |
||
#include <ext/functional> |
#include <ext/functional> |
||
Line 641: | Line 857: | ||
int main() { |
int main() { |
||
std::cout << __gnu_cxx::compose1(std::ptr_fun(::sin), std::ptr_fun(::asin))(0.5) << std::endl; |
std::cout << __gnu_cxx::compose1(std::ptr_fun(::sin), std::ptr_fun(::asin))(0.5) << std::endl; |
||
}</syntaxhighlight> |
|||
'''Works with:''' C++20 |
|||
return 0; |
|||
<syntaxhighlight lang="cpp">#include <iostream> |
|||
}</lang> |
|||
#include <cmath> |
|||
auto compose(auto f, auto g) { |
|||
return [=](auto x) { return f(g(x)); }; |
|||
} |
|||
int main() { |
|||
std::cout << compose(sin, asin)(0.5) << "\n"; |
|||
} |
|||
</syntaxhighlight> |
|||
{{out}} |
|||
<pre> |
|||
0.5</pre> |
|||
=={{header|Clojure}}== |
=={{header|Clojure}}== |
||
Line 649: | Line 879: | ||
A manual implementation could look like this: |
A manual implementation could look like this: |
||
< |
<syntaxhighlight lang="clojure">(defn compose [f g] |
||
(fn [x] |
(fn [x] |
||
(f (g x)))) |
(f (g x)))) |
||
Line 655: | Line 885: | ||
; Example |
; Example |
||
(def inc2 (compose inc inc)) |
(def inc2 (compose inc inc)) |
||
(println (inc2 5)) ; prints 7</ |
(println (inc2 5)) ; prints 7</syntaxhighlight> |
||
=={{header|CoffeeScript}}== |
=={{header|CoffeeScript}}== |
||
< |
<syntaxhighlight lang="coffeescript"> |
||
compose = ( f, g ) -> ( x ) -> f g x |
compose = ( f, g ) -> ( x ) -> f g x |
||
Line 674: | Line 904: | ||
console.log "addFirst 2 #=> #{ addFirst 2 }" |
console.log "addFirst 2 #=> #{ addFirst 2 }" |
||
console.log "multiple 2 #=> #{ multiple 2 }" |
console.log "multiple 2 #=> #{ multiple 2 }" |
||
</syntaxhighlight> |
|||
</lang> |
|||
{{out}} |
{{out}} |
||
Line 687: | Line 917: | ||
Or, extending the <code>Function</code> prototype. |
Or, extending the <code>Function</code> prototype. |
||
< |
<syntaxhighlight lang="coffeescript"> |
||
Function::of = (f) -> (args...) => @ f args... |
Function::of = (f) -> (args...) => @ f args... |
||
Line 703: | Line 933: | ||
console.log "addFirst 2 #=> #{ addFirst 2 }" |
console.log "addFirst 2 #=> #{ addFirst 2 }" |
||
console.log "multiple 2 #=> #{ multiple 2 }" |
console.log "multiple 2 #=> #{ multiple 2 }" |
||
</syntaxhighlight> |
|||
</lang> |
|||
Output is identical. |
Output is identical. |
||
Line 709: | Line 939: | ||
=={{header|Common Lisp}}== |
=={{header|Common Lisp}}== |
||
<code>compose</code> returns a function that closes on the lexical variables f and g. |
<code>compose</code> returns a function that closes on the lexical variables f and g. |
||
< |
<syntaxhighlight lang="lisp">(defun compose (f g) (lambda (x) (funcall f (funcall g x))))</syntaxhighlight> |
||
Example use: |
Example use: |
||
< |
<syntaxhighlight lang="lisp">>(defun compose (f g) (lambda (x) (funcall f (funcall g x)))) |
||
COMPOSE |
COMPOSE |
||
>(let ((sin-asin (compose #'sin #'asin))) |
>(let ((sin-asin (compose #'sin #'asin))) |
||
(funcall sin-asin 0.5)) |
(funcall sin-asin 0.5)) |
||
0.5</ |
0.5</syntaxhighlight> |
||
This alternate solution, more ugly and more difficult, never closes on any lexical variables. Instead, it uses [[runtime evaluation]] to insert the values of f and g into new code. This is just a different way to create a closure. |
This alternate solution, more ugly and more difficult, never closes on any lexical variables. Instead, it uses [[runtime evaluation]] to insert the values of f and g into new code. This is just a different way to create a closure. |
||
< |
<syntaxhighlight lang="lisp">(defun compose (f g) |
||
(eval `(lambda (x) (funcall ',f (funcall ',g x)))))</ |
(eval `(lambda (x) (funcall ',f (funcall ',g x)))))</syntaxhighlight> |
||
---- |
---- |
||
In this last example, a macro is used to compose any number of single parameter functions. |
In this last example, a macro is used to compose any number of single parameter functions. |
||
< |
<syntaxhighlight lang="lisp">CL-USER> (defmacro compose (fn-name &rest args) |
||
(labels ((rec1 (args) |
(labels ((rec1 (args) |
||
(if (= (length args) 1) |
(if (= (length args) 1) |
||
`(funcall ,@args x) |
`(funcall ,@args x) |
||
`(funcall ,(first args) ,(rec1 (rest args)))))) |
`(funcall ,(first args) ,(rec1 (rest args)))))) |
||
`(defun ,fn-name (x) ,(rec1 args))))</ |
`(defun ,fn-name (x) ,(rec1 args))))</syntaxhighlight> |
||
Because this macro expands into a defun form, the function returned by compose is in the function namespace and the use of funcall is not necessary. |
Because this macro expands into a defun form, the function returned by compose is in the function namespace and the use of funcall is not necessary. |
||
<pre>CL-USER> (compose f #'ceiling #'sin #'sqrt) |
<pre>CL-USER> (compose f #'ceiling #'sin #'sqrt) |
||
Line 747: | Line 977: | ||
=={{header|Crystal}}== |
=={{header|Crystal}}== |
||
Crystal requires using closures for function composition. Since the only type the compiler can't infer for <code>compose</code> is the type of <code>x</code>, the type of the first argument to <code>f</code> has to be specified as the generic type <code>T</code>. |
Crystal requires using closures for function composition. Since the only type the compiler can't infer for <code>compose</code> is the type of <code>x</code>, the type of the first argument to <code>f</code> has to be specified as the generic type <code>T</code>. |
||
< |
<syntaxhighlight lang="ruby">require "math" |
||
def compose(f : Proc(T, _), g : Proc(_, _)) forall T |
def compose(f : Proc(T, _), g : Proc(_, _)) forall T |
||
Line 753: | Line 983: | ||
end |
end |
||
compose(->Math.sin(Float64), ->Math.asin(Float64)).call(0.5) #=> 0.5</ |
compose(->Math.sin(Float64), ->Math.asin(Float64)).call(0.5) #=> 0.5</syntaxhighlight> |
||
The types for <code>f</code>'s output, <code>g</code>'s input and output, and the result of <code>compose</code> can all be inferred, but could be specified verbosely with <code>def compose(f : Proc(T, U), g : Proc(U, V)) : Proc(T, V) forall T, U, V</code> |
The types for <code>f</code>'s output, <code>g</code>'s input and output, and the result of <code>compose</code> can all be inferred, but could be specified verbosely with <code>def compose(f : Proc(T, U), g : Proc(U, V)) : Proc(T, V) forall T, U, V</code> |
||
=={{header|D}}== |
=={{header|D}}== |
||
< |
<syntaxhighlight lang="d">import std.stdio; |
||
T delegate(S) compose(T, U, S)(in T delegate(U) f, |
T delegate(S) compose(T, U, S)(in T delegate(U) f, |
||
Line 767: | Line 997: | ||
writeln(compose((int x) => x + 15, (int x) => x ^^ 2)(10)); |
writeln(compose((int x) => x + 15, (int x) => x ^^ 2)(10)); |
||
writeln(compose((int x) => x ^^ 2, (int x) => x + 15)(10)); |
writeln(compose((int x) => x ^^ 2, (int x) => x + 15)(10)); |
||
}</ |
}</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre>115 |
<pre>115 |
||
Line 776: | Line 1,006: | ||
Anonymous methods were introduced in Delphi 2009, so next code works with Delphi 2009 and above: |
Anonymous methods were introduced in Delphi 2009, so next code works with Delphi 2009 and above: |
||
< |
<syntaxhighlight lang="delphi">program AnonCompose; |
||
{$APPTYPE CONSOLE} |
{$APPTYPE CONSOLE} |
||
Line 812: | Line 1,042: | ||
Writeln(Func3(6)); // 36 = 6 * 3 * 2 |
Writeln(Func3(6)); // 36 = 6 * 3 * 2 |
||
Readln; |
Readln; |
||
end.</ |
end.</syntaxhighlight> |
||
=={{header|Diego}}== |
|||
Function composition of two simple functions: |
|||
<syntaxhighlight lang="diego">set_namespace(rosettacode); |
|||
begin_funct(compose)_arg(f, g); |
|||
[]_ret(x)_calc([f]([g]([x]))); |
|||
end_funct[]; |
|||
me_msg()_funct(compose)_arg(f)_sin()_arg(g)_asin()_var(x)_value(0.5); // result: 0.5 |
|||
reset_namespace[];</syntaxhighlight> |
|||
Function composition of two calculated functions: |
|||
<syntaxhighlight lang="diego">set_namespace(rosettacode); |
|||
with_funct(f)_arg({int}, x)_ret()_calc([x] * [x]); |
|||
with_funct(g)_arg({int}, x)_ret()_calc([x] + 2); |
|||
begin_funct(compose)_arg(f, g); |
|||
[]_ret(x)_calc([f]([g]([x]))); |
|||
end_funct[]; |
|||
me_msg()_funct(compose)_arg(f)_funct(f)_arg(g)_funct(g)_var(x)_v(10); // result: 144 |
|||
// or me_msg()_funct(compose)_arg({f}, f)_arg({g}, g)_var(x)_v(10); |
|||
reset_ns[];</syntaxhighlight> |
|||
=={{header|Dylan}}== |
=={{header|Dylan}}== |
||
Line 818: | Line 1,075: | ||
compose[https://opendylan.org/books/drm/Functional_Operations#compose] is already part of the language standard, with a more complete definition than this. |
compose[https://opendylan.org/books/drm/Functional_Operations#compose] is already part of the language standard, with a more complete definition than this. |
||
< |
<syntaxhighlight lang="dylan"> |
||
define method compose(f,g) |
define method compose(f,g) |
||
method(x) f(g(x)) end |
method(x) f(g(x)) end |
||
end; |
end; |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|Déjà Vu}}== |
=={{header|Déjà Vu}}== |
||
It is already defined in the standard library as <code>$</code>. |
It is already defined in the standard library as <code>$</code>. |
||
< |
<syntaxhighlight lang="dejavu">compose f g: |
||
labda: |
labda: |
||
f g</ |
f g</syntaxhighlight> |
||
=={{header|E}}== |
=={{header|E}}== |
||
< |
<syntaxhighlight lang="e">def compose(f, g) { |
||
return fn x { return f(g(x)) } |
return fn x { return f(g(x)) } |
||
}</ |
}</syntaxhighlight> |
||
=={{header|EchoLisp}}== |
=={{header|EchoLisp}}== |
||
< |
<syntaxhighlight lang="lisp"> |
||
;; By decreasing order of performance |
;; By decreasing order of performance |
||
;; 1) user definition : lambda and closure |
;; 1) user definition : lambda and closure |
||
Line 855: | Line 1,112: | ||
(define (sincos x) (sin (cos x))) |
(define (sincos x) (sin (cos x))) |
||
sincos → (λ (_x) (⭕️ #sin (#cos _x))) |
sincos → (λ (_x) (⭕️ #sin (#cos _x))) |
||
</syntaxhighlight> |
|||
</lang> |
|||
{{out}} |
{{out}} |
||
< |
<syntaxhighlight lang="lisp"> |
||
((ucompose sin cos) 3) → -0.8360218615377305 |
((ucompose sin cos) 3) → -0.8360218615377305 |
||
((compose sin cos) 3) → -0.8360218615377305 |
((compose sin cos) 3) → -0.8360218615377305 |
||
(sincos 3) → -0.8360218615377305 |
(sincos 3) → -0.8360218615377305 |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|Ela}}== |
=={{header|Ela}}== |
||
It is already defined in standard prelude as (<<) operator. |
It is already defined in standard prelude as (<<) operator. |
||
< |
<syntaxhighlight lang="ela">let compose f g x = f (g x)</syntaxhighlight> =={{header|Ela}}== |
||
It is already defined in standard prelude as (<<) operator. |
It is already defined in standard prelude as (<<) operator. |
||
< |
<syntaxhighlight lang="ela">compose f g x = f (g x)</syntaxhighlight> |
||
=={{header|Elena}}== |
=={{header|Elena}}== |
||
ELENA |
ELENA 6.x : |
||
< |
<syntaxhighlight lang="elena">import extensions; |
||
extension op : Func1 |
extension op : Func1 |
||
Line 883: | Line 1,140: | ||
public program() |
public program() |
||
{ |
{ |
||
var fg := (x => x + 1).compose:(x => x * x); |
var fg := (x => x + 1).compose::(x => x * x); |
||
console.printLine(fg(3)) |
console.printLine(fg(3)) |
||
}</ |
}</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 894: | Line 1,151: | ||
=={{header|Elixir}}== |
=={{header|Elixir}}== |
||
{{trans|Erlang}} |
{{trans|Erlang}} |
||
< |
<syntaxhighlight lang="elixir">defmodule RC do |
||
def compose(f, g), do: fn(x) -> f.(g.(x)) end |
def compose(f, g), do: fn(x) -> f.(g.(x)) end |
||
Line 904: | Line 1,161: | ||
IO.puts RC.multicompose([&:math.sin/1, &:math.asin/1, fn x->1/x end]).(0.5) |
IO.puts RC.multicompose([&:math.sin/1, &:math.asin/1, fn x->1/x end]).(0.5) |
||
IO.puts RC.multicompose([&(&1*&1), &(1/&1), &(&1*&1)]).(0.5)</ |
IO.puts RC.multicompose([&(&1*&1), &(1/&1), &(&1*&1)]).(0.5)</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 917: | Line 1,174: | ||
Lexical binding is supported as of Emacs 24.1, allowing the use of a closure for function composition. |
Lexical binding is supported as of Emacs 24.1, allowing the use of a closure for function composition. |
||
< |
<syntaxhighlight lang="lisp">;; lexical-binding: t |
||
(defun compose (f g) |
(defun compose (f g) |
||
(lambda (x) |
(lambda (x) |
||
Line 923: | Line 1,180: | ||
(let ((func (compose '1+ '1+))) |
(let ((func (compose '1+ '1+))) |
||
(funcall func 5)) ;=> 7</ |
(funcall func 5)) ;=> 7</syntaxhighlight> |
||
Alternatively, a <code>lambda</code> form can be constructed with the desired <code>f</code> and <code>g</code> inserted. The result is simply a list. A list starting with <code>lambda</code> is a function. |
Alternatively, a <code>lambda</code> form can be constructed with the desired <code>f</code> and <code>g</code> inserted. The result is simply a list. A list starting with <code>lambda</code> is a function. |
||
< |
<syntaxhighlight lang="lisp">(defun compose (f g) |
||
`(lambda (x) (,f (,g x)))) |
`(lambda (x) (,f (,g x)))) |
||
(let ((func (compose '1+ '1+))) |
(let ((func (compose '1+ '1+))) |
||
(funcall func 5)) ;=> 7</ |
(funcall func 5)) ;=> 7</syntaxhighlight> |
||
A similar thing can be done with a macro like the following. It differs in that the arguments should be unquoted symbols, and if they're expressions then they're evaluated on every call to the resulting <code>lambda</code>. |
A similar thing can be done with a macro like the following. It differs in that the arguments should be unquoted symbols, and if they're expressions then they're evaluated on every call to the resulting <code>lambda</code>. |
||
< |
<syntaxhighlight lang="lisp">(defmacro compose (f g) |
||
`(lambda (x) (,f (,g x)))) |
`(lambda (x) (,f (,g x)))) |
||
(let ((func (compose 1+ 1+))) |
(let ((func (compose 1+ 1+))) |
||
(funcall func 5)) ;=> 7</ |
(funcall func 5)) ;=> 7</syntaxhighlight> |
||
=={{header|Erlang}}== |
=={{header|Erlang}}== |
||
< |
<syntaxhighlight lang="erlang">-module(fn). |
||
-export([compose/2, multicompose/1]). |
-export([compose/2, multicompose/1]). |
||
Line 948: | Line 1,205: | ||
multicompose(Fs) -> |
multicompose(Fs) -> |
||
lists:foldl(fun compose/2, fun(X) -> X end, Fs).</ |
lists:foldl(fun compose/2, fun(X) -> X end, Fs).</syntaxhighlight> |
||
Using them: |
Using them: |
||
< |
<syntaxhighlight lang="erlang">1> (fn:compose(fun math:sin/1, fun math:asin/1))(0.5). |
||
0.5 |
0.5 |
||
2> Sin_asin_plus1 = fn:multicompose([fun math:sin/1, fun math:asin/1, fun(X) -> X + 1 end]). |
2> Sin_asin_plus1 = fn:multicompose([fun math:sin/1, fun math:asin/1, fun(X) -> X + 1 end]). |
||
#Fun<tests.0.59446746> |
#Fun<tests.0.59446746> |
||
82> Sin_asin_plus1(0.5). |
82> Sin_asin_plus1(0.5). |
||
1.5</ |
1.5</syntaxhighlight> |
||
{{omit from|Euphoria}} |
{{omit from|Euphoria}} |
||
Line 966: | Line 1,223: | ||
We can implement composition manually like this (F# Interactive session): |
We can implement composition manually like this (F# Interactive session): |
||
< |
<syntaxhighlight lang="fsharp">> let compose f g x = f (g x);; |
||
val compose : ('a -> 'b) -> ('c -> 'a) -> 'c -> 'b</ |
val compose : ('a -> 'b) -> ('c -> 'a) -> 'c -> 'b</syntaxhighlight> |
||
Usage: |
Usage: |
||
< |
<syntaxhighlight lang="fsharp">> let sin_asin = compose sin asin;; |
||
val sin_asin : (float -> float) |
val sin_asin : (float -> float) |
||
> sin_asin 0.5;; |
> sin_asin 0.5;; |
||
val it : float = 0.5</ |
val it : float = 0.5</syntaxhighlight> |
||
=={{header|Factor}}== |
=={{header|Factor}}== |
||
Line 982: | Line 1,239: | ||
To compose quotations (anonymous functions), <code>compose</code> may be used: |
To compose quotations (anonymous functions), <code>compose</code> may be used: |
||
< |
<syntaxhighlight lang="factor">( scratchpad ) [ 2 * ] [ 1 + ] compose . |
||
[ 2 * 1 + ] |
[ 2 * 1 + ] |
||
( scratchpad ) 4 [ 2 * ] [ 1 + ] compose call . |
( scratchpad ) 4 [ 2 * ] [ 1 + ] compose call . |
||
9</ |
9</syntaxhighlight> |
||
=={{header|Fantom}}== |
=={{header|Fantom}}== |
||
< |
<syntaxhighlight lang="fantom"> |
||
class Compose |
class Compose |
||
{ |
{ |
||
Line 1,004: | Line 1,261: | ||
} |
} |
||
} |
} |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|Forth}}== |
=={{header|Forth}}== |
||
< |
<syntaxhighlight lang="forth">: compose ( xt1 xt2 -- xt3 ) |
||
>r >r :noname |
>r >r :noname |
||
r> compile, |
r> compile, |
||
Line 1,015: | Line 1,272: | ||
' 2* ' 1+ compose ( xt ) |
' 2* ' 1+ compose ( xt ) |
||
3 swap execute . \ 7</ |
3 swap execute . \ 7</syntaxhighlight> |
||
=={{header|Fortran}}== |
=={{header|Fortran}}== |
||
Modern Fortran standard has (limited) kind of higher-order functions (as result, argument, and with one level of nested functions) and optional arguments, and this enables to compose the following function (it is impure because Fortran ''has no closures''). For simple cases function calls may be just nested to achieve the effect of function composition, because in fortran nested calls f(g(d(x))) generate a hierarchic set of function calls and the result of each function is transmitted to its calling function in a standard way for all functions. |
Modern Fortran standard has (limited) kind of higher-order functions (as result, argument, and with one level of nested functions) and optional arguments, and this enables to compose the following function (it is impure because Fortran ''has no closures''). For simple cases function calls may be just nested to achieve the effect of function composition, because in fortran nested calls f(g(d(x))) generate a hierarchic set of function calls and the result of each function is transmitted to its calling function in a standard way for all functions. |
||
< |
<syntaxhighlight lang="fortran"> |
||
module functions_module |
module functions_module |
||
implicit none |
implicit none |
||
Line 1,100: | Line 1,357: | ||
write(*,*) "run compose:", compose(0.5) |
write(*,*) "run compose:", compose(0.5) |
||
end program test_compose |
end program test_compose |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|Fortress}}== |
=={{header|Fortress}}== |
||
Line 1,109: | Line 1,366: | ||
In this version, we allow any type of function to be used by defining our own types in the function definition and using those types to define how the composed function should behave. This version operates very similarly to the way that the COMPOSE operator, explained below, operates. |
In this version, we allow any type of function to be used by defining our own types in the function definition and using those types to define how the composed function should behave. This version operates very similarly to the way that the COMPOSE operator, explained below, operates. |
||
< |
<syntaxhighlight lang="fortress"> |
||
compose[\A, B, C\](f:A->B, g:B->C, i:Any): A->C = do |
compose[\A, B, C\](f:A->B, g:B->C, i:Any): A->C = do |
||
f(g(i)) |
f(g(i)) |
||
Line 1,115: | Line 1,372: | ||
composed(i:RR64): RR64 = compose(sin, cos, i) |
composed(i:RR64): RR64 = compose(sin, cos, i) |
||
</syntaxhighlight> |
|||
</lang> |
|||
Alternatively, you could explicitly define each type for improved type safety. |
Alternatively, you could explicitly define each type for improved type safety. |
||
Due to the fact that alt_compose() is built around the idea that it is being used to compose two trigonometric functions, these will return identical functions. However, if you were to pass alt_composed() any other type of function, the interpreter would throw an error. |
Due to the fact that alt_compose() is built around the idea that it is being used to compose two trigonometric functions, these will return identical functions. However, if you were to pass alt_composed() any other type of function, the interpreter would throw an error. |
||
< |
<syntaxhighlight lang="fortress"> |
||
alt_compose(f:Number->RR64, g:Number->RR64, i:RR64): ()->RR64 = do |
alt_compose(f:Number->RR64, g:Number->RR64, i:RR64): ()->RR64 = do |
||
f(g(i)) |
f(g(i)) |
||
Line 1,126: | Line 1,383: | ||
alt_composed(i:RR64): RR64 = compose(sin, cos, i) |
alt_composed(i:RR64): RR64 = compose(sin, cos, i) |
||
</syntaxhighlight> |
|||
</lang> |
|||
2. You can use the COMPOSE operator (or CIRC or RING). Because COMPOSE returns an anonymous function, it is necessary to wrap it in parentheses if you want to be able to use it in this manner. |
2. You can use the COMPOSE operator (or CIRC or RING). Because COMPOSE returns an anonymous function, it is necessary to wrap it in parentheses if you want to be able to use it in this manner. |
||
< |
<syntaxhighlight lang="fortress"> |
||
opr_composed(i:Number): Number->RR64 = (sin COMPOSE cos)(i) |
opr_composed(i:Number): Number->RR64 = (sin COMPOSE cos)(i) |
||
</syntaxhighlight> |
|||
</lang> |
|||
Should you need to, you could also mix both methods by overloading the COMPOSE operator. |
Should you need to, you could also mix both methods by overloading the COMPOSE operator. |
||
Line 1,138: | Line 1,395: | ||
=={{header|FreeBASIC}}== |
=={{header|FreeBASIC}}== |
||
Illustrating with functions that take and return integers. |
Illustrating with functions that take and return integers. |
||
< |
<syntaxhighlight lang="freebasic">function compose( f as function(as integer) as integer,_ |
||
g as function(as integer) as integer,_ |
g as function(as integer) as integer,_ |
||
n as integer ) as integer |
n as integer ) as integer |
||
return f(g(n)) |
return f(g(n)) |
||
end function</ |
end function</syntaxhighlight> |
||
If you have functions named, say, foo and bar you would call compose with |
If you have functions named, say, foo and bar you would call compose with |
||
<pre>compose( @foo, @bar, n )</pre> for some integer n. |
<pre>compose( @foo, @bar, n )</pre> for some integer n. |
||
=={{header|FunL}}== |
=={{header|FunL}}== |
||
< |
<syntaxhighlight lang="funl">import math.{sin, asin} |
||
def compose( f, g ) = x -> f( g(x) ) |
def compose( f, g ) = x -> f( g(x) ) |
||
Line 1,153: | Line 1,410: | ||
sin_asin = compose( sin, asin ) |
sin_asin = compose( sin, asin ) |
||
println( sin_asin(0.5) )</ |
println( sin_asin(0.5) )</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 1,163: | Line 1,420: | ||
=={{header|Fōrmulæ}}== |
=={{header|Fōrmulæ}}== |
||
{{FormulaeEntry|page=https://formulae.org/?script=examples/Function_composition}} |
|||
Fōrmulæ programs are not textual, visualization/edition of programs is done showing/manipulating structures but not text. Moreover, there can be multiple visual representations of the same program. Even though it is possible to have textual representation —i.e. XML, JSON— they are intended for storage and transfer purposes more than visualization and edition. |
|||
'''Solution''' |
|||
Programs in Fōrmulæ are created/edited online in its [https://formulae.org website], However they run on execution servers. By default remote servers are used, but they are limited in memory and processing power, since they are intended for demonstration and casual use. A local server can be downloaded and installed, it has no limitations (it runs in your own computer). Because of that, example programs can be fully visualized and edited, but some of them will not run if they require a moderate or heavy computation/memory resources, and no local server is being used. |
|||
[[File:Fōrmulæ - Function composition 01.png]] |
|||
In '''[https://formulae.org/?example=Function_composition this]''' page you can see the program(s) related to this task and their results. |
|||
The compose function returns a lambda expression, containing the actual composition of its arguments, and hence it can be called applied with its argument(s): |
|||
'''Test cases''' |
|||
[[File:Fōrmulæ - Function composition 02.png]] |
|||
[[File:Fōrmulæ - Function composition 03.png]] |
|||
Arguments of the functions to compose can be the same symbol, they are not "scrambled": |
|||
[[File:Fōrmulæ - Function composition 04.png]] |
|||
[[File:Fōrmulæ - Function composition 05.png]] |
|||
Because a function in Fōrmulæ is just a lambda expression, a lambda expression can be directly provided. |
|||
[[File:Fōrmulæ - Function composition 06.png]] |
|||
[[File:Fōrmulæ - Function composition 03.png]] |
|||
[[File:Fōrmulæ - Function composition 07.png]] |
|||
[[File:Fōrmulæ - Function composition 05.png]] |
|||
Since the composition function returns a lambda expression, it is not required to be applied: |
|||
[[File:Fōrmulæ - Function composition 08.png]] |
|||
[[File:Fōrmulæ - Function composition 09.png]] |
|||
[[File:Fōrmulæ - Function composition 10.png]] |
|||
[[File:Fōrmulæ - Function composition 11.png]] |
|||
=={{header|GAP}}== |
=={{header|GAP}}== |
||
< |
<syntaxhighlight lang="gap">Composition := function(f, g) |
||
return x -> f(g(x)); |
return x -> f(g(x)); |
||
end; |
end; |
||
Line 1,176: | Line 1,467: | ||
h := Composition(x -> x+1, x -> x*x); |
h := Composition(x -> x+1, x -> x*x); |
||
h(5); |
h(5); |
||
# 26</ |
# 26</syntaxhighlight> |
||
=={{header|Go}}== |
=={{header|Go}}== |
||
< |
<syntaxhighlight lang="go">// Go doesn't have generics, but sometimes a type definition helps |
||
// readability and maintainability. This example is written to |
// readability and maintainability. This example is written to |
||
// the following function type, which uses float64. |
// the following function type, which uses float64. |
||
Line 1,189: | Line 1,480: | ||
return f(g(x)) |
return f(g(x)) |
||
} |
} |
||
}</ |
}</syntaxhighlight> |
||
Example use: |
Example use: |
||
< |
<syntaxhighlight lang="go">package main |
||
import "math" |
import "math" |
||
Line 1,207: | Line 1,498: | ||
sin_asin := compose(math.Sin, math.Asin) |
sin_asin := compose(math.Sin, math.Asin) |
||
fmt.Println(sin_asin(.5)) |
fmt.Println(sin_asin(.5)) |
||
}</ |
}</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 1,215: | Line 1,506: | ||
=={{header|Groovy}}== |
=={{header|Groovy}}== |
||
Test program: |
Test program: |
||
< |
<syntaxhighlight lang="groovy">final times2 = { it * 2 } |
||
final plus1 = { it + 1 } |
final plus1 = { it + 1 } |
||
Line 1,222: | Line 1,513: | ||
assert plus1_then_times2(3) == 8 |
assert plus1_then_times2(3) == 8 |
||
assert times2_then_plus1(3) == 7</ |
assert times2_then_plus1(3) == 7</syntaxhighlight> |
||
=={{header|Haskell}}== |
=={{header|Haskell}}== |
||
This is already defined as the '''.''' (dot) operator in Haskell: |
This is already defined as the '''.''' (dot) operator in Haskell: |
||
< |
<syntaxhighlight lang="haskell">Prelude> let sin_asin = sin . asin |
||
Prelude> sin_asin 0.5 |
Prelude> sin_asin 0.5 |
||
0.49999999999999994</ |
0.49999999999999994</syntaxhighlight> |
||
Ways to use directly: |
Ways to use directly: |
||
< |
<syntaxhighlight lang="haskell">(sin . asin) 0.5</syntaxhighlight> |
||
< |
<syntaxhighlight lang="haskell">sin . asin $ 0.5</syntaxhighlight> |
||
Implementing compose function from scratch: |
Implementing compose function from scratch: |
||
< |
<syntaxhighlight lang="haskell">compose f g x = f (g x)</syntaxhighlight> |
||
Example use: |
Example use: |
||
< |
<syntaxhighlight lang="haskell">Prelude> let compose f g x = f (g x) |
||
Prelude> let sin_asin = compose sin asin |
Prelude> let sin_asin = compose sin asin |
||
Prelude> sin_asin 0.5 |
Prelude> sin_asin 0.5 |
||
0.5</ |
0.5</syntaxhighlight> |
||
Right to left composition of a list of functions could be defined as ''flip (foldr id)'': |
Right to left composition of a list of functions could be defined as ''flip (foldr id)'': |
||
< |
<syntaxhighlight lang="haskell">composeList :: [a -> a] -> a -> a |
||
composeList = flip (foldr id) |
composeList = flip (foldr id) |
||
main :: IO () |
main :: IO () |
||
main = print $ composeList [(/ 2), succ, sqrt] 5</ |
main = print $ composeList [(/ 2), succ, sqrt] 5</syntaxhighlight> |
||
{{Out}} |
{{Out}} |
||
<pre>1.618033988749895</pre> |
<pre>1.618033988749895</pre> |
||
=={{header|Hy}}== |
=={{header|Hy}}== |
||
< |
<syntaxhighlight lang="clojure">(defn compose [f g] |
||
(fn [x] |
(fn [x] |
||
(f (g x))))</ |
(f (g x))))</syntaxhighlight> |
||
=={{header|Icon}} and {{header|Unicon}}== |
=={{header|Icon}} and {{header|Unicon}}== |
||
Line 1,269: | Line 1,560: | ||
The solution below can be adapted to work in Icon by reverting to the old syntax for invoking co-expressions. |
The solution below can be adapted to work in Icon by reverting to the old syntax for invoking co-expressions. |
||
< |
<syntaxhighlight lang="icon"> x @ f # use this syntax in Icon instead of the Unicon f(x) to call co-expressions |
||
every push(fL := [],!rfL) # use this instead of reverse(fL) as the Icon reverse applies only to strings</ |
every push(fL := [],!rfL) # use this instead of reverse(fL) as the Icon reverse applies only to strings</syntaxhighlight> |
||
See [[Icon%2BUnicon/Intro#Minor_Differences|Icon and Unicon Introduction:Minor Differences]] for more information |
See [[Icon%2BUnicon/Intro#Minor_Differences|Icon and Unicon Introduction:Minor Differences]] for more information |
||
< |
<syntaxhighlight lang="unicon">procedure main(arglist) |
||
h := compose(sqrt,abs) |
h := compose(sqrt,abs) |
||
k := compose(integer,"sqrt",ord) |
k := compose(integer,"sqrt",ord) |
||
Line 1,303: | Line 1,594: | ||
return (@cf, cf) # 'prime' the co-expr before returning it |
return (@cf, cf) # 'prime' the co-expr before returning it |
||
end</ |
end</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 1,320: | Line 1,611: | ||
'''Solution''': |
'''Solution''': |
||
< |
<syntaxhighlight lang="j">compose =: @</syntaxhighlight> |
||
'''Example''': |
'''Example''': |
||
<lang |
<syntaxhighlight lang="j">f compose g</syntaxhighlight> |
||
Of course, given that <code>@</code> is only one character long and is a built-in primitive, there is no need for the cover function <code>compose</code>. And <code>@</code> is not the only composition primitive; composition is a very important concept in J. For more details, see the [[Talk:Functional Composition#J|talk page]]. |
Of course, given that <code>@</code> is only one character long and is a built-in primitive, there is no need for the cover function <code>compose</code>. And <code>@</code> is not the only composition primitive; composition is a very important concept in J. For more details, see the [[Talk:Functional Composition#J|talk page]]. |
||
Line 1,329: | Line 1,620: | ||
Tentative new example: |
Tentative new example: |
||
< |
<syntaxhighlight lang="j">f=: >.@(1&o.)@%: |
||
g=: 1&+@|@(2&o.) |
g=: 1&+@|@(2&o.) |
||
h=: f@g</ |
h=: f@g</syntaxhighlight> |
||
Example use: |
Example use: |
||
< |
<syntaxhighlight lang="j"> (f, g, h) 1p1 |
||
1 2 1</ |
1 2 1</syntaxhighlight> |
||
Note: <code>1&o.</code> is sine (mnemonic: sine is an odd circular function), <code>2&o.</code> is cosine (cosine is an even circular function), <code>%:</code> is square root, <code>>.</code> is ceiling, <code>|</code> is absolute value and <code>1&+</code> adds 1. |
Note: <code>1&o.</code> is sine (mnemonic: sine is an odd circular function), <code>2&o.</code> is cosine (cosine is an even circular function), <code>%:</code> is square root, <code>>.</code> is ceiling, <code>|</code> is absolute value and <code>1&+</code> adds 1. |
||
=={{header|Janet}}== |
|||
Janet supports function composition with the [https://janet-lang.org/api/misc.html#comp <code>comp</code>] function. |
|||
<syntaxhighlight lang="janet">(defn fahrenheit->celsius [deg-f] |
|||
(/ (* (- deg-f 32) 5) 9)) |
|||
(defn celsius->kelvin [deg-c] |
|||
(+ deg-c 273.15)) |
|||
(def fahrenheit->kelvin (comp celsius->kelvin fahrenheit->celsius)) |
|||
(fahrenheit->kelvin 72) // 295.372 |
|||
</syntaxhighlight> |
|||
=={{header|Java}}== |
=={{header|Java}}== |
||
< |
<syntaxhighlight lang="java">public class Compose { |
||
// Java doesn't have function type so we define an interface |
// Java doesn't have function type so we define an interface |
||
Line 1,372: | Line 1,678: | ||
System.out.println(sin_asin.call(0.5)); // prints "0.5" |
System.out.println(sin_asin.call(0.5)); // prints "0.5" |
||
} |
} |
||
}</ |
}</syntaxhighlight> |
||
===Java 8=== |
===Java 8=== |
||
Line 1,378: | Line 1,684: | ||
Java 8's <code>Function</code> interface already has a <code>.compose()</code> default method: |
Java 8's <code>Function</code> interface already has a <code>.compose()</code> default method: |
||
{{works with|Java|8+}} |
{{works with|Java|8+}} |
||
< |
<syntaxhighlight lang="java">import java.util.function.Function; |
||
public class Compose { |
public class Compose { |
||
Line 1,386: | Line 1,692: | ||
System.out.println(sin_asin.apply(0.5)); // prints "0.5" |
System.out.println(sin_asin.apply(0.5)); // prints "0.5" |
||
} |
} |
||
}</ |
}</syntaxhighlight> |
||
Implementing it yourself as a static method: |
Implementing it yourself as a static method: |
||
{{works with|Java|8+}} |
{{works with|Java|8+}} |
||
< |
<syntaxhighlight lang="java">import java.util.function.Function; |
||
public class Compose { |
public class Compose { |
||
Line 1,402: | Line 1,708: | ||
System.out.println(sin_asin.apply(0.5)); // prints "0.5" |
System.out.println(sin_asin.apply(0.5)); // prints "0.5" |
||
} |
} |
||
}</ |
}</syntaxhighlight> |
||
=={{header|JavaScript}}== |
=={{header|JavaScript}}== |
||
===ES5=== |
===ES5=== |
||
====Simple composition of two functions==== |
====Simple composition of two functions==== |
||
< |
<syntaxhighlight lang="javascript">function compose(f, g) { |
||
return function(x) { |
return function(x) { |
||
return f(g(x)); |
return f(g(x)); |
||
}; |
}; |
||
}</ |
}</syntaxhighlight> |
||
Example: |
Example: |
||
< |
<syntaxhighlight lang="javascript">var id = compose(Math.sin, Math.asin); |
||
console.log(id(0.5)); // 0.5</ |
console.log(id(0.5)); // 0.5</syntaxhighlight> |
||
Line 1,424: | Line 1,730: | ||
# With a fold / reduction (see http://rosettacode.org/wiki/Catamorphism). The fold is arguably simpler to write and reason about, though not quite as fast to execute. |
# With a fold / reduction (see http://rosettacode.org/wiki/Catamorphism). The fold is arguably simpler to write and reason about, though not quite as fast to execute. |
||
< |
<syntaxhighlight lang="javascript">(function () { |
||
'use strict'; |
'use strict'; |
||
Line 1,473: | Line 1,779: | ||
}); |
}); |
||
})(); |
})(); |
||
</syntaxhighlight> |
|||
</lang> |
|||
{{Out}} |
{{Out}} |
||
Line 1,483: | Line 1,789: | ||
====Simple composition of two functions==== |
====Simple composition of two functions==== |
||
< |
<syntaxhighlight lang="javascript">function compose(f, g) { |
||
return x => f(g(x)); |
return x => f(g(x)); |
||
}</ |
}</syntaxhighlight> |
||
or |
or |
||
< |
<syntaxhighlight lang="javascript">var compose = (f, g) => x => f(g(x));</syntaxhighlight> |
||
Example: |
Example: |
||
< |
<syntaxhighlight lang="javascript">var id = compose(Math.sin, Math.asin); |
||
console.log(id(0.5)); // 0.5</ |
console.log(id(0.5)); // 0.5</syntaxhighlight> |
||
====Multiple composition==== |
====Multiple composition==== |
||
< |
<syntaxhighlight lang="javascript">(() => { |
||
"use strict"; |
|||
// -------------- MULTIPLE COMPOSITION --------------- |
|||
// compose :: |
// compose (<<<) :: (b -> c) -> (a -> b) -> a -> c |
||
const compose = (...fs) => |
const compose = (...fs) => |
||
// A function defined by the right-to-left |
|||
x => fs.reduceRight( |
|||
// composition of all the functions in fs. |
|||
fs.reduce( |
|||
(f, g) => x => f(g(x)), |
|||
x => x |
|||
); |
); |
||
// ---------------------- TEST ----------------------- |
|||
// Test a composition of 3 functions (right to left) |
|||
const |
const |
||
sqrt = Math.sqrt, |
sqrt = Math.sqrt, |
||
Line 1,511: | Line 1,821: | ||
return compose(half, succ, sqrt)(5); |
return compose(half, succ, sqrt)(5); |
||
// --> 1.618033988749895 |
// --> 1.618033988749895 |
||
})();</ |
})();</syntaxhighlight> |
||
{{Out}} |
{{Out}} |
||
<pre>1.618033988749895</pre> |
<pre>1.618033988749895</pre> |
||
Line 1,519: | Line 1,829: | ||
=={{header|Joy}}== |
=={{header|Joy}}== |
||
Composition is the default operation in Joy. The composition of two functions is the concatenation of those functions, in the order in which they are to be applied. |
Composition is the default operation in Joy. The composition of two functions is the concatenation of those functions, in the order in which they are to be applied. |
||
<lang |
<syntaxhighlight lang="joy">g f</syntaxhighlight> |
||
And yes, there should be a space between the two names. |
|||
=={{header|jq}}== |
=={{header|jq}}== |
||
Line 1,525: | Line 1,836: | ||
We therefore illustrate here how a function that composes two 0-arity filters can be written: |
We therefore illustrate here how a function that composes two 0-arity filters can be written: |
||
<syntaxhighlight lang="jq"> |
|||
<lang jq> |
|||
# apply g first and then f |
# apply g first and then f |
||
def compose(f; g): g | f; |
def compose(f; g): g | f; |
||
</syntaxhighlight> |
|||
</lang> |
|||
Example: 0.5 | compose(asin; sin) |
Example: 0.5 | compose(asin; sin) |
||
Line 1,536: | Line 1,847: | ||
{{works with|Julia|0.6}} |
{{works with|Julia|0.6}} |
||
'''Built-in''': |
'''Built-in''': |
||
< |
<syntaxhighlight lang="julia">@show (asin ∘ sin)(0.5)</syntaxhighlight> |
||
'''Alternative''': |
'''Alternative''': |
||
< |
<syntaxhighlight lang="julia">compose(f::Function, g::Function) = (x) -> g(f(x)) |
||
@show compose(sin, asin)(0.5)</ |
@show compose(sin, asin)(0.5)</syntaxhighlight> |
||
=={{header|K}}== |
=={{header|K}}== |
||
The K syntax for APL tacit (point free) function composition is the dyadic form of apostrophe ('), here is a cover function |
The K syntax for APL tacit (point free) function composition is the dyadic form of apostrophe ('), here is a cover function |
||
<lang |
<syntaxhighlight lang="k">compose:{'[x;y]}</syntaxhighlight> |
||
An equivalent explicit definition would be |
An equivalent explicit definition would be |
||
< |
<syntaxhighlight lang="k">compose:{x[y[z]]}</syntaxhighlight> |
||
'''Example:''' |
'''Example:''' |
||
< |
<syntaxhighlight lang="k"> sin_asin:compose[sin;asin] // or compose . (sin;asin) |
||
sin_asin 0.5 |
sin_asin 0.5 |
||
0.5</ |
0.5</syntaxhighlight> |
||
=={{header|Klingphix}}== |
=={{header|Klingphix}}== |
||
< |
<syntaxhighlight lang="klingphix">include ..\Utilitys.tlhy |
||
:*2 2 * ; |
:*2 2 * ; |
||
Line 1,563: | Line 1,874: | ||
@++ @*2 3 composite ? { result: 7 } |
@++ @*2 3 composite ? { result: 7 } |
||
"End " input</ |
"End " input</syntaxhighlight> |
||
=={{header|Kotlin}}== |
=={{header|Kotlin}}== |
||
<syntaxhighlight lang="kotlin"> |
|||
<lang scala>// version 1.0.6 |
|||
fun f(x: Int): Int = x * x |
fun f(x: Int): Int = x * x |
||
fun g(x: Int): Int = x + 2 |
fun g(x: Int): Int = x + 2 |
||
fun compose(f: ( |
fun <T, V, R> compose(f: (V) -> R, g: (T) -> V): (T) -> R = { f(g(it) } |
||
fun main( |
fun main() { |
||
val x |
val x = 10 |
||
println(compose(::f, ::g)(x)) |
println(compose(::f, ::g)(x)) |
||
}</ |
}</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 1,585: | Line 1,895: | ||
=={{header|Lambdatalk}}== |
=={{header|Lambdatalk}}== |
||
<syntaxhighlight lang="scheme"> |
|||
<lang Scheme> |
|||
{def compose |
{def compose |
||
{lambda {:f :g :x} |
{lambda {:f :g :x} |
||
Line 1,602: | Line 1,912: | ||
{{f} 3} |
{{f} 3} |
||
-> 80 |
-> 80 |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|Lang}}== |
|||
<syntaxhighlight lang="lang"> |
|||
fp.f = ($x) -> return parser.op($x * 3) |
|||
fp.g = ($x) -> return parser.op($x + 2) |
|||
$x = 5 |
|||
# In Lang this task can be achieved with the concat operator |
|||
fn.println(parser.op((fp.g ||| fp.f)($x))) # Prints 21 [Internal execution: fp.f(fp.g($x))] |
|||
# Creating a user-defined function doing the same thing is a bit more difficult |
|||
fp.compose = (fp.f, fp.g) -> { |
|||
fp.innerFunc = (fp.f, fp.g, $x) -> return fp.f(fp.g($x)) |
|||
return fn.argCnt1(fn.combA3(fp.innerFunc, fp.f, fp.g)) # fn.combA3 must be used, because Lang does not support closures |
|||
} |
|||
fn.println(fp.compose(fp.f, fp.g)($x)) # Prints also 21 |
|||
</syntaxhighlight> |
|||
=={{header|LFE}}== |
=={{header|LFE}}== |
||
< |
<syntaxhighlight lang="lisp"> |
||
(defun compose (f g) |
(defun compose (f g) |
||
(lambda (x) |
(lambda (x) |
||
Line 1,622: | Line 1,951: | ||
(io:format '"Expected answer: ~p~n" (list expected)) |
(io:format '"Expected answer: ~p~n" (list expected)) |
||
(io:format '"Answer with compose: ~p~n" (list compose-result)))) |
(io:format '"Answer with compose: ~p~n" (list compose-result)))) |
||
</syntaxhighlight> |
|||
</lang> |
|||
If you pasted those into the LFE REPL, you can do the following: |
If you pasted those into the LFE REPL, you can do the following: |
||
< |
<syntaxhighlight lang="lisp"> |
||
> (funcall (compose #'math:sin/1 #'math:asin/1) |
> (funcall (compose #'math:sin/1 #'math:asin/1) |
||
0.5) |
0.5) |
||
Line 1,639: | Line 1,968: | ||
ok |
ok |
||
> |
> |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|Lingo}}== |
=={{header|Lingo}}== |
||
Line 1,657: | Line 1,986: | ||
For such "call-functions", function composition can be implemented using the following global (i.e. movie script) function compose() and the following parent script "Composer": |
For such "call-functions", function composition can be implemented using the following global (i.e. movie script) function compose() and the following parent script "Composer": |
||
< |
<syntaxhighlight lang="lingo">-- in some movie script |
||
---------------------------------------- |
---------------------------------------- |
||
-- Composes 2 call-functions, returns a new call-function |
-- Composes 2 call-functions, returns a new call-function |
||
Line 1,666: | Line 1,995: | ||
on compose (f, g) |
on compose (f, g) |
||
return script("Composer").new(f, g) |
return script("Composer").new(f, g) |
||
end</ |
end</syntaxhighlight> |
||
< |
<syntaxhighlight lang="lingo">-- parent script "Composer" |
||
property _f |
property _f |
||
Line 1,701: | Line 2,030: | ||
return _movie.call(me._f, _movie, value(cmd)) |
return _movie.call(me._f, _movie, value(cmd)) |
||
end if |
end if |
||
end</ |
end</syntaxhighlight> |
||
Usage: |
Usage: |
||
< |
<syntaxhighlight lang="lingo">-- compose new function based on built-in function 'sin' and user-defined function 'asin' |
||
f1 = compose(#asin, #sin) |
f1 = compose(#asin, #sin) |
||
put call(f1, _movie, 0.5) |
put call(f1, _movie, 0.5) |
||
Line 1,719: | Line 2,048: | ||
f3 = compose(f2, f1) |
f3 = compose(f2, f1) |
||
put call(f3, _movie, 0.5) |
put call(f3, _movie, 0.5) |
||
-- 3.0000</ |
-- 3.0000</syntaxhighlight> |
||
User-defined custom functions used in demo code above: |
User-defined custom functions used in demo code above: |
||
< |
<syntaxhighlight lang="lingo">-- in some movie script |
||
on asin (x) |
on asin (x) |
||
res = atan(sqrt(x*x/(1-x*x))) |
res = atan(sqrt(x*x/(1-x*x))) |
||
Line 1,735: | Line 2,064: | ||
on triple (x) |
on triple (x) |
||
return x*3 |
return x*3 |
||
end</ |
end</syntaxhighlight> |
||
=={{header|LOLCODE}}== |
=={{header|LOLCODE}}== |
||
LOLCODE supports first-class functions only insofar as they may be stored in variables and returned from other functions. Alas, given the current lack of support for either lambdas or closures, function composition can only be reasonably simulated with the help of a few global variables. |
LOLCODE supports first-class functions only insofar as they may be stored in variables and returned from other functions. Alas, given the current lack of support for either lambdas or closures, function composition can only be reasonably simulated with the help of a few global variables. |
||
< |
<syntaxhighlight lang="lolcode">HAI 1.3 |
||
I HAS A fx, I HAS A gx |
I HAS A fx, I HAS A gx |
||
Line 1,765: | Line 2,094: | ||
VISIBLE I IZ sqrincin YR 10 MKAY BTW, prints 121 |
VISIBLE I IZ sqrincin YR 10 MKAY BTW, prints 121 |
||
KTHXBYE</ |
KTHXBYE</syntaxhighlight> |
||
=={{header|Lua}}== |
=={{header|Lua}}== |
||
< |
<syntaxhighlight lang="lua">function compose(f, g) return function(...) return f(g(...)) end end</syntaxhighlight> |
||
=={{header|M2000 Interpreter}}== |
=={{header|M2000 Interpreter}}== |
||
===Using Lambda functions=== |
===Using Lambda functions=== |
||
<syntaxhighlight lang="m2000 interpreter"> |
|||
<lang M2000 Interpreter> |
|||
Module CheckIt { |
Module CheckIt { |
||
Compose = lambda (f, g)->{ |
Compose = lambda (f, g)->{ |
||
Line 1,783: | Line 2,112: | ||
} |
} |
||
CheckIt |
CheckIt |
||
</syntaxhighlight> |
|||
</lang> |
|||
===Using EVAL and EVAL$=== |
===Using EVAL and EVAL$=== |
||
<syntaxhighlight lang="m2000 interpreter"> |
|||
<lang M2000 Interpreter> |
|||
class Compose { |
class Compose { |
||
private: |
private: |
||
Line 1,823: | Line 2,152: | ||
UcaseLcase$=ComposeStr$("Ucase$", "Lcase$") |
UcaseLcase$=ComposeStr$("Ucase$", "Lcase$") |
||
Print UcaseLcase$("GOOD") |
Print UcaseLcase$("GOOD") |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|Mathcad}}== |
=={{header|Mathcad}}== |
||
Line 1,849: | Line 2,178: | ||
=={{header|Mathematica}} / {{header|Wolfram Language}}== |
=={{header|Mathematica}} / {{header|Wolfram Language}}== |
||
Built-in function that takes any amount of function-arguments: |
Built-in function that takes any amount of function-arguments: |
||
< |
<syntaxhighlight lang="mathematica">Composition[f, g][x] |
||
Composition[f, g, h, i][x]</ |
Composition[f, g, h, i][x]</syntaxhighlight> |
||
gives back: |
gives back: |
||
< |
<syntaxhighlight lang="mathematica">f[g[x]] |
||
f[g[h[i[x]]]]</ |
f[g[h[i[x]]]]</syntaxhighlight> |
||
Custom function: |
Custom function: |
||
< |
<syntaxhighlight lang="mathematica">compose[f_, g_][x_] := f[g[x]] |
||
compose[Sin, Cos][r]</ |
compose[Sin, Cos][r]</syntaxhighlight> |
||
gives back: |
gives back: |
||
<lang |
<syntaxhighlight lang="mathematica">Sin[Cos[r]]</syntaxhighlight> |
||
Composition can be done in more than 1 way: |
Composition can be done in more than 1 way: |
||
< |
<syntaxhighlight lang="mathematica">Composition[f,g,h][x] |
||
f@g@h@x |
f@g@h@x |
||
x//h//g//f</ |
x//h//g//f</syntaxhighlight> |
||
all give back: |
all give back: |
||
<lang |
<syntaxhighlight lang="mathematica">f[g[h[x]]]</syntaxhighlight> |
||
The built-in function has a couple of automatic simplifications: |
The built-in function has a couple of automatic simplifications: |
||
< |
<syntaxhighlight lang="mathematica">Composition[f, Identity, g] |
||
Composition[f, InverseFunction[f], h][x]</ |
Composition[f, InverseFunction[f], h][x]</syntaxhighlight> |
||
becomes: |
becomes: |
||
< |
<syntaxhighlight lang="mathematica">f[g[x]] |
||
h[x]</ |
h[x]</syntaxhighlight> |
||
=={{header|Maxima}}== |
=={{header|Maxima}}== |
||
< |
<syntaxhighlight lang="maxima">/* built-in */ |
||
load(to_poly_solver); |
load(to_poly_solver); |
||
Line 1,880: | Line 2,209: | ||
/* An implementation, to show a use of buildq */ |
/* An implementation, to show a use of buildq */ |
||
compose(f, g) := buildq([f, g], lambda([x], f(g(x))));</ |
compose(f, g) := buildq([f, g], lambda([x], f(g(x))));</syntaxhighlight> |
||
=={{header|min}}== |
=={{header|min}}== |
||
{{works with|min|0.19.3}} |
{{works with|min|0.19.3}} |
||
Since min is both [http://concatenative.org/wiki/view/Concatenative%20language concatenative] and homoiconic, function composition is equivalent to list concatenation. Example: |
Since min is both [http://concatenative.org/wiki/view/Concatenative%20language concatenative] and homoiconic, function composition is equivalent to list concatenation. Example: |
||
< |
<syntaxhighlight lang="min">(1 +) (2 *) concat print</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 1,892: | Line 2,221: | ||
=={{header|MiniScript}}== |
=={{header|MiniScript}}== |
||
< |
<syntaxhighlight lang="miniscript">funcA = function(x) |
||
return x * 10 |
return x * 10 |
||
end function |
end function |
||
Line 1,907: | Line 2,236: | ||
f = compose(@funcA, @funcB) |
f = compose(@funcA, @funcB) |
||
print f(3) // should be equal to (3+5)*10</ |
print f(3) // should be equal to (3+5)*10</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre>80</pre> |
<pre>80</pre> |
||
=={{header|Nemerle}}== |
=={{header|Nemerle}}== |
||
< |
<syntaxhighlight lang="nemerle">using System; |
||
using System.Console; |
using System.Console; |
||
using System.Math; |
using System.Math; |
||
Line 1,928: | Line 2,257: | ||
WriteLine(SinAsin(0.5)); |
WriteLine(SinAsin(0.5)); |
||
} |
} |
||
}</ |
}</syntaxhighlight> |
||
=={{header|Never}}== |
=={{header|Never}}== |
||
<syntaxhighlight lang="never"> |
|||
<lang Never> |
|||
func compose(f(i : int) -> int, g(i : int) -> int) -> (int) -> int |
func compose(f(i : int) -> int, g(i : int) -> int) -> (int) -> int |
||
{ |
{ |
||
Line 1,949: | Line 2,278: | ||
0 |
0 |
||
} |
} |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|NewLISP}}== |
=={{header|NewLISP}}== |
||
< |
<syntaxhighlight lang="newlisp">> (define (compose f g) (expand (lambda (x) (f (g x))) 'f 'g)) |
||
(lambda (f g) (expand (lambda (x) (f (g x))) 'f 'g)) |
(lambda (f g) (expand (lambda (x) (f (g x))) 'f 'g)) |
||
> ((compose sin asin) 0.5) |
> ((compose sin asin) 0.5) |
||
0.5 |
0.5 |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|Nim}}== |
=={{header|Nim}}== |
||
< |
<syntaxhighlight lang="nim">import sugar |
||
proc compose[A,B,C](f: |
proc compose[A,B,C](f: B -> C, g: A -> B): A -> C = (x: A) => f(g(x)) |
||
proc plustwo(x: int): int = x + 2 |
proc plustwo(x: int): int = x + 2 |
||
Line 1,968: | Line 2,297: | ||
var plusminustwo = compose(plustwo, minustwo) |
var plusminustwo = compose(plustwo, minustwo) |
||
echo plusminustwo(10)</ |
echo plusminustwo(10)</syntaxhighlight> |
||
=={{header|Objeck}}== |
=={{header|Objeck}}== |
||
< |
<syntaxhighlight lang="objeck"> |
||
bundle Default { |
bundle Default { |
||
class Test { |
class Test { |
||
Line 2,001: | Line 2,330: | ||
} |
} |
||
} |
} |
||
</syntaxhighlight> |
|||
</lang> |
|||
prints: 42 |
prints: 42 |
||
=={{header|ObjectIcon}}== |
|||
{{trans|Icon and Unicon}} |
|||
<syntaxhighlight lang="objecticon"># -*- ObjectIcon -*- |
|||
# |
|||
# The Rosetta Code function composition task, in Object Icon. |
|||
# Composition will result in a co-expression. |
|||
# |
|||
# Object Icon co-expressions are closures: they share the local |
|||
# variables of the context in which they are created. In Arizona Icon, |
|||
# co-expressions obtain only the *values* of those variables. However, |
|||
# this difference, despite its significance, is not really important |
|||
# to the notion of composition. |
|||
# |
|||
# This example is adapted from the Unicon implementation of the |
|||
# task. To simplify the example, I have removed support for string |
|||
# invocations. |
|||
# |
|||
import io |
|||
procedure main (arglist) |
|||
local f, g |
|||
# f gets a co-expression that is a composition of three procedures. |
|||
f := compose(append_exclamation, string_repeat, double_it) |
|||
write(123@f) |
|||
# g gets a co-expression that is a composition of a procedure and f. |
|||
g := compose(string_repeat, f) |
|||
write(123@g) |
|||
end |
|||
procedure double_it (n) |
|||
return n + n |
|||
end |
|||
procedure string_repeat (x) |
|||
return string(x) || string(x) |
|||
end |
|||
procedure append_exclamation (s) |
|||
return s || "!" |
|||
end |
|||
procedure compose (rfL[]) |
|||
local x, f, saveSource, fL, cf |
|||
every push(fL := [], !rfL) |
|||
cf := create { |
|||
saveSource := &source |
|||
repeat { |
|||
x := x@saveSource |
|||
saveSource := &source |
|||
every f := !fL do { |
|||
case type(f) of { |
|||
"co-expression": x := x@f |
|||
default: x := f(x) |
|||
} |
|||
} |
|||
} |
|||
} |
|||
# Co-expressions often need to be "primed" before they can be |
|||
# used. |
|||
@cf |
|||
return cf |
|||
end</syntaxhighlight> |
|||
{{out}} |
|||
<pre>$ oit -s function_composition-OI.icn && ./function_composition-OI |
|||
246246! |
|||
246246!246246!</pre> |
|||
=={{header|Objective-C}}== |
=={{header|Objective-C}}== |
||
Line 2,008: | Line 2,414: | ||
We restrict ourselves to functions that take and return one object. |
We restrict ourselves to functions that take and return one object. |
||
< |
<syntaxhighlight lang="objc">#include <Foundation/Foundation.h> |
||
typedef id (^Function)(id); |
typedef id (^Function)(id); |
||
Line 2,049: | Line 2,455: | ||
} |
} |
||
return 0; |
return 0; |
||
}</ |
}</syntaxhighlight> |
||
=={{header|OCaml}}== |
=={{header|OCaml}}== |
||
< |
<syntaxhighlight lang="ocaml">let compose f g x = f (g x)</syntaxhighlight> |
||
Example use: |
Example use: |
||
< |
<syntaxhighlight lang="ocaml"># let compose f g x = f (g x);; |
||
val compose : ('a -> 'b) -> ('c -> 'a) -> 'c -> 'b = <fun> |
val compose : ('a -> 'b) -> ('c -> 'a) -> 'c -> 'b = <fun> |
||
# let sin_asin = compose sin asin;; |
# let sin_asin = compose sin asin;; |
||
val sin_asin : float -> float = <fun> |
val sin_asin : float -> float = <fun> |
||
# sin_asin 0.5;; |
# sin_asin 0.5;; |
||
- : float = 0.5</ |
- : float = 0.5</syntaxhighlight> |
||
=={{header|Octave}}== |
=={{header|Octave}}== |
||
< |
<syntaxhighlight lang="octave">function r = compose(f, g) |
||
r = @(x) f(g(x)); |
r = @(x) f(g(x)); |
||
endfunction |
endfunction |
||
r = compose(@exp, @sin); |
r = compose(@exp, @sin); |
||
r(pi/3)</ |
r(pi/3)</syntaxhighlight> |
||
=={{header|Oforth}}== |
=={{header|Oforth}}== |
||
Oforth uses RPN notation. Function composition of f and g is just calling : |
Oforth uses RPN notation. Function composition of f and g is just calling : |
||
<lang |
<syntaxhighlight lang="oforth">g f</syntaxhighlight> |
||
If a block is needed, a compose function can be implemented : |
If a block is needed, a compose function can be implemented : |
||
< |
<syntaxhighlight lang="oforth">: compose(f, g) #[ g perform f perform ] ;</syntaxhighlight> |
||
Usage : |
Usage : |
||
< |
<syntaxhighlight lang="oforth">1.2 compose(#asin, #sin) perform |
||
[ 1, 2, 3, 4, 5 ] compose(#[ map(#sqrt) ], #[ filter(#isEven) ]) perform</ |
[ 1, 2, 3, 4, 5 ] compose(#[ map(#sqrt) ], #[ filter(#isEven) ]) perform</syntaxhighlight> |
||
The last line returns : [1.4142135623731, 2] |
The last line returns : [1.4142135623731, 2] |
||
=={{header|Ol}}== |
=={{header|Ol}}== |
||
< |
<syntaxhighlight lang="scheme"> |
||
(define (compose f g) |
(define (compose f g) |
||
(lambda (x) (f (g x)))) |
(lambda (x) (f (g x)))) |
||
Line 2,089: | Line 2,495: | ||
(define ((compose f g) x) (f (g x))) |
(define ((compose f g) x) (f (g x))) |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|Order}}== |
=={{header|Order}}== |
||
Order supplies the built-in function <code>8compose</code> for this purpose. However, a manual implementation might be: |
Order supplies the built-in function <code>8compose</code> for this purpose. However, a manual implementation might be: |
||
< |
<syntaxhighlight lang="c">#include <order/interpreter.h> |
||
#define ORDER_PP_DEF_8comp ORDER_PP_FN( \ |
#define ORDER_PP_DEF_8comp ORDER_PP_FN( \ |
||
8fn(8F, 8G, 8fn(8X, 8ap(8F, 8ap(8G, 8X)))) )</ |
8fn(8F, 8G, 8fn(8X, 8ap(8F, 8ap(8G, 8X)))) )</syntaxhighlight> |
||
Interpreter limitations mean that local variables containing functions must be called with the <code>8ap</code> operator, but the functions themselves are still first-class values. |
Interpreter limitations mean that local variables containing functions must be called with the <code>8ap</code> operator, but the functions themselves are still first-class values. |
||
=={{header|Oz}}== |
=={{header|Oz}}== |
||
< |
<syntaxhighlight lang="oz">declare |
||
fun {Compose F G} |
fun {Compose F G} |
||
fun {$ X} |
fun {$ X} |
||
Line 2,109: | Line 2,515: | ||
SinAsin = {Compose Float.sin Float.asin} |
SinAsin = {Compose Float.sin Float.asin} |
||
in |
in |
||
{Show {SinAsin 0.5}}</ |
{Show {SinAsin 0.5}}</syntaxhighlight> |
||
=={{header|PARI/GP}}== |
=={{header|PARI/GP}}== |
||
{{works with|PARI/GP|2.4.2 and above}} |
{{works with|PARI/GP|2.4.2 and above}} |
||
< |
<syntaxhighlight lang="parigp">compose(f, g)={ |
||
x -> f(g(x)) |
x -> f(g(x)) |
||
}; |
}; |
||
compose(x->sin(x),x->cos(x)(1)</ |
compose(x->sin(x),x->cos(x)(1)</syntaxhighlight> |
||
Usage note: In Pari/GP 2.4.3, this can be expressed more succinctly: |
Usage note: In Pari/GP 2.4.3, this can be expressed more succinctly: |
||
<lang |
<syntaxhighlight lang="parigp">compose(sin,cos)(1)</syntaxhighlight> |
||
=={{header|Pascal}}== |
=={{header|Pascal}}== |
||
Line 2,126: | Line 2,532: | ||
=={{header|Perl}}== |
=={{header|Perl}}== |
||
< |
<syntaxhighlight lang="perl">sub compose { |
||
my ($f, $g) = @_; |
my ($f, $g) = @_; |
||
Line 2,135: | Line 2,541: | ||
use Math::Trig; |
use Math::Trig; |
||
print compose(sub {sin $_[0]}, \&asin)->(0.5), "\n";</ |
print compose(sub {sin $_[0]}, \&asin)->(0.5), "\n";</syntaxhighlight> |
||
=={{header|Phix}}== |
=={{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> |
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, you cannot use constant m in the same way as a routine_id, or pass a standard routine_id to call_composite(), but tagging the ctable entries so that you know precisely what to do with each entry does not sound the least bit difficult to me. |
In the following, as it stands, you cannot use constant m in the same way as a routine_id, or pass a standard routine_id to call_composite(), but tagging the ctable entries so that you know precisely what to do with each entry does not sound the least bit difficult to me. |
||
<!--< |
<!--<syntaxhighlight lang="phix">--> |
||
<span style="color: #004080;">sequence</span> <span style="color: #000000;">ctable</span> <span style="color: #0000FF;">=</span> <span style="color: #0000FF;">{<span style="color: #0000FF;">}</span> |
<span style="color: #004080;">sequence</span> <span style="color: #000000;">ctable</span> <span style="color: #0000FF;">=</span> <span style="color: #0000FF;">{<span style="color: #0000FF;">}</span> |
||
Line 2,166: | Line 2,572: | ||
<span style="color: #0000FF;">?<span style="color: #000000;">call_composite<span style="color: #0000FF;">(<span style="color: #000000;">m<span style="color: #0000FF;">,<span style="color: #000000;">1<span style="color: #0000FF;">)</span> <span style="color: #000080;font-style:italic;">-- displays 1</span> |
<span style="color: #0000FF;">?<span style="color: #000000;">call_composite<span style="color: #0000FF;">(<span style="color: #000000;">m<span style="color: #0000FF;">,<span style="color: #000000;">1<span style="color: #0000FF;">)</span> <span style="color: #000080;font-style:italic;">-- displays 1</span> |
||
<span style="color: #0000FF;">?<span style="color: #000000;">call_composite<span style="color: #0000FF;">(<span style="color: #000000;">m<span style="color: #0000FF;">,<span style="color: #000000;">4<span style="color: #0000FF;">)</span> <span style="color: #000080;font-style:italic;">-- displays 2.5 |
<span style="color: #0000FF;">?<span style="color: #000000;">call_composite<span style="color: #0000FF;">(<span style="color: #000000;">m<span style="color: #0000FF;">,<span style="color: #000000;">4<span style="color: #0000FF;">)</span> <span style="color: #000080;font-style:italic;">-- displays 2.5 |
||
<!--</ |
<!--</syntaxhighlight>--> |
||
=={{header|Phixmonti}}== |
=={{header|Phixmonti}}== |
||
< |
<syntaxhighlight lang="phixmonti">def *2 2 * enddef |
||
def ++ 1 + enddef |
def ++ 1 + enddef |
||
def composite swap exec swap exec enddef |
def composite swap exec swap exec enddef |
||
getid ++ getid *2 3 composite print /# result: 7 #/</ |
getid ++ getid *2 3 composite print /# result: 7 #/</syntaxhighlight> |
||
=={{header|PHP}}== |
=={{header|PHP}}== |
||
{{works with|PHP|5.3+}} |
{{works with|PHP|5.3+}} |
||
< |
<syntaxhighlight lang="php"><?php |
||
function compose($f, $g) { |
function compose($f, $g) { |
||
return function($x) use ($f, $g) { return $f($g($x)); }; |
return function($x) use ($f, $g) { return $f($g($x)); }; |
||
Line 2,184: | Line 2,590: | ||
$trim_strlen = compose('strlen', 'trim'); |
$trim_strlen = compose('strlen', 'trim'); |
||
echo $result = $trim_strlen(' Test '), "\n"; // prints 4 |
echo $result = $trim_strlen(' Test '), "\n"; // prints 4 |
||
?></ |
?></syntaxhighlight> |
||
{{works with|PHP|pre-5.3 and 5.3+}} |
{{works with|PHP|pre-5.3 and 5.3+}} |
||
works with regular functions as well as functions created by <tt>create_function()</tt> |
works with regular functions as well as functions created by <tt>create_function()</tt> |
||
< |
<syntaxhighlight lang="php"><?php |
||
function compose($f, $g) { |
function compose($f, $g) { |
||
return create_function('$x', 'return '.var_export($f,true).'('.var_export($g,true).'($x));'); |
return create_function('$x', 'return '.var_export($f,true).'('.var_export($g,true).'($x));'); |
||
Line 2,195: | Line 2,601: | ||
$trim_strlen = compose('strlen', 'trim'); |
$trim_strlen = compose('strlen', 'trim'); |
||
echo $result = $trim_strlen(' Test '), "\n"; // prints 4 |
echo $result = $trim_strlen(' Test '), "\n"; // prints 4 |
||
?></ |
?></syntaxhighlight> |
||
=={{header|PicoLisp}}== |
=={{header|PicoLisp}}== |
||
< |
<syntaxhighlight lang="picolisp">(de compose (F G) |
||
(curry (F G) (X) |
(curry (F G) (X) |
||
(F (G X)) ) )</ |
(F (G X)) ) )</syntaxhighlight> |
||
< |
<syntaxhighlight lang="picolisp">(def 'a (compose inc dec)) |
||
(def 'b (compose 'inc 'dec)) |
(def 'b (compose 'inc 'dec)) |
||
(def 'c (compose '((A) (inc A)) '((B) (dec B))))</ |
(def 'c (compose '((A) (inc A)) '((B) (dec B))))</syntaxhighlight> |
||
< |
<syntaxhighlight lang="picolisp">: (a 7) |
||
-> 7 |
-> 7 |
||
Line 2,211: | Line 2,617: | ||
: (c 7) |
: (c 7) |
||
-> 7</ |
-> 7</syntaxhighlight> |
||
=={{header|PostScript}}== |
=={{header|PostScript}}== |
||
<syntaxhighlight lang="postscript"> |
|||
<lang PostScript> |
|||
/compose { % f g -> { g f } |
/compose { % f g -> { g f } |
||
[ 3 1 roll exch |
[ 3 1 roll exch |
||
Line 2,227: | Line 2,633: | ||
/plus1 { 1 add } def |
/plus1 { 1 add } def |
||
/sqPlus1 /square load /plus1 load compose def |
/sqPlus1 /square load /plus1 load compose def |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|PowerShell}}== |
=={{header|PowerShell}}== |
||
You can simply call g inside f like this: |
You can simply call g inside f like this: |
||
<syntaxhighlight lang="powershell"> |
|||
<lang PowerShell> |
|||
function g ($x) { |
function g ($x) { |
||
$x + $x |
$x + $x |
||
Line 2,239: | Line 2,645: | ||
} |
} |
||
f (g 1) |
f (g 1) |
||
</syntaxhighlight> |
|||
</lang> |
|||
Or g and f can become paramaters of a new function fg |
Or g and f can become paramaters of a new function fg |
||
<syntaxhighlight lang="powershell"> |
|||
<lang PowerShell> |
|||
function fg (${function:f}, ${function:g}, $x) { |
function fg (${function:f}, ${function:g}, $x) { |
||
f (g $x) |
f (g $x) |
||
} |
} |
||
fg f g 1 |
fg f g 1 |
||
</syntaxhighlight> |
|||
</lang> |
|||
In both cases the answer is: |
In both cases the answer is: |
||
Line 2,255: | Line 2,661: | ||
=={{header|Prolog}}== |
=={{header|Prolog}}== |
||
Works with SWI-Prolog and module lambda, written by <b>Ulrich Neumerkel</b> found there http://www.complang.tuwien.ac.at/ulrich/Prolog-inedit/lambda.pl |
Works with SWI-Prolog and module lambda, written by <b>Ulrich Neumerkel</b> found there http://www.complang.tuwien.ac.at/ulrich/Prolog-inedit/lambda.pl |
||
< |
<syntaxhighlight lang="prolog">:- use_module(lambda). |
||
compose(F,G, FG) :- |
compose(F,G, FG) :- |
||
FG = \X^Z^(call(G,X,Y), call(F,Y,Z)). |
FG = \X^Z^(call(G,X,Y), call(F,Y,Z)). |
||
</syntaxhighlight> |
|||
</lang> |
|||
{{out}} |
{{out}} |
||
<pre> ?- compose(sin, asin, F), call(F, 0.5, Y). |
<pre> ?- compose(sin, asin, F), call(F, 0.5, Y). |
||
Line 2,267: | Line 2,673: | ||
=={{header|PureBasic}}== |
=={{header|PureBasic}}== |
||
< |
<syntaxhighlight lang="purebasic">;Declare how our function looks like |
||
Prototype.i Func(Arg.i) |
Prototype.i Func(Arg.i) |
||
Line 2,289: | Line 2,695: | ||
Title$="With x="+Str(x) |
Title$="With x="+Str(x) |
||
Body$="Compose(f(),g(), x) ="+Str(Compose(@f(),@g(),X)) |
Body$="Compose(f(),g(), x) ="+Str(Compose(@f(),@g(),X)) |
||
MessageRequester(Title$,Body$)</ |
MessageRequester(Title$,Body$)</syntaxhighlight> |
||
=={{header|Purity}}== |
=={{header|Purity}}== |
||
<syntaxhighlight lang="purity"> |
|||
<lang Purity> |
|||
data compose = f => g => $f . $g |
data compose = f => g => $f . $g |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|Python}}== |
=={{header|Python}}== |
||
===Simple composition of two functions=== |
===Simple composition of two functions=== |
||
< |
<syntaxhighlight lang="python">compose = lambda f, g: lambda x: f( g(x) )</syntaxhighlight> |
||
Example use: |
Example use: |
||
< |
<syntaxhighlight lang="python">>>> compose = lambda f, g: lambda x: f( g(x) ) |
||
>>> from math import sin, asin |
>>> from math import sin, asin |
||
>>> sin_asin = compose(sin, asin) |
>>> sin_asin = compose(sin, asin) |
||
>>> sin_asin(0.5) |
>>> sin_asin(0.5) |
||
0.5 |
0.5 |
||
>>></ |
>>></syntaxhighlight> |
||
Or, expanding slightly: |
Or, expanding slightly: |
||
{{Works with|Python|3}} |
{{Works with|Python|3}} |
||
< |
<syntaxhighlight lang="python">from math import (acos, cos, asin, sin) |
||
Line 2,345: | Line 2,751: | ||
if __name__ == '__main__': |
if __name__ == '__main__': |
||
main()</ |
main()</syntaxhighlight> |
||
{{Out}} |
{{Out}} |
||
<pre>[0.49999999999999994, 0.5000000000000001, 0.5000000000000001]</pre> |
<pre>[0.49999999999999994, 0.5000000000000001, 0.5000000000000001]</pre> |
||
Line 2,353: | Line 2,759: | ||
{{Works with|Python|3}} |
{{Works with|Python|3}} |
||
< |
<syntaxhighlight lang="python">from functools import reduce |
||
from |
from math import sqrt |
||
import math |
|||
def compose(*fs): |
|||
'''Composition, from right to left, |
|||
of an arbitrary number of functions. |
|||
''' |
|||
def go(f, g): |
|||
return lambda x: f(g(x)) |
|||
return reduce(go, fs, lambda x: x) |
|||
# ------------------------- TEST ------------------------- |
|||
def main(): |
def main(): |
||
''' |
'''Composition of three functions.''' |
||
f = |
f = compose( |
||
half, |
|||
succ, |
succ, |
||
sqrt |
|||
) |
|||
print( |
print( |
||
Line 2,372: | Line 2,788: | ||
# |
# ----------------------- GENERAL ------------------------ |
||
def half(n): |
|||
return n / 2 |
|||
def succ(n): |
|||
# composeList :: [(a -> a)] -> (a -> a) |
|||
return 1 + n |
|||
def composeList(fs): |
|||
'''Composition, from right to left, |
|||
of a series of functions.''' |
|||
return lambda x: reduce( |
|||
lambda a, f: f(a), |
|||
fs[::-1], |
|||
x |
|||
) |
|||
# succ :: Enum a => a -> a |
|||
def succ(x): |
|||
'''The successor of a value. For numeric types, (1 +).''' |
|||
return 1 + x if isinstance(x, Number) else ( |
|||
chr(1 + ord(x)) |
|||
) |
|||
if __name__ == '__main__': |
if __name__ == '__main__': |
||
main()</ |
main()</syntaxhighlight> |
||
{{Out}} |
{{Out}} |
||
<pre>1.618033988749895</pre> |
<pre>1.618033988749895</pre> |
||
=== composition via operator overloading=== |
=== composition via operator overloading=== |
||
Here need composition of several functions is reduced with classes. |
Here need composition of several functions is reduced with classes. |
||
{{Works with|Python|3}} |
{{Works with|Python|3}} |
||
< |
<syntaxhighlight lang="python"> |
||
# Contents of `pip install compositions' |
# Contents of `pip install compositions' |
||
Line 2,426: | Line 2,828: | ||
g = Compose(lambda x: x) |
g = Compose(lambda x: x) |
||
print((f * g)(2))</ |
print((f * g)(2))</syntaxhighlight> |
||
=={{header|Qi}}== |
=={{header|Qi}}== |
||
Qi supports partial applications, but only when calling a function with one argument. |
Qi supports partial applications, but only when calling a function with one argument. |
||
<syntaxhighlight lang="qi"> |
|||
<lang qi> |
|||
(define compose |
(define compose |
||
F G -> (/. X |
F G -> (/. X |
||
Line 2,436: | Line 2,838: | ||
((compose (+ 1) (+ 2)) 3) \ (Outputs 6) \ |
((compose (+ 1) (+ 2)) 3) \ (Outputs 6) \ |
||
</syntaxhighlight> |
|||
</lang> |
|||
Alternatively, it can be done like this: |
Alternatively, it can be done like this: |
||
<syntaxhighlight lang="qi"> |
|||
<lang qi> |
|||
(define compose F G X -> (F (G X))) |
(define compose F G X -> (F (G X))) |
||
(((compose (+ 1)) (+ 2)) 3) \ (Outputs 6) \ |
(((compose (+ 1)) (+ 2)) 3) \ (Outputs 6) \ |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|Quackery}}== |
=={{header|Quackery}}== |
||
< |
<syntaxhighlight lang="quackery"> [ nested swap |
||
nested swap join ] is compose ( g f --> [ ) |
nested swap join ] is compose ( g f --> [ ) |
||
Line 2,465: | Line 2,867: | ||
19 ' double ' [ 4 + ] compose do echo |
19 ' double ' [ 4 + ] compose do echo |
||
</syntaxhighlight> |
|||
</lang> |
|||
{{out}} |
{{out}} |
||
Line 2,472: | Line 2,874: | ||
=={{header|R}}== |
=={{header|R}}== |
||
< |
<syntaxhighlight lang="r">compose <- function(f,g) function(x) { f(g(x)) } |
||
r <- compose(sin, cos) |
r <- compose(sin, cos) |
||
print(r(.5))</ |
print(r(.5))</syntaxhighlight> |
||
=={{header|Racket}}== |
=={{header|Racket}}== |
||
< |
<syntaxhighlight lang="racket"> |
||
(define (compose f g) |
(define (compose f g) |
||
(lambda (x) (f (g x)))) |
(lambda (x) (f (g x)))) |
||
</syntaxhighlight> |
|||
</lang> |
|||
Also available as a <tt>compose1</tt> builtin, and a more general <tt>compose</tt> where one function can produce multiple arguments that are sent the the next function in the chain. (Note however that this is rarely desired.) |
Also available as a <tt>compose1</tt> builtin, and a more general <tt>compose</tt> where one function can produce multiple arguments that are sent the the next function in the chain. (Note however that this is rarely desired.) |
||
Line 2,488: | Line 2,890: | ||
{{works with|rakudo|2018.03}} |
{{works with|rakudo|2018.03}} |
||
The function composition operator is <tt>∘</tt>, U+2218 RING OPERATOR (with a "Texas" version <tt>o</tt> for the Unicode challenged). Here we compose a routine, an operator, and a lambda: |
The function composition operator is <tt>∘</tt>, U+2218 RING OPERATOR (with a "Texas" version <tt>o</tt> for the Unicode challenged). Here we compose a routine, an operator, and a lambda: |
||
<lang |
<syntaxhighlight lang="raku" line>sub triple($n) { 3 * $n } |
||
my &f = &triple ∘ &prefix:<-> ∘ { $^n + 2 }; |
my &f = &triple ∘ &prefix:<-> ∘ { $^n + 2 }; |
||
say &f(5); # prints "-21".</ |
say &f(5); # prints "-21".</syntaxhighlight> |
||
=={{header|REBOL}}== |
=={{header|REBOL}}== |
||
< |
<syntaxhighlight lang="rebol">REBOL [ |
||
Title: "Functional Composition" |
Title: "Functional Composition" |
||
URL: http://rosettacode.org/wiki/Functional_Composition |
URL: http://rosettacode.org/wiki/Functional_Composition |
||
Line 2,506: | Line 2,908: | ||
] [ |
] [ |
||
func [x] compose [(:f) (:g) x] |
func [x] compose [(:f) (:g) x] |
||
]</ |
]</syntaxhighlight> |
||
Functions "foo" and "bar" are used to prove that composition |
Functions "foo" and "bar" are used to prove that composition |
||
actually took place by attaching their signatures to the result. |
actually took place by attaching their signatures to the result. |
||
< |
<syntaxhighlight lang="rebol">foo: func [x] [reform ["foo:" x]] |
||
bar: func [x] [reform ["bar:" x]] |
bar: func [x] [reform ["bar:" x]] |
||
Line 2,518: | Line 2,920: | ||
sin-asin: compose-functions :sine :arcsine |
sin-asin: compose-functions :sine :arcsine |
||
print [crlf "Composition of sine and arcsine:" sin-asin 0.5]</ |
print [crlf "Composition of sine and arcsine:" sin-asin 0.5]</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 2,526: | Line 2,928: | ||
=={{header|REXX}}== |
=={{header|REXX}}== |
||
< |
<syntaxhighlight lang="rexx">compose: procedure; parse arg f,g,x; interpret 'return' f"(" g'(' x "))" |
||
exit /*control should never gets here, but this was added just in case.*/</ |
exit /*control should never gets here, but this was added just in case.*/</syntaxhighlight> |
||
=={{header|Ring}}== |
=={{header|Ring}}== |
||
< |
<syntaxhighlight lang="ring"> |
||
# Project : Function composition |
# Project : Function composition |
||
Line 2,545: | Line 2,947: | ||
res = x * y |
res = x * y |
||
return res |
return res |
||
</syntaxhighlight> |
|||
</lang> |
|||
Output: |
Output: |
||
<pre> |
<pre> |
||
11 |
11 |
||
</pre> |
|||
=={{header|RPL}}== |
|||
{{works with|HP|48G}} |
|||
« →STR SWAP →STR + |
|||
DUP "»«" POS " " REPL STR→ |
|||
» '<span style="color:blue">FCOMP</span>' STO <span style="color:grey">@ ''( « f » « g » → « f o g » )''</span> |
|||
≪ ALOG ≫ ≪ COS ≫ <span style="color:blue">FCOMP</span> |
|||
≪ ALOG ≫ ≪ COS ≫ <span style="color:blue">FCOMP</span> 0 EVAL |
|||
≪ ALOG ≫ ≪ COS ≫ <span style="color:blue">FCOMP</span> 'x' EVAL |
|||
{{out}} |
|||
<pre> |
|||
3: ≪ COS ALOG ≫ |
|||
2: 10 |
|||
1: 'ALOG(COS(x))' |
|||
</pre> |
</pre> |
||
=={{header|Ruby}}== |
=={{header|Ruby}}== |
||
This <tt>compose</tt> method gets passed two Method objects or Proc objects |
This <tt>compose</tt> method gets passed two Method objects or Proc objects |
||
< |
<syntaxhighlight lang="ruby">def compose(f,g) |
||
lambda {|x| f[g[x]]} |
lambda {|x| f[g[x]]} |
||
end |
end |
||
Line 2,560: | Line 2,978: | ||
# verify |
# verify |
||
p Math.sin(Math.cos(0.5)) # => 0.769196354841008</ |
p Math.sin(Math.cos(0.5)) # => 0.769196354841008</syntaxhighlight> |
||
=={{header|Rust}}== |
=={{header|Rust}}== |
||
Line 2,567: | Line 2,985: | ||
===Stable=== |
===Stable=== |
||
Function is allocated on the heap and is called via dynamic dispatch |
Function is allocated on the heap and is called via dynamic dispatch |
||
< |
<syntaxhighlight lang="rust">fn compose<'a,F,G,T,U,V>(f: F, g: G) -> Box<Fn(T) -> V + 'a> |
||
where F: Fn(U) -> V + 'a, |
where F: Fn(U) -> V + 'a, |
||
G: Fn(T) -> U + 'a, |
G: Fn(T) -> U + 'a, |
||
{ |
{ |
||
Box::new(move |x| f(g(x))) |
Box::new(move |x| f(g(x))) |
||
}</ |
}</syntaxhighlight> |
||
===Nightly=== |
===Nightly=== |
||
Function is returned on the stack and is called via static dispatch (monomorphized) |
Function is returned on the stack and is called via static dispatch (monomorphized) |
||
< |
<syntaxhighlight lang="rust">#![feature(conservative_impl_trait)] |
||
fn compose<'a,F,G,T,U,V>(f: F, g: G) -> impl Fn(T) -> V + 'a |
fn compose<'a,F,G,T,U,V>(f: F, g: G) -> impl Fn(T) -> V + 'a |
||
where F: Fn(U) -> V + 'a, |
where F: Fn(U) -> V + 'a, |
||
Line 2,582: | Line 3,000: | ||
{ |
{ |
||
move |x| f(g(x)) |
move |x| f(g(x)) |
||
}</ |
}</syntaxhighlight> |
||
=={{header|Scala}}== |
=={{header|Scala}}== |
||
< |
<syntaxhighlight lang="scala">def compose[A](f: A => A, g: A => A) = { x: A => f(g(x)) } |
||
def add1(x: Int) = x+1 |
def add1(x: Int) = x+1 |
||
val add2 = compose(add1, add1)</ |
val add2 = compose(add1, add1)</syntaxhighlight> |
||
We can achieve a more natural style by creating a container class for composable functions, which provides |
We can achieve a more natural style by creating a container class for composable functions, which provides |
||
the compose method 'o': |
the compose method 'o': |
||
< |
<syntaxhighlight lang="scala">class Composable[A](f: A => A) { |
||
def o (g: A => A) = compose(f, g) |
def o (g: A => A) = compose(f, g) |
||
} |
} |
||
Line 2,599: | Line 3,017: | ||
implicit def toComposable[A](f: A => A) = new Composable(f) |
implicit def toComposable[A](f: A => A) = new Composable(f) |
||
val add3 = (add1 _) o add2</ |
val add3 = (add1 _) o add2</syntaxhighlight> |
||
<pre> |
<pre> |
||
Line 2,607: | Line 3,025: | ||
=={{header|Scheme}}== |
=={{header|Scheme}}== |
||
< |
<syntaxhighlight lang="scheme">(define (compose f g) (lambda (x) (f (g x)))) |
||
;; or: |
;; or: |
||
Line 2,622: | Line 3,040: | ||
((_ f g h ...) #'(lambda (y) (f ((compose g h ...) y))))))) |
((_ f g h ...) #'(lambda (y) (f ((compose g h ...) y))))))) |
||
</syntaxhighlight> |
|||
</lang> |
|||
Example: |
Example: |
||
< |
<syntaxhighlight lang="scheme"> |
||
(display ((compose sin asin) 0.5)) |
(display ((compose sin asin) 0.5)) |
||
(newline)</ |
(newline)</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<lang>0.5</ |
<syntaxhighlight lang="text">0.5</syntaxhighlight> |
||
=={{header|Sidef}}== |
=={{header|Sidef}}== |
||
< |
<syntaxhighlight lang="ruby">func compose(f, g) { |
||
func(x) { f(g(x)) } |
func(x) { f(g(x)) } |
||
} |
} |
||
var fg = compose(func(x){ sin(x) }, func(x){ cos(x) }) |
var fg = compose(func(x){ sin(x) }, func(x){ cos(x) }) |
||
say fg(0.5) # => 0.76919635484100842185251475805107</ |
say fg(0.5) # => 0.76919635484100842185251475805107</syntaxhighlight> |
||
=={{header|Slate}}== |
=={{header|Slate}}== |
||
Function (method) composition is standard: |
Function (method) composition is standard: |
||
< |
<syntaxhighlight lang="slate">[| :x | x + 1] ** [| :x | x squared] applyTo: {3}</syntaxhighlight> |
||
=={{header|Smalltalk}}== |
=={{header|Smalltalk}}== |
||
< |
<syntaxhighlight lang="smalltalk">| composer fg | |
||
composer := [ :f :g | [ :x | f value: (g value: x) ] ]. |
composer := [ :f :g | [ :x | f value: (g value: x) ] ]. |
||
fg := composer value: [ :x | x + 1 ] |
fg := composer value: [ :x | x + 1 ] |
||
value: [ :x | x * x ]. |
value: [ :x | x * x ]. |
||
(fg value:3) displayNl.</ |
(fg value:3) displayNl.</syntaxhighlight> |
||
=={{header|Standard ML}}== |
=={{header|Standard ML}}== |
||
This is already defined as the '''o''' operator in Standard ML. |
This is already defined as the '''o''' operator in Standard ML. |
||
< |
<syntaxhighlight lang="sml">fun compose (f, g) x = f (g x)</syntaxhighlight> |
||
Example use: |
Example use: |
||
< |
<syntaxhighlight lang="sml">- fun compose (f, g) x = f (g x); |
||
val compose = fn : ('a -> 'b) * ('c -> 'a) -> 'c -> 'b |
val compose = fn : ('a -> 'b) * ('c -> 'a) -> 'c -> 'b |
||
- val sin_asin = compose (Math.sin, Math.asin); |
- val sin_asin = compose (Math.sin, Math.asin); |
||
val sin_asin = fn : real -> real |
val sin_asin = fn : real -> real |
||
- sin_asin 0.5; |
- sin_asin 0.5; |
||
val it = 0.5 : real</ |
val it = 0.5 : real</syntaxhighlight> |
||
=={{header|SuperCollider}}== |
=={{header|SuperCollider}}== |
||
has a function composition operator (the message `<>`): |
has a function composition operator (the message `<>`): |
||
<syntaxhighlight lang="supercollider"> |
|||
<lang SuperCollider> |
|||
f = { |x| x + 1 }; |
f = { |x| x + 1 }; |
||
g = { |x| x * 2 }; |
g = { |x| x * 2 }; |
||
h = g <> f; |
h = g <> f; |
||
h.(8); // returns 18 |
h.(8); // returns 18 |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|Swift}}== |
=={{header|Swift}}== |
||
< |
<syntaxhighlight lang="swift">func compose<A,B,C>(f: (B) -> C, g: (A) -> B) -> (A) -> C { |
||
return { f(g($0)) } |
return { f(g($0)) } |
||
} |
} |
||
let sin_asin = compose(sin, asin) |
let sin_asin = compose(sin, asin) |
||
println(sin_asin(0.5))</ |
println(sin_asin(0.5))</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 2,685: | Line 3,103: | ||
{{works with|Tcl|8.5}} |
{{works with|Tcl|8.5}} |
||
This creates a <code>compose</code> procedure that returns an anonymous function term that should be expanded as part of application to its argument. |
This creates a <code>compose</code> procedure that returns an anonymous function term that should be expanded as part of application to its argument. |
||
< |
<syntaxhighlight lang="tcl">package require Tcl 8.5 |
||
namespace path {::tcl::mathfunc} |
namespace path {::tcl::mathfunc} |
||
Line 2,694: | Line 3,112: | ||
set sin_asin [compose sin asin] |
set sin_asin [compose sin asin] |
||
{*}$sin_asin 0.5 ;# ==> 0.5 |
{*}$sin_asin 0.5 ;# ==> 0.5 |
||
{*}[compose abs int] -3.14 ;# ==> 3</ |
{*}[compose abs int] -3.14 ;# ==> 3</syntaxhighlight> |
||
=={{header|Transd}}== |
|||
<syntaxhighlight lang="Scheme">#lang transd |
|||
MainModule: { |
|||
// Make a short alias for a function type that takes a string and |
|||
// returns a string. Call it 'Shader'. |
|||
Shader: typealias(Lambda<String String>), |
|||
// 'composer' function takes two Shaders, combines them into |
|||
// a single Shader, which is a capturing closure, аnd returns |
|||
// this closure to the caller. |
|||
// [[f1,f2]] is a list of captured variables |
|||
composer: (λ f1 Shader() f2 Shader() |
|||
(ret Shader(λ[[f1,f2]] s String() (exec f1 (exec f2 s))))), |
|||
_start: (λ |
|||
// create a combined shader as a local variable 'render' |
|||
locals: render (composer |
|||
Shader(λ s String() (ret (toupper s))) |
|||
Shader(λ s String() (ret (+ s "!")))) |
|||
// call this combined shader as a usual shader with passing |
|||
// a string to it, аnd receiving from it the combined result of |
|||
// its two captured shaders |
|||
(textout (exec render "hello"))) |
|||
}</syntaxhighlight> |
|||
{{out}} |
|||
<pre> |
|||
HELLO! |
|||
</pre> |
|||
=={{header|TypeScript}}== |
=={{header|TypeScript}}== |
||
<syntaxhighlight lang="typescript"> |
|||
<lang TypeScript> |
|||
function compose<T, U, V> (fn1: (input: T) => U, fn2: (input: U) => V){ |
function compose<T, U, V> (fn1: (input: T) => U, fn2: (input: U) => V){ |
||
return function(value: T) { |
return function(value: T) { |
||
Line 2,712: | Line 3,165: | ||
console.log(evenSize("ABCD")) // true |
console.log(evenSize("ABCD")) // true |
||
console.log(evenSize("ABC")) // false |
console.log(evenSize("ABC")) // false |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|uBasic/4tH}}== |
|||
<syntaxhighlight lang="text">Print FUNC(_Compose (_f, _g, 3)) |
|||
End |
|||
_Compose Param (3) : Return (FUNC(a@(FUNC(b@(c@))))) |
|||
_f Param (1) : Return (a@ + 1) |
|||
_g Param (1) : Return (a@ * 2)</syntaxhighlight> |
|||
=={{header|UNIX Shell}}== |
=={{header|UNIX Shell}}== |
||
Line 2,720: | Line 3,181: | ||
{{works with|Bourne Shell}} |
{{works with|Bourne Shell}} |
||
< |
<syntaxhighlight lang="bash">compose() { |
||
eval "$1() { $3 | $2; }" |
eval "$1() { $3 | $2; }" |
||
} |
} |
||
Line 2,728: | Line 3,189: | ||
compose c downvowel upcase |
compose c downvowel upcase |
||
echo 'Cozy lummox gives smart squid who asks for job pen.' | c |
echo 'Cozy lummox gives smart squid who asks for job pen.' | c |
||
# => CoZY LuMMoX GiVeS SMaRT SQuiD WHo aSKS FoR JoB PeN.</ |
# => CoZY LuMMoX GiVeS SMaRT SQuiD WHo aSKS FoR JoB PeN.</syntaxhighlight> |
||
{{works with|Bourne Again SHell}} |
{{works with|Bourne Again SHell}} |
||
This solution uses no external tools, just Bash itself. |
This solution uses no external tools, just Bash itself. |
||
< |
<syntaxhighlight lang="bash"> |
||
#compose a new function consisting of the application of 2 unary functions |
#compose a new function consisting of the application of 2 unary functions |
||
Line 2,870: | Line 3,331: | ||
compose strdownvowel strupcase "Cozy lummox gives smart squid who asks for job pen." |
compose strdownvowel strupcase "Cozy lummox gives smart squid who asks for job pen." |
||
# --> CoZY LuMMoX GiVeS SMaRT SQuiD WHo aSKS FoR JoB PeN.</ |
# --> CoZY LuMMoX GiVeS SMaRT SQuiD WHo aSKS FoR JoB PeN.</syntaxhighlight> |
||
Line 2,876: | Line 3,337: | ||
With shell pipelines: |
With shell pipelines: |
||
< |
<syntaxhighlight lang="es">fn compose f g { |
||
result @ {$g | $f} |
result @ {$g | $f} |
||
} |
} |
||
Line 2,884: | Line 3,345: | ||
fn-c = <={compose $fn-downvowel $fn-upcase} |
fn-c = <={compose $fn-downvowel $fn-upcase} |
||
echo 'Cozy lummox gives smart squid who asks for job pen.' | c |
echo 'Cozy lummox gives smart squid who asks for job pen.' | c |
||
# => CoZY LuMMoX GiVeS SMaRT SQuiD WHo aSKS FoR JoB PeN.</ |
# => CoZY LuMMoX GiVeS SMaRT SQuiD WHo aSKS FoR JoB PeN.</syntaxhighlight> |
||
With function arguments: |
With function arguments: |
||
< |
<syntaxhighlight lang="es">fn compose f g { |
||
result @ x {result <={$f <={$g $x}}} |
result @ x {result <={$f <={$g $x}}} |
||
} |
} |
||
Line 2,896: | Line 3,357: | ||
fn-c = <={compose $fn-downvowel $fn-upcase} |
fn-c = <={compose $fn-downvowel $fn-upcase} |
||
echo <={c 'Cozy lummox gives smart squid who asks for job pen.'} |
echo <={c 'Cozy lummox gives smart squid who asks for job pen.'} |
||
# => CoZY LuMMoX GiVeS SMaRT SQuiD WHo aSKS FoR JoB PeN.</ |
# => CoZY LuMMoX GiVeS SMaRT SQuiD WHo aSKS FoR JoB PeN.</syntaxhighlight> |
||
=={{header|Unlambda}}== |
=={{header|Unlambda}}== |
||
Line 2,907: | Line 3,368: | ||
for functions f and g, hence hardly worth defining. However, it could |
for functions f and g, hence hardly worth defining. However, it could |
||
be defined without using the operator like this. |
be defined without using the operator like this. |
||
< |
<syntaxhighlight lang="ursala">compose("f","g") "x" = "f" "g" "x"</syntaxhighlight> |
||
test program: |
test program: |
||
< |
<syntaxhighlight lang="ursala">#import nat |
||
#cast %n |
#cast %n |
||
test = compose(successor,double) 3</ |
test = compose(successor,double) 3</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre>7</pre> |
<pre>7</pre> |
||
Line 2,923: | Line 3,384: | ||
'''Implementation''' |
'''Implementation''' |
||
<syntaxhighlight lang="vb"> |
|||
<lang vb> |
|||
option explicit |
option explicit |
||
class closure |
class closure |
||
Line 2,942: | Line 3,403: | ||
end class |
end class |
||
</syntaxhighlight> |
|||
</lang> |
|||
'''Invocation''' |
'''Invocation''' |
||
<syntaxhighlight lang="vb"> |
|||
<lang vb> |
|||
dim c |
dim c |
||
set c = new closure |
set c = new closure |
||
Line 2,972: | Line 3,433: | ||
wscript.echo c.formula |
wscript.echo c.formula |
||
wscript.echo c(12.3) |
wscript.echo c(12.3) |
||
</syntaxhighlight> |
|||
</lang> |
|||
{{out}} |
{{out}} |
||
Line 2,990: | Line 3,451: | ||
The simplest way is with a lambda: |
The simplest way is with a lambda: |
||
< |
<syntaxhighlight lang="wdte">let compose f g => (@ c x => g x -> f);</syntaxhighlight> |
||
Alternatively, you can take advantage of partial function calls: |
Alternatively, you can take advantage of partial function calls: |
||
< |
<syntaxhighlight lang="wdte">let compose f g x => g x -> f;</syntaxhighlight> |
||
Both can be used as follows: |
Both can be used as follows: |
||
< |
<syntaxhighlight lang="wdte">(compose (io.writeln io.stdout) !) true;</syntaxhighlight> |
||
Output: |
Output: |
||
<lang |
<syntaxhighlight lang="wdte">false</syntaxhighlight> |
||
=={{header|Wortel}}== |
=={{header|Wortel}}== |
||
The <code>@</code> operator applied to a array literal will compose the functions in the array and <code>^</code> with a group literal will do the same, but also quotes operators. |
The <code>@</code> operator applied to a array literal will compose the functions in the array and <code>^</code> with a group literal will do the same, but also quotes operators. |
||
< |
<syntaxhighlight lang="wortel">! @[f g] x ; f(g(x))</syntaxhighlight> |
||
< |
<syntaxhighlight lang="wortel">! ^(f g) x ; f(g(x))</syntaxhighlight> |
||
Defining the <code>compose</code> function |
Defining the <code>compose</code> function |
||
< |
<syntaxhighlight lang="wortel">@var compose &[f g] &x !f!g x</syntaxhighlight> |
||
=={{header|Wren}}== |
=={{header|Wren}}== |
||
< |
<syntaxhighlight lang="wren">var compose = Fn.new { |f, g| Fn.new { |x| f.call(g.call(x)) } } |
||
var double = Fn.new { |x| 2 * x } |
var double = Fn.new { |x| 2 * x } |
||
Line 3,018: | Line 3,479: | ||
var addOne = Fn.new { |x| x + 1 } |
var addOne = Fn.new { |x| x + 1 } |
||
System.print(compose.call(double, addOne).call(3))</ |
System.print(compose.call(double, addOne).call(3))</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 3,026: | Line 3,487: | ||
=={{header|zkl}}== |
=={{header|zkl}}== |
||
< |
<syntaxhighlight lang="zkl">Utils.Helpers.fcomp('+(1),'*(2))(5) //-->11</syntaxhighlight> |
||
Which is implemented with a closure (.fp1), which fixes the second paramter |
Which is implemented with a closure (.fp1), which fixes the second paramter |
||
< |
<syntaxhighlight lang="zkl">fcn fcomp(f,g,h,etc){ |
||
{ fcn(x,hgf){ T(x).pump(Void,hgf.xplode()) }.fp1(vm.arglist.reverse()); }</ |
{ fcn(x,hgf){ T(x).pump(Void,hgf.xplode()) }.fp1(vm.arglist.reverse()); }</syntaxhighlight> |
||
=={{header|ZX Spectrum Basic}}== |
=={{header|ZX Spectrum Basic}}== |
||
DEF FN commands can be nested, making this appear trivial: |
DEF FN commands can be nested, making this appear trivial: |
||
< |
<syntaxhighlight lang="zxbasic">10 DEF FN f(x)=SQR x |
||
20 DEF FN g(x)=ABS x |
20 DEF FN g(x)=ABS x |
||
30 DEF FN c(x)=FN f(FN g(x)) |
30 DEF FN c(x)=FN f(FN g(x)) |
||
40 PRINT FN c(-4)</ |
40 PRINT FN c(-4)</syntaxhighlight> |
||
Which gets you f(g(x)), for sure. But if you want g(f(x)) you need to DEF a whole new FN. Instead we can pass the function names as strings to a new function and numerically evaluate the string: |
Which gets you f(g(x)), for sure. But if you want g(f(x)) you need to DEF a whole new FN. Instead we can pass the function names as strings to a new function and numerically evaluate the string: |
||
< |
<syntaxhighlight lang="zxbasic">10 DEF FN f(x)=SQR x |
||
20 DEF FN g(x)=ABS x |
20 DEF FN g(x)=ABS x |
||
30 DEF FN c(a$,b$,x)=VAL ("FN "+a$+"(FN "+b$+"(x))") |
30 DEF FN c(a$,b$,x)=VAL ("FN "+a$+"(FN "+b$+"(x))") |
||
40 PRINT FN c("f","g",-4) |
40 PRINT FN c("f","g",-4) |
||
50 PRINT FN c("g","f",-4)</ |
50 PRINT FN c("g","f",-4)</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre>2 |
<pre>2 |
Latest revision as of 22:04, 13 March 2024
You are encouraged to solve this task according to the task description, using any language you may know.
- Task
Create a function, compose, whose two arguments f and g, are both functions with one argument.
The result of compose is to be a function of one argument, (lets call the argument x), which works like applying function f to the result of applying function g to x.
- Example
compose(f, g) (x) = f(g(x))
Reference: Function composition
Hint: In some languages, implementing compose correctly requires creating a closure.
11l
V compose = (f, g) -> (x -> @f(@g(x)))
V sin_asin = compose(x -> sin(x), x -> asin(x))
print(sin_asin(0.5))
- Output:
0.5
ActionScript
ActionScript supports closures, making function composition very straightforward.
function compose(f:Function, g:Function):Function {
return function(x:Object) {return f(g(x));};
}
function test() {
trace(compose(Math.atan, Math.tan)(0.5));
}
Ada
The interface of a generic functions package. The package can be instantiated with any type that has value semantics. Functions are composed using the operation '*'. The same operation applied to an argument evaluates it there: f * x. Functions can be composed with pointers to Ada functions. (In Ada functions are not first-class):
generic
type Argument is private;
package Functions is
type Primitive_Operation is not null
access function (Value : Argument) return Argument;
type Func (<>) is private;
function "*" (Left : Func; Right : Argument) return Argument;
function "*" (Left : Func; Right : Primitive_Operation) return Func;
function "*" (Left, Right : Primitive_Operation) return Func;
function "*" (Left, Right : Func) return Func;
private
type Func is array (Positive range <>) of Primitive_Operation;
end Functions;
Here is an implementation;
package body Functions is
function "*" (Left : Func; Right : Argument) return Argument is
Result : Argument := Right;
begin
for I in reverse Left'Range loop
Result := Left (I) (Result);
end loop;
return Result;
end "*";
function "*" (Left, Right : Func) return Func is
begin
return Left & Right;
end "*";
function "*" (Left : Func; Right : Primitive_Operation) return Func is
begin
return Left & (1 => Right);
end "*";
function "*" (Left, Right : Primitive_Operation) return Func is
begin
return (Left, Right);
end "*";
end Functions;
The following is an example of use:
with Ada.Numerics.Elementary_Functions; use Ada.Numerics.Elementary_Functions;
with Ada.Text_IO; use Ada.Text_IO;
with Functions;
procedure Test_Compose is
package Float_Functions is new Functions (Float);
use Float_Functions;
Sin_Arcsin : Func := Sin'Access * Arcsin'Access;
begin
Put_Line (Float'Image (Sin_Arcsin * 0.5));
end Test_Compose;
- Output:
5.00000E-01
Agda
compose : ∀ {a b c} {A : Set a} {B : Set b} {C : Set c}
→ (B → C)
→ (A → B)
→ A → C
compose f g x = f (g x)
Aikido
import math
function compose (f, g) {
return function (x) { return f(g(x)) }
}
var func = compose(Math.sin, Math.asin)
println (func(0.5)) // 0.5
Aime
compose_i(,,)
{
($0)(($1)($2));
}
compose(,)
{
compose_i.apply($0, $1);
}
double(real a)
{
2 * a;
}
square(real a)
{
a * a;
}
main(void)
{
o_(compose(square, double)(40), "\n");
0;
}
- Output:
6400
ALGOL 68
Note: Returning PROC (REAL x)REAL: f1(f2(x))
from a function apparently
violates standard ALGOL 68's scoping rules. ALGOL 68G warns about this during
parsing, and then rejects during runtime.
MODE F = PROC(REAL)REAL; # ALGOL 68 is strong typed #
# As a procedure for real to real functions #
PROC compose = (F f, g)F: (REAL x)REAL: f(g(x));
OP (F,F)F O = compose; # or an OPerator that can be overloaded #
# Example use: #
F sin arc sin = compose(sin, arc sin);
print((sin arc sin(0.5), (sin O arc sin)(0.5), new line))
- Output:
+.500000000000000e +0 +.500000000000000e +0
ALGOL 68 is a stack based language, and the following apparently does not violate it's scoping rules.
MODE F = PROC(REAL)REAL; # ALGOL 68 is strong typed #
# As a procedure for real to real functions #
PROC compose = (F f, g)F: ((F f2, g2, REAL x)REAL: f2(g2(x)))(f, g, ); # Curry #
PRIO O = 7;
OP (F,F)F O = compose; # or an OPerator that can be overloaded #
# Example use: #
F sin arc sin = compose(sin, arc sin);
print((sin arc sin(0.5), (sin O arc sin)(0.5), new line))
Amazing Hopper
VERSION 1:
#defn Compose(_FX_,_FY_) _FX_,_FY_
main:
0.5,Compose(sin,arcsin)
"\n", print
{0}return
- Output:
$ hopper3 basica/compose1.hop 0.500000
VERSION 2:
#define-a «(_X_) _X_ )
#define Compose(_FX_,_FY_) _FC_(_FX_,_FY_,
#define _FC_(_X_,_Y_,*) *,_X_,_Y_
main:
Compose(sin,arcsin)«( 0.5)
"\n", print
{0}return
- Output:
$ hopper3 basica/compose2.hop 0.500000
VERSION 3:
#define «(_X_) _X_ )
#define Compose(_FX_,_FY_) _FC_(_FX_,_FY_,
#define _FC_(_X_,_Y_,*) *,_X_,_Y_
main:
Compose(sin,arcsin)«( 0.5, mul by '2' )
"\n", print
{0}return
- Output:
$ hopper3 basica/compose2.hop 1.000000
The power of macro-substitution, by Hopper!
AntLang
/Apply g to exactly one argument
compose1: {f: x; g: y; {f[g[x]]}}
/Extra: apply to multiple arguments
compose: {f: x; g: y; {f[g apply args]}}
AppleScript
-- Compose two functions where each function is
-- a script object with a call(x) handler.
on compose(f, g)
script
on call(x)
f's call(g's call(x))
end call
end script
end compose
script sqrt
on call(x)
x ^ 0.5
end call
end script
script twice
on call(x)
2 * x
end call
end script
compose(sqrt, twice)'s call(32)
-- Result: 8.0
A limitation of AppleScript's handlers (functions), which can be seen in the example above, is that they are not in themselves composable first class objects, and have to be lifted into script objects before they can be composed or passed as arguments.
We can generalise this lifting with an mReturn or mInject function, which injects a handler into a script for us. This allows use to write higher-order composition and pipelining functions which take a pair (or sequence of) ordinary handlers as arguments, and return a first class script object. (We can also use mReturn to equip AppleScript with map and fold functions which take a list and an ordinary handler as arguments).
------------ COMPOSITION OF A LIST OF FUNCTIONS ----------
-- compose :: [(a -> a)] -> (a -> a)
on compose(fs)
script
on |λ|(x)
script go
on |λ|(a, f)
mReturn(f)'s |λ|(a)
end |λ|
end script
foldr(go, x, fs)
end |λ|
end script
end compose
--------------------------- TEST -------------------------
on root(x)
x ^ 0.5
end root
on succ(x)
x + 1
end succ
on half(x)
x / 2
end half
on run
tell compose({half, succ, root})
|λ|(5)
end tell
--> 1.61803398875
end run
-------------------- GENERIC FUNCTIONS -------------------
-- foldr :: (a -> b -> a) -> a -> [b] -> a
on foldr(f, startValue, xs)
tell mReturn(f)
set v to startValue
set lng to length of xs
repeat with i from lng to 1 by -1
set v to |λ|(v, item i of xs, i, xs)
end repeat
return v
end tell
end foldr
-- 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
- Output:
1.61803398875
Applesoft BASIC
10 F$ = "SIN"
20 DEF FN A(P) = ATN(P/SQR(-P*P+1))
30 G$ = "FN A"
40 GOSUB 100"COMPOSE
50 SA$ = E$
60 X = .5 : E$ = SA$
70 GOSUB 200"EXEC
80 PRINT R
90 END
100 E$ = F$ + "(" + G$ + "(X))" : RETURN : REMCOMPOSE F$ G$
200 D$ = CHR$(4) : FI$ = "TEMPORARY.EX" : M$ = CHR$(13)
210 PRINT D$"OPEN"FI$M$D$"CLOSE"FI$M$D$"DELETE"FI$
220 PRINT D$"OPEN"FI$M$D$"WRITE"FI$
230 PRINT "CALL-998:CALL-958:R="E$":CONT"
240 PRINT D$"CLOSE"FI$M$D$"EXEC"FI$:CALL-998:END:RETURN
Argile
Only works for functions taking real and returning real (double precision, 64 bits)
use std, math
let my_asin = new Function (.:<any,real x>:. -> real {asin x})
let my__sin = new Function (.:<any,real x>:. -> real { sin x})
let sinasin = my__sin o my_asin
print sin asin 0.5
print *my__sin 0.0
print *sinasin 0.5
~my_asin
~my__sin
~sinasin
=: <Function f> o <Function g> := -> Function {compose f g}
.:compose <Function f, Function g>:. -> Function
use array
let d = (new array of 2 Function)
(d[0]) = f ; (d[1]) = g
let c = new Function (.:<array of Function fg, real x>:. -> real {
*fg[0]( *fg[1](x) )
}) (d)
c.del = .:<any>:.{free any}
c
class Function
function(any)(real)->(real) func
any data
function(any) del
=: * <Function f> <real x> := -> real
Cgen "(*("(f.func)"))("(f.data)", "(x)")"
.: del Function <Function f> :.
unless f.del is nil
call f.del with f.data
free f
=: ~ <Function f> := {del Function f}
.: new Function <function(any)(real)-\>real func> (<any data>):. -> Function
let f = new Function
f.func = func
f.data = data
f
Arturo
compose: function [f,g] ->
return function [x].import:[f,g][
call f @[call g @[x]]
]
splitupper: compose 'split 'upper
print call 'splitupper ["done"]
- Output:
D O N E
ATS
If I may state in greater detail what the task requires, it is this:
That compose should return a new function, which will exist independently of compose once created. A person should never have to call compose merely to get the result of the composed computation.
Thus it is probably impossible, for instance, to really satisfy the requirement in standard C, if the result of composition is to be called like an ordinary function. However, the C solution shows it is possible, if the notion of a function is expanded to include structures requiring more than just a plain C function call. Also, there is at least one platform-dependent library for creating a "true" closure in C.
In ATS we have closures, but of more than one kind.
(*
The task:
Create a function, compose, whose two arguments f and g, are
both functions with one argument.
The result of compose is to be a function of one argument,
(let's call the argument x), which works like applying function
f to the result of applying function g to x.
In ATS, we have to choose whether to use non-linear closures
(cloref) or linear closures (cloptr). In the latter case, we also
have to choose between closures allocated with malloc (or similar)
and closures allocated on the stack.
For simplicity, we will use non-linear closures and assume there is
a garbage collector, or that the memory allocated for the closures
can be allowed to leak. (This is often the case in a program that
does not run continuously.)
*)
#include "share/atspre_staload.hats"
(* The following is actually a *template function*, rather than a
function proper. It is expanded during template processing. *)
fn {t1, t2, t3 : t@ype}
compose (f : t2 -<cloref1> t3,
g : t1 -<cloref1> t2) : t1 -<cloref1> t3 =
lam x => f (g (x))
implement
main0 () =
let
val one_hundred = 100.0
val char_zero = '0'
val f = (lam y =<cloref1> add_double_int (one_hundred, y))
val g = (lam x =<cloref1> char2i x - char2i char_zero)
val z = compose (f, g) ('5')
val fg = compose (f, g)
val w = fg ('7')
in
println! (z : double);
println! (w : double)
end
- Output:
$ patscc -O2 -DATS_MEMALLOC_GCBDW function_composition.dats -lgc && ./a.out 105.000000 107.000000
Incidentally, it is possible to instantiate the template function and obtain a true function that does the composition. What the template does for us is give us compile-time type polymorphism. In the following, the template is instantiated as a true function for specific types:
#include "share/atspre_staload.hats"
fn {t1, t2, t3 : t@ype}
compose (f : t2 -<cloref1> t3,
g : t1 -<cloref1> t2) : t1 -<cloref1> t3 =
lam x => f (g (x))
fn
compose_char2int2double
(f : int -<cloref1> double,
g : char -<cloref1> int) :
char -<cloref1> double =
compose<char, int, double> (f, g)
implement
main0 () =
let
val one_hundred = 100.0
val char_zero = '0'
val f = (lam y =<cloref1> add_double_int (one_hundred, y))
val g = (lam x =<cloref1> char2i x - char2i char_zero)
val z = compose_char2int2double (f, g) ('5')
val fg = compose_char2int2double (f, g)
val w = fg ('7')
in
println! (z : double);
println! (w : double)
end
- Output:
$ patscc -O2 -DATS_MEMALLOC_GCBDW function_composition_2.dats -lgc && ./a.out 105.000000 107.000000
One could even make the composition procedures themselves be closures:
#include "share/atspre_staload.hats"
fn {t1, t2, t3 : t@ype}
compose (f : t2 -<cloref1> t3,
g : t1 -<cloref1> t2) :<cloref1>
t1 -<cloref1> t3 =
lam x => f (g (x))
fn
compose_char2int2double
(f : int -<cloref1> double,
g : char -<cloref1> int) :<cloref1>
char -<cloref1> double =
compose<char, int, double> (f, g)
implement
main0 () =
let
val one_hundred = 100.0
val char_zero = '0'
val f = (lam y =<cloref1> add_double_int (one_hundred, y))
val g = (lam x =<cloref1> char2i x - char2i char_zero)
val z = compose_char2int2double (f, g) ('5')
val fg = compose_char2int2double (f, g)
val w = fg ('7')
in
println! (z : double);
println! (w : double)
end
- Output:
$ patscc -O2 -DATS_MEMALLOC_GCBDW function_composition_3.dats -lgc && ./a.out 105.000000 107.000000
AutoHotkey
contributed by Laszlo on the ahk forum
MsgBox % compose("sin","cos",1.5)
compose(f,g,x) { ; function composition
Return %f%(%g%(x))
}
BBC BASIC
REM Create some functions for testing:
DEF FNsqr(a) = SQR(a)
DEF FNabs(a) = ABS(a)
REM Create the function composition:
SqrAbs = FNcompose(FNsqr(), FNabs())
REM Test calling the composition:
x = -2 : PRINT ; x, FN(SqrAbs)(x)
END
DEF FNcompose(RETURN f%, RETURN g%)
LOCAL f$, p% : DIM p% 7 : p%!0 = f% : p%!4 = g%
f$ = "(x)=" + CHR$&A4 + "(&" + STR$~p% + ")(" + \
\ CHR$&A4 + "(&" + STR$~(p%+4) + ")(x))"
DIM p% LEN(f$) + 4 : $(p%+4) = f$ : !p% = p%+4
= p%
- Output:
-2 1.41421356
Bori
double sin (double v) { return Math.sin(v); }
double asin (double v) { return Math.asin(v); }
Var compose (Func f, Func g, double d) { return f(g(d)); }
void button1_onClick (Widget widget)
{
double d = compose(sin, asin, 0.5);
label1.setText(d.toString(9));
}
- Output:
on Android phone
0.500000000
Binary Lambda Calculus
In lambda calculus, the compose functions happens to coincide with multiplication on Church numerals, namely compose = \f \g \x. f (g x)
which in BLC is
00 00 00 01 1110 01 110 10
BQN
As a 2-modifier:
_compose_ ← ∘
Or:
_compose_ ← {𝔽𝔾𝕩}
As a dyadic function:
Compose ← {𝕏∘𝕎}
This is how you can use it:
(Compose´ ⟨-,÷⟩) {𝕎𝕩} 2 ¯0.5
Bracmat
This solution uses a macro in the body of the compose
function.
Function composition is illustrated with a conversion from Fahrenheit to Celsius in two steps, followed by a conversion of the resulting rational number to a floating point expression. This shows that the returned value from the compose
function indeed is a function and can be used as an argument to another call to compose
.
( ( compose
= f g
. !arg:(?f.?g)&'(.($f)$(($g)$!arg))
)
& compose
$ ( (=.flt$(!arg,2))
. compose$((=.!arg*5/9).(=.!arg+-32))
)
: (=?FahrenheitToCelsius)
& ( FahrenheitToCelsiusExample
= deg
. chu$(x2d$b0):?deg
& out
$ ( str
$ (!arg " " !deg "F in " !deg "C = " FahrenheitToCelsius$!arg)
)
)
& FahrenheitToCelsiusExample$0
& FahrenheitToCelsiusExample$100
)
0 °F in °C = -1,78*10E1 100 °F in °C = 3,78*10E1
Brat
compose = { f, g | { x | f g x } }
#Test
add1 = { x | x + 1 }
double = { x | x * 2 }
b = compose(->double ->add1)
p b 1 #should print 4
Bruijn
Composition operators as defined in std/Combinator
:
:import std/Number .
# 1x composition, bluebird combinator
…∘… [[[2 (1 0)]]]
:test (((inc ∘ (mul (+2))) (+3)) =? (+7)) ([[1]])
# 2x composition, blackbird combinator
…∘∘… [[[[3 (2 1 0)]]]]
:test (((inc ∘∘ mul) (+2) (+3)) =? (+7)) ([[1]])
# 3x composition, bunting combinator
…∘∘∘… [[[[[4 (3 2 1 0)]]]]]
:test (((inc ∘∘∘ (add ∘∘ mul)) (+1) (+2) (+4)) =? (+7)) ([[1]])
# reverse composition, queer bird combinator
…→… [[[1 (2 0)]]]
:test ((((mul (+2)) → inc) (+3)) =? (+7)) ([[1]])
C
Only works for functions taking a double and returning a double:
#include <stdlib.h>
/* generic interface for functors from double to double */
typedef struct double_to_double {
double (*fn)(struct double_to_double *, double);
} double_to_double;
#define CALL(f, x) f->fn(f, x)
/* functor returned by compose */
typedef struct compose_functor {
double (*fn)(struct compose_functor *, double);
double_to_double *f;
double_to_double *g;
} compose_functor;
/* function to be used in "fn" in preceding functor */
double compose_call(compose_functor *this, double x) {
return CALL(this->f, CALL(this->g, x));
}
/* returns functor that is the composition of functors
f & g. caller is responsible for deallocating memory */
double_to_double *compose(double_to_double *f,
double_to_double *g) {
compose_functor *result = malloc(sizeof(compose_functor));
result->fn = &compose_call;
result->f = f;
result->g = g;
return (double_to_double *)result;
}
#include <math.h>
/* we can make functors for sin and asin by using
the following as "fn" in a functor */
double sin_call(double_to_double *this, double x) {
return sin(x);
}
double asin_call(double_to_double *this, double x) {
return asin(x);
}
#include <stdio.h>
int main() {
double_to_double *my_sin = malloc(sizeof(double_to_double));
my_sin->fn = &sin_call;
double_to_double *my_asin = malloc(sizeof(double_to_double));
my_asin->fn = &asin_call;
double_to_double *sin_asin = compose(my_sin, my_asin);
printf("%f\n", CALL(sin_asin, 0.5)); /* prints "0.500000" */
free(sin_asin);
free(my_sin);
free(my_asin);
return 0;
}
C#
using System;
class Program
{
static void Main(string[] args)
{
Func<int, int> outfunc = Composer<int, int, int>.Compose(functA, functB);
Console.WriteLine(outfunc(5)); //Prints 100
}
static int functA(int i) { return i * 10; }
static int functB(int i) { return i + 5; }
class Composer<A, B, C>
{
public static Func<C, A> Compose(Func<B, A> a, Func<C, B> b)
{
return delegate(C i) { return a(b(i)); };
}
}
}
C++
#include <functional>
#include <cmath>
#include <iostream>
// functor class to be returned by compose function
template <class Fun1, class Fun2>
class compose_functor :
public std::unary_function<typename Fun2::argument_type,
typename Fun1::result_type>
{
protected:
Fun1 f;
Fun2 g;
public:
compose_functor(const Fun1& _f, const Fun2& _g)
: f(_f), g(_g) { }
typename Fun1::result_type
operator()(const typename Fun2::argument_type& x) const
{ return f(g(x)); }
};
// we wrap it in a function so the compiler infers the template arguments
// whereas if we used the class directly we would have to specify them explicitly
template <class Fun1, class Fun2>
inline compose_functor<Fun1, Fun2>
compose(const Fun1& f, const Fun2& g)
{ return compose_functor<Fun1,Fun2>(f, g); }
int main() {
std::cout << compose(std::ptr_fun(::sin), std::ptr_fun(::asin))(0.5) << std::endl;
return 0;
}
composing std::function
#include <iostream>
#include <functional>
#include <cmath>
template <typename A, typename B, typename C>
std::function<C(A)> compose(std::function<C(B)> f, std::function<B(A)> g) {
return [f,g](A x) { return f(g(x)); };
}
int main() {
std::function<double(double)> f = sin;
std::function<double(double)> g = asin;
std::cout << compose(f, g)(0.5) << std::endl;
}
This much simpler version uses decltype(auto)
.
#include <iostream>
#include <cmath>
template <class F, class G>
decltype(auto) compose(F&& f, G&& g) {
return [=](auto x) { return f(g(x)); };
}
int main() {
std::cout << compose(sin, asin)(0.5) << "\n";
}
Not standard C++, but GCC has a built-in compose function
#include <iostream>
#include <cmath>
#include <ext/functional>
int main() {
std::cout << __gnu_cxx::compose1(std::ptr_fun(::sin), std::ptr_fun(::asin))(0.5) << std::endl;
}
Works with: C++20
#include <iostream>
#include <cmath>
auto compose(auto f, auto g) {
return [=](auto x) { return f(g(x)); };
}
int main() {
std::cout << compose(sin, asin)(0.5) << "\n";
}
- Output:
0.5
Clojure
Function composition is built in to Clojure. Simply call the comp
function.
A manual implementation could look like this:
(defn compose [f g]
(fn [x]
(f (g x))))
; Example
(def inc2 (compose inc inc))
(println (inc2 5)) ; prints 7
CoffeeScript
compose = ( f, g ) -> ( x ) -> f g x
# Example
add2 = ( x ) -> x + 2
mul2 = ( x ) -> x * 2
mulFirst = compose add2, mul2
addFirst = compose mul2, add2
multiple = compose mul2, compose add2, mul2
console.log "add2 2 #=> #{ add2 2 }"
console.log "mul2 2 #=> #{ mul2 2 }"
console.log "mulFirst 2 #=> #{ mulFirst 2 }"
console.log "addFirst 2 #=> #{ addFirst 2 }"
console.log "multiple 2 #=> #{ multiple 2 }"
- Output:
add2 2 #=> 4 mul2 2 #=> 4 mulFirst 2 #=> 6 addFirst 2 #=> 8 multiple 2 #=> 12
Or, extending the Function
prototype.
Function::of = (f) -> (args...) => @ f args...
# Example
add2 = (x) -> x + 2
mul2 = (x) -> x * 2
mulFirst = add2.of mul2
addFirst = mul2.of add2
multiple = mul2.of add2.of mul2
console.log "add2 2 #=> #{ add2 2 }"
console.log "mul2 2 #=> #{ mul2 2 }"
console.log "mulFirst 2 #=> #{ mulFirst 2 }"
console.log "addFirst 2 #=> #{ addFirst 2 }"
console.log "multiple 2 #=> #{ multiple 2 }"
Output is identical.
Common Lisp
compose
returns a function that closes on the lexical variables f and g.
(defun compose (f g) (lambda (x) (funcall f (funcall g x))))
Example use:
>(defun compose (f g) (lambda (x) (funcall f (funcall g x))))
COMPOSE
>(let ((sin-asin (compose #'sin #'asin)))
(funcall sin-asin 0.5))
0.5
This alternate solution, more ugly and more difficult, never closes on any lexical variables. Instead, it uses runtime evaluation to insert the values of f and g into new code. This is just a different way to create a closure.
(defun compose (f g)
(eval `(lambda (x) (funcall ',f (funcall ',g x)))))
In this last example, a macro is used to compose any number of single parameter functions.
CL-USER> (defmacro compose (fn-name &rest args)
(labels ((rec1 (args)
(if (= (length args) 1)
`(funcall ,@args x)
`(funcall ,(first args) ,(rec1 (rest args))))))
`(defun ,fn-name (x) ,(rec1 args))))
Because this macro expands into a defun form, the function returned by compose is in the function namespace and the use of funcall is not necessary.
CL-USER> (compose f #'ceiling #'sin #'sqrt) F CL-USER> (compose g #'1+ #'abs #'cos) G CL-USER> (compose h #'f #'g) H CL-USER> (values (f pi) (g pi) (h pi)) 1 2.0L0 1 CL-USER>
Crystal
Crystal requires using closures for function composition. Since the only type the compiler can't infer for compose
is the type of x
, the type of the first argument to f
has to be specified as the generic type T
.
require "math"
def compose(f : Proc(T, _), g : Proc(_, _)) forall T
return ->(x : T) { f.call(g.call(x)) }
end
compose(->Math.sin(Float64), ->Math.asin(Float64)).call(0.5) #=> 0.5
The types for f
's output, g
's input and output, and the result of compose
can all be inferred, but could be specified verbosely with def compose(f : Proc(T, U), g : Proc(U, V)) : Proc(T, V) forall T, U, V
D
import std.stdio;
T delegate(S) compose(T, U, S)(in T delegate(U) f,
in U delegate(S) g) {
return s => f(g(s));
}
void main() {
writeln(compose((int x) => x + 15, (int x) => x ^^ 2)(10));
writeln(compose((int x) => x ^^ 2, (int x) => x + 15)(10));
}
- Output:
115 625
Delphi
Anonymous methods were introduced in Delphi 2009, so next code works with Delphi 2009 and above:
program AnonCompose;
{$APPTYPE CONSOLE}
type
TFunc = reference to function(Value: Integer): Integer;
// Alternative: TFunc = TFunc<Integer,Integer>;
function Compose(F, G: TFunc): TFunc;
begin
Result:= function(Value: Integer): Integer
begin
Result:= F(G(Value));
end
end;
var
Func1, Func2, Func3: TFunc;
begin
Func1:=
function(Value: Integer): Integer
begin
Result:= Value * 2;
end;
Func2:=
function(Value: Integer): Integer
begin
Result:= Value * 3;
end;
Func3:= Compose(Func1, Func2);
Writeln(Func3(6)); // 36 = 6 * 3 * 2
Readln;
end.
Diego
Function composition of two simple functions:
set_namespace(rosettacode);
begin_funct(compose)_arg(f, g);
[]_ret(x)_calc([f]([g]([x])));
end_funct[];
me_msg()_funct(compose)_arg(f)_sin()_arg(g)_asin()_var(x)_value(0.5); // result: 0.5
reset_namespace[];
Function composition of two calculated functions:
set_namespace(rosettacode);
with_funct(f)_arg({int}, x)_ret()_calc([x] * [x]);
with_funct(g)_arg({int}, x)_ret()_calc([x] + 2);
begin_funct(compose)_arg(f, g);
[]_ret(x)_calc([f]([g]([x])));
end_funct[];
me_msg()_funct(compose)_arg(f)_funct(f)_arg(g)_funct(g)_var(x)_v(10); // result: 144
// or me_msg()_funct(compose)_arg({f}, f)_arg({g}, g)_var(x)_v(10);
reset_ns[];
Dylan
compose[1] is already part of the language standard, with a more complete definition than this.
define method compose(f,g)
method(x) f(g(x)) end
end;
Déjà Vu
It is already defined in the standard library as $
.
compose f g:
labda:
f g
E
def compose(f, g) {
return fn x { return f(g(x)) }
}
EchoLisp
;; By decreasing order of performance
;; 1) user definition : lambda and closure
(define (ucompose f g ) (lambda (x) ( f ( g x))))
(ucompose sin cos)
→ (🔒 λ (_x) (f (g _x)))
;; 2) built-in compose : lambda
(compose sin cos)
→ (λ (_#:g1002) (#apply-compose (#list #cos #sin) _#:g1002))
;; 3) compiled composition
(define (sincos x) (sin (cos x)))
sincos → (λ (_x) (⭕️ #sin (#cos _x)))
- Output:
((ucompose sin cos) 3) → -0.8360218615377305
((compose sin cos) 3) → -0.8360218615377305
(sincos 3) → -0.8360218615377305
Ela
It is already defined in standard prelude as (<<) operator.
let compose f g x = f (g x)
==Ela==
It is already defined in standard prelude as (<<) operator.
compose f g x = f (g x)
Elena
ELENA 6.x :
import extensions;
extension op : Func1
{
compose(Func1 f)
= (x => self(f(x)));
}
public program()
{
var fg := (x => x + 1).compose::(x => x * x);
console.printLine(fg(3))
}
- Output:
10
Elixir
defmodule RC do
def compose(f, g), do: fn(x) -> f.(g.(x)) end
def multicompose(fs), do: List.foldl(fs, fn(x) -> x end, &compose/2)
end
sin_asin = RC.compose(&:math.sin/1, &:math.asin/1)
IO.puts sin_asin.(0.5)
IO.puts RC.multicompose([&:math.sin/1, &:math.asin/1, fn x->1/x end]).(0.5)
IO.puts RC.multicompose([&(&1*&1), &(1/&1), &(&1*&1)]).(0.5)
- Output:
0.5 2.0 16.0
Emacs Lisp
Lexical binding is supported as of Emacs 24.1, allowing the use of a closure for function composition.
;; lexical-binding: t
(defun compose (f g)
(lambda (x)
(funcall f (funcall g x))))
(let ((func (compose '1+ '1+)))
(funcall func 5)) ;=> 7
Alternatively, a lambda
form can be constructed with the desired f
and g
inserted. The result is simply a list. A list starting with lambda
is a function.
(defun compose (f g)
`(lambda (x) (,f (,g x))))
(let ((func (compose '1+ '1+)))
(funcall func 5)) ;=> 7
A similar thing can be done with a macro like the following. It differs in that the arguments should be unquoted symbols, and if they're expressions then they're evaluated on every call to the resulting lambda
.
(defmacro compose (f g)
`(lambda (x) (,f (,g x))))
(let ((func (compose 1+ 1+)))
(funcall func 5)) ;=> 7
Erlang
-module(fn).
-export([compose/2, multicompose/1]).
compose(F,G) -> fun(X) -> F(G(X)) end.
multicompose(Fs) ->
lists:foldl(fun compose/2, fun(X) -> X end, Fs).
Using them:
1> (fn:compose(fun math:sin/1, fun math:asin/1))(0.5).
0.5
2> Sin_asin_plus1 = fn:multicompose([fun math:sin/1, fun math:asin/1, fun(X) -> X + 1 end]).
#Fun<tests.0.59446746>
82> Sin_asin_plus1(0.5).
1.5
F#
The most-used composition operator in F# is >>
. It implements forward composition, i.e. f >> g
is a function which calls f first and then calls g on the result.
The reverse composition operator <<
, on the other hand, exactly fulfills the requirements of the compose function described in this task.
We can implement composition manually like this (F# Interactive session):
> let compose f g x = f (g x);;
val compose : ('a -> 'b) -> ('c -> 'a) -> 'c -> 'b
Usage:
> let sin_asin = compose sin asin;;
val sin_asin : (float -> float)
> sin_asin 0.5;;
val it : float = 0.5
Factor
Factor is a concatenative language, so function composition is inherent. If the functions f
and g
are named, their composition is f g
. Thanks to stack polymorphism, this holds true even if g
consumes more values than f
leaves behind. You always get every sort of composition for free. But watch out for stack underflows!
To compose quotations (anonymous functions), compose
may be used:
( scratchpad ) [ 2 * ] [ 1 + ] compose .
[ 2 * 1 + ]
( scratchpad ) 4 [ 2 * ] [ 1 + ] compose call .
9
Fantom
class Compose
{
static |Obj -> Obj| compose (|Obj -> Obj| fn1, |Obj -> Obj| fn2)
{
return |Obj x -> Obj| { fn2 (fn1 (x)) }
}
public static Void main ()
{
double := |Int x -> Int| { 2 * x }
|Int -> Int| quad := compose(double, double)
echo ("Double 3 = ${double(3)}")
echo ("Quadruple 3 = ${quad (3)}")
}
}
Forth
: compose ( xt1 xt2 -- xt3 )
>r >r :noname
r> compile,
r> compile,
postpone ;
;
' 2* ' 1+ compose ( xt )
3 swap execute . \ 7
Fortran
Modern Fortran standard has (limited) kind of higher-order functions (as result, argument, and with one level of nested functions) and optional arguments, and this enables to compose the following function (it is impure because Fortran has no closures). For simple cases function calls may be just nested to achieve the effect of function composition, because in fortran nested calls f(g(d(x))) generate a hierarchic set of function calls and the result of each function is transmitted to its calling function in a standard way for all functions.
module functions_module
implicit none
private ! all by default
public :: f,g
contains
pure function f(x)
implicit none
real, intent(in) :: x
real :: f
f = sin(x)
end function f
pure function g(x)
implicit none
real, intent(in) :: x
real :: g
g = cos(x)
end function g
end module functions_module
module compose_module
implicit none
private ! all by default
public :: compose
interface
pure function f(x)
implicit none
real, intent(in) :: x
real :: f
end function f
pure function g(x)
implicit none
real, intent(in) :: x
real :: g
end function g
end interface
contains
impure function compose(x, fi, gi)
implicit none
real, intent(in) :: x
procedure(f), optional :: fi
procedure(g), optional :: gi
real :: compose
procedure (f), pointer, save :: fpi => null()
procedure (g), pointer, save :: gpi => null()
if(present(fi) .and. present(gi))then
fpi => fi
gpi => gi
compose = 0
return
endif
if(.not. associated(fpi)) error stop "fpi"
if(.not. associated(gpi)) error stop "gpi"
compose = fpi(gpi(x))
contains
end function compose
end module compose_module
program test_compose
use functions_module
use compose_module
implicit none
write(*,*) "prepare compose:", compose(0.0, f,g)
write(*,*) "run compose:", compose(0.5)
end program test_compose
Fortress
In Fortress, there are two ways that you can compose functions.
1. You can compose functions manually by writing your own composition function.
In this version, we allow any type of function to be used by defining our own types in the function definition and using those types to define how the composed function should behave. This version operates very similarly to the way that the COMPOSE operator, explained below, operates.
compose[\A, B, C\](f:A->B, g:B->C, i:Any): A->C = do
f(g(i))
end
composed(i:RR64): RR64 = compose(sin, cos, i)
Alternatively, you could explicitly define each type for improved type safety.
Due to the fact that alt_compose() is built around the idea that it is being used to compose two trigonometric functions, these will return identical functions. However, if you were to pass alt_composed() any other type of function, the interpreter would throw an error.
alt_compose(f:Number->RR64, g:Number->RR64, i:RR64): ()->RR64 = do
f(g(i))
end
alt_composed(i:RR64): RR64 = compose(sin, cos, i)
2. You can use the COMPOSE operator (or CIRC or RING). Because COMPOSE returns an anonymous function, it is necessary to wrap it in parentheses if you want to be able to use it in this manner.
opr_composed(i:Number): Number->RR64 = (sin COMPOSE cos)(i)
Should you need to, you could also mix both methods by overloading the COMPOSE operator.
FreeBASIC
Illustrating with functions that take and return integers.
function compose( f as function(as integer) as integer,_
g as function(as integer) as integer,_
n as integer ) as integer
return f(g(n))
end function
If you have functions named, say, foo and bar you would call compose with
compose( @foo, @bar, n )
for some integer n.
FunL
import math.{sin, asin}
def compose( f, g ) = x -> f( g(x) )
sin_asin = compose( sin, asin )
println( sin_asin(0.5) )
- Output:
0.5
Fōrmulæ
Fōrmulæ programs are not textual, visualization/edition of programs is done showing/manipulating structures but not text. Moreover, there can be multiple visual representations of the same program. Even though it is possible to have textual representation —i.e. XML, JSON— they are intended for storage and transfer purposes more than visualization and edition.
Programs in Fōrmulæ are created/edited online in its website.
In this page you can see and run the program(s) related to this task and their results. You can also change either the programs or the parameters they are called with, for experimentation, but remember that these programs were created with the main purpose of showing a clear solution of the task, and they generally lack any kind of validation.
Solution
The compose function returns a lambda expression, containing the actual composition of its arguments, and hence it can be called applied with its argument(s):
Test cases
Arguments of the functions to compose can be the same symbol, they are not "scrambled":
Because a function in Fōrmulæ is just a lambda expression, a lambda expression can be directly provided.
Since the composition function returns a lambda expression, it is not required to be applied:
GAP
Composition := function(f, g)
return x -> f(g(x));
end;
h := Composition(x -> x+1, x -> x*x);
h(5);
# 26
Go
// Go doesn't have generics, but sometimes a type definition helps
// readability and maintainability. This example is written to
// the following function type, which uses float64.
type ffType func(float64) float64
// compose function requested by task
func compose(f, g ffType) ffType {
return func(x float64) float64 {
return f(g(x))
}
}
Example use:
package main
import "math"
import "fmt"
type ffType func(float64) float64
func compose(f, g ffType) ffType {
return func(x float64) float64 {
return f(g(x))
}
}
func main() {
sin_asin := compose(math.Sin, math.Asin)
fmt.Println(sin_asin(.5))
}
- Output:
0.5
Groovy
Test program:
final times2 = { it * 2 }
final plus1 = { it + 1 }
final plus1_then_times2 = times2 << plus1
final times2_then_plus1 = times2 >> plus1
assert plus1_then_times2(3) == 8
assert times2_then_plus1(3) == 7
Haskell
This is already defined as the . (dot) operator in Haskell:
Prelude> let sin_asin = sin . asin
Prelude> sin_asin 0.5
0.49999999999999994
Ways to use directly:
(sin . asin) 0.5
sin . asin $ 0.5
Implementing compose function from scratch:
compose f g x = f (g x)
Example use:
Prelude> let compose f g x = f (g x)
Prelude> let sin_asin = compose sin asin
Prelude> sin_asin 0.5
0.5
Right to left composition of a list of functions could be defined as flip (foldr id):
composeList :: [a -> a] -> a -> a
composeList = flip (foldr id)
main :: IO ()
main = print $ composeList [(/ 2), succ, sqrt] 5
- Output:
1.618033988749895
Hy
(defn compose [f g]
(fn [x]
(f (g x))))
Icon and Unicon
Icon and Unicon don't have a lambda function or native closure; however, they do have co-expressions which are extremely versatile and can be used to achieve the same effect. The list of functions to compose can be a 'procedure', 'co-expression", or an invocable string (i.e. procedure name or unary operator). It will correctly handle compose(compose(...),..).
There are a few limitations to be aware of:
- type(compose(f,g)) returns a co-expression not a procedure
- this construction only handles functions of 1 argument (a closure construct is better for the general case)
The solution below can be adapted to work in Icon by reverting to the old syntax for invoking co-expressions.
See Icon and Unicon Introduction:Minor Differences for more information
procedure main(arglist)
h := compose(sqrt,abs)
k := compose(integer,"sqrt",ord)
m := compose("-",k)
every write(i := -2 to 2, " h=(sqrt,abs)-> ", h(i))
every write(c := !"1@Q", " k=(integer,\"sqrt\",ord)-> ", k(c))
write(c := "1"," m=(\"-\",k) -> ",m(c))
end
invocable all # permit string invocations
procedure compose(fL[]) #: compose(f1,f2,...) returns the functional composition of f1,f2,... as a co-expression
local x,f,saveSource
every case type(x := !fL) of {
"procedure"|"co-expression": &null # procedures and co-expressions are fine
"string" : if not proc(x,1) then runnerr(123,fL) # as are invocable strings (unary operators, and procedures)
default: runerr(123,fL)
}
fL := reverse(fL) # reverse and isolate from mutable side-effects
cf := create { saveSource := &source # don't forget where we came from
repeat {
x := (x@saveSource)[1] # return result and resume here
saveSource := &source # ...
every f := !fL do x := f(x) # apply the list of 'functions'
}
}
return (@cf, cf) # 'prime' the co-expr before returning it
end
- Output:
-2 h=(sqrt,abs)-> 1.414213562373095 -1 h=(sqrt,abs)-> 1.0 0 h=(sqrt,abs)-> 0.0 1 h=(sqrt,abs)-> 1.0 2 h=(sqrt,abs)-> 1.414213562373095 1 k=(integer,"sqrt",ord)-> 7 @ k=(integer,"sqrt",ord)-> 8 Q k=(integer,"sqrt",ord)-> 9 1 m=("-",k) -> -7
J
Solution:
compose =: @
Example:
f compose g
Of course, given that @
is only one character long and is a built-in primitive, there is no need for the cover function compose
. And @
is not the only composition primitive; composition is a very important concept in J. For more details, see the talk page.
Tentative new example:
f=: >.@(1&o.)@%:
g=: 1&+@|@(2&o.)
h=: f@g
Example use:
(f, g, h) 1p1
1 2 1
Note: 1&o.
is sine (mnemonic: sine is an odd circular function), 2&o.
is cosine (cosine is an even circular function), %:
is square root, >.
is ceiling, |
is absolute value and 1&+
adds 1.
Janet
Janet supports function composition with the comp
function.
(defn fahrenheit->celsius [deg-f]
(/ (* (- deg-f 32) 5) 9))
(defn celsius->kelvin [deg-c]
(+ deg-c 273.15))
(def fahrenheit->kelvin (comp celsius->kelvin fahrenheit->celsius))
(fahrenheit->kelvin 72) // 295.372
Java
public class Compose {
// Java doesn't have function type so we define an interface
// of function objects instead
public interface Fun<A,B> {
B call(A x);
}
public static <A,B,C> Fun<A,C> compose(final Fun<B,C> f, final Fun<A,B> g) {
return new Fun<A,C>() {
public C call(A x) {
return f.call(g.call(x));
}
};
}
public static void main(String[] args) {
Fun<Double,Double> sin = new Fun<Double,Double>() {
public Double call(Double x) {
return Math.sin(x);
}
};
Fun<Double,Double> asin = new Fun<Double,Double>() {
public Double call(Double x) {
return Math.asin(x);
}
};
Fun<Double,Double> sin_asin = compose(sin, asin);
System.out.println(sin_asin.call(0.5)); // prints "0.5"
}
}
Java 8
Java 8's Function
interface already has a .compose()
default method:
import java.util.function.Function;
public class Compose {
public static void main(String[] args) {
Function<Double,Double> sin_asin = ((Function<Double,Double>)Math::sin).compose(Math::asin);
System.out.println(sin_asin.apply(0.5)); // prints "0.5"
}
}
Implementing it yourself as a static method:
import java.util.function.Function;
public class Compose {
public static <A,B,C> Function<A,C> compose(Function<B,C> f, Function<A,B> g) {
return x -> f.apply(g.apply(x));
}
public static void main(String[] args) {
Function<Double,Double> sin_asin = compose(Math::sin, Math::asin);
System.out.println(sin_asin.apply(0.5)); // prints "0.5"
}
}
JavaScript
ES5
Simple composition of two functions
function compose(f, g) {
return function(x) {
return f(g(x));
};
}
Example:
var id = compose(Math.sin, Math.asin);
console.log(id(0.5)); // 0.5
Multiple composition
Recursion apart, multiple composition can be written in at least two general ways in JS:
- Iteratively (faster to run, perhaps more fiddly to write)
- With a fold / reduction (see http://rosettacode.org/wiki/Catamorphism). The fold is arguably simpler to write and reason about, though not quite as fast to execute.
(function () {
'use strict';
// iterativeComposed :: [f] -> f
function iterativeComposed(fs) {
return function (x) {
var i = fs.length,
e = x;
while (i--) e = fs[i](e);
return e;
}
}
// foldComposed :: [f] -> f
function foldComposed(fs) {
return function (x) {
return fs
.reduceRight(function (a, f) {
return f(a);
}, x);
};
}
var sqrt = Math.sqrt,
succ = function (x) {
return x + 1;
},
half = function (x) {
return x / 2;
};
// Testing two different multiple composition ([f] -> f) functions
return [iterativeComposed, foldComposed]
.map(function (compose) {
// both functions compose from right to left
return compose([half, succ, sqrt])(5);
});
})();
- Output:
[1.618033988749895, 1.618033988749895]
ES6
Simple composition of two functions
function compose(f, g) {
return x => f(g(x));
}
or
var compose = (f, g) => x => f(g(x));
Example:
var id = compose(Math.sin, Math.asin);
console.log(id(0.5)); // 0.5
Multiple composition
(() => {
"use strict";
// -------------- MULTIPLE COMPOSITION ---------------
// compose (<<<) :: (b -> c) -> (a -> b) -> a -> c
const compose = (...fs) =>
// A function defined by the right-to-left
// composition of all the functions in fs.
fs.reduce(
(f, g) => x => f(g(x)),
x => x
);
// ---------------------- TEST -----------------------
const
sqrt = Math.sqrt,
succ = x => x + 1,
half = x => x / 2;
return compose(half, succ, sqrt)(5);
// --> 1.618033988749895
})();
- Output:
1.618033988749895
Joy
Composition is the default operation in Joy. The composition of two functions is the concatenation of those functions, in the order in which they are to be applied.
g f
And yes, there should be a space between the two names.
jq
The equivalent in jq of a function with one argument is a 0-arity filter. For example, in jq, exp is the exponential function and can be evaluated like so: 0.5 | exp.
We therefore illustrate here how a function that composes two 0-arity filters can be written:
# apply g first and then f
def compose(f; g): g | f;
Example: 0.5 | compose(asin; sin)
In practice, "compose" is rarely used since, given two 0-arity filters, f and g, the expression "g|f" can be passed as an argument to other functions.
Julia
Built-in:
@show (asin ∘ sin)(0.5)
Alternative:
compose(f::Function, g::Function) = (x) -> g(f(x))
@show compose(sin, asin)(0.5)
K
The K syntax for APL tacit (point free) function composition is the dyadic form of apostrophe ('), here is a cover function
compose:{'[x;y]}
An equivalent explicit definition would be
compose:{x[y[z]]}
Example:
sin_asin:compose[sin;asin] // or compose . (sin;asin)
sin_asin 0.5
0.5
Klingphix
include ..\Utilitys.tlhy
:*2 2 * ;
:++ 1 + ;
:composite swap exec swap exec ;
@++ @*2 3 composite ? { result: 7 }
"End " input
Kotlin
fun f(x: Int): Int = x * x
fun g(x: Int): Int = x + 2
fun <T, V, R> compose(f: (V) -> R, g: (T) -> V): (T) -> R = { f(g(it) }
fun main() {
val x = 10
println(compose(::f, ::g)(x))
}
- Output:
144
Lambdatalk
{def compose
{lambda {:f :g :x}
{:f {:g :x}}}}
-> compose
{def funcA {lambda {:x} {* :x 10}}}
-> funcA
{def funcB {lambda {:x} {+ :x 5}}}
-> funcB
{def f {compose funcA funcB}}
-> f
{{f} 3}
-> 80
Lang
fp.f = ($x) -> return parser.op($x * 3)
fp.g = ($x) -> return parser.op($x + 2)
$x = 5
# In Lang this task can be achieved with the concat operator
fn.println(parser.op((fp.g ||| fp.f)($x))) # Prints 21 [Internal execution: fp.f(fp.g($x))]
# Creating a user-defined function doing the same thing is a bit more difficult
fp.compose = (fp.f, fp.g) -> {
fp.innerFunc = (fp.f, fp.g, $x) -> return fp.f(fp.g($x))
return fn.argCnt1(fn.combA3(fp.innerFunc, fp.f, fp.g)) # fn.combA3 must be used, because Lang does not support closures
}
fn.println(fp.compose(fp.f, fp.g)($x)) # Prints also 21
LFE
(defun compose (f g)
(lambda (x)
(funcall f
(funcall g x))))
(defun compose (funcs)
(lists:foldl #'compose/2
(lambda (x) x)
funcs))
(defun check ()
(let* ((sin-asin (compose #'math:sin/1 #'math:asin/1))
(expected (math:sin (math:asin 0.5)))
(compose-result (funcall sin-asin 0.5)))
(io:format '"Expected answer: ~p~n" (list expected))
(io:format '"Answer with compose: ~p~n" (list compose-result))))
If you pasted those into the LFE REPL, you can do the following:
> (funcall (compose #'math:sin/1 #'math:asin/1)
0.5)
0.49999999999999994
> (funcall (compose `(,#'math:sin/1
,#'math:asin/1
,(lambda (x) (+ x 1))))
0.5)
1.5
> (check)
Expected answer: 0.49999999999999994
Answer with compose: 0.49999999999999994
ok
>
Lingo
Lingo does not support functions as first-class objects. However, there is a way to achieve something similar:
In Lingo global functions (i.e. either built-in functions or custom functions defined in movie scripts) are methods of the _movie object. There are 2 ways to call such functions:
- a) foo (1,2,3)
- b) call (#foo, _movie, 1, 2, 3)
If we ignore the standard way a) and only concentrate on b), we can define a "call-function" (arbitrary word coining) as:
- "Anything that supports the syntax 'call(<func>, _movie [, comma-separated arg list])' and might return a value."
As described above, this "call-function" definition includes all built-in and global user-defined functions.
For such "call-functions", function composition can be implemented using the following global (i.e. movie script) function compose() and the following parent script "Composer":
-- in some movie script
----------------------------------------
-- Composes 2 call-functions, returns a new call-function
-- @param {symbol|instance} f
-- @param {symbol|instance} g
-- @return {instance}
----------------------------------------
on compose (f, g)
return script("Composer").new(f, g)
end
-- parent script "Composer"
property _f
property _g
----------------------------------------
-- @constructor
-- @param {symbol|instance} f
-- @param {symbol|instance} g
----------------------------------------
on new (me, f, g)
me._f = f
me._g = g
return me
end
on call (me)
if ilk(me._g)=#instance then
cmd = "_movie.call(#call,me._g,VOID"
else
cmd = "_movie.call(me._g,_movie"
end if
a = [] -- local args list
repeat with i = 1 to the paramCount-2
a[i] = param(i+2)
put ",a["&i&"]" after cmd
end repeat
put ")" after cmd
if ilk(me._f)=#instance then
return _movie.call(#call, me._f, VOID, value(cmd))
else
return _movie.call(me._f, _movie, value(cmd))
end if
end
Usage:
-- compose new function based on built-in function 'sin' and user-defined function 'asin'
f1 = compose(#asin, #sin)
put call(f1, _movie, 0.5)
-- 0.5000
-- compose new function based on previously composed function 'f1' and user-defined function 'double'
f2 = compose(#double, f1)
put call(f2, _movie, 0.5)
-- 1.0000
-- compose new function based on 2 composed functions
f1 = compose(#asin, #sin)
f2 = compose(#double, #triple)
f3 = compose(f2, f1)
put call(f3, _movie, 0.5)
-- 3.0000
User-defined custom functions used in demo code above:
-- in some movie script
on asin (x)
res = atan(sqrt(x*x/(1-x*x)))
if x<0 then res = -res
return res
end
on double (x)
return x*2
end
on triple (x)
return x*3
end
LOLCODE
LOLCODE supports first-class functions only insofar as they may be stored in variables and returned from other functions. Alas, given the current lack of support for either lambdas or closures, function composition can only be reasonably simulated with the help of a few global variables.
HAI 1.3
I HAS A fx, I HAS A gx
HOW IZ I composin YR f AN YR g
fx R f, gx R g
HOW IZ I composed YR x
FOUND YR I IZ fx YR I IZ gx YR x MKAY MKAY
IF U SAY SO
FOUND YR composed
IF U SAY SO
HOW IZ I incin YR num
FOUND YR SUM OF num AN 1
IF U SAY SO
HOW IZ I sqrin YR num
FOUND YR PRODUKT OF num AN num
IF U SAY SO
I HAS A incsqrin ITZ I IZ composin YR incin AN YR sqrin MKAY
VISIBLE I IZ incsqrin YR 10 MKAY BTW, prints 101
I HAS A sqrincin ITZ I IZ composin YR sqrin AN YR incin MKAY
VISIBLE I IZ sqrincin YR 10 MKAY BTW, prints 121
KTHXBYE
Lua
function compose(f, g) return function(...) return f(g(...)) end end
M2000 Interpreter
Using Lambda functions
Module CheckIt {
Compose = lambda (f, g)->{
=lambda f, g (x)->f(g(x))
}
Add5=lambda (x)->x+5
Division2=lambda (x)->x/2
Add5Div2=compose(Division2, Add5)
Print Add5Div2(15)=10 ' True
}
CheckIt
Using EVAL and EVAL$
class Compose {
private:
composition$
public:
function formula$ {
=.composition$
}
value (x){
=Eval(.composition$)
}
Class:
module compose(a$, b$) {
.composition$<=a$+"("+b$+"(x))"
}
}
function Global Exp(x) {
=round(2.7182818284590452**x)
}
class ComposeStr$ {
private:
composition$
public:
function formula$ {
=.composition$
}
value (x$){
=Eval$(.composition$.) // NEED A DOT AFTER STRING VARIABLE
}
Class:
module composeStr(a$, b$) {
.composition$<=a$+"("+b$+"(x$))"
}
}
ExpLog=Compose("Exp", "Ln")
Print ExpLog(3)
UcaseLcase$=ComposeStr$("Ucase$", "Lcase$")
Print UcaseLcase$("GOOD")
Mathcad
Mathcad is a non-text-based programming environment. The expressions below are an approximations of the way that they are entered (and) displayed on a Mathcad worksheet. The worksheet is available at xxx_tbd_xxx
This particular version of Function Composition was created in Mathcad Prime Express 7.0, a free version of Mathcad Prime 7.0 with restrictions (such as no programming or symbolics). All Prime Express numbers are complex. There is a recursion depth limit of about 4,500.
compose(f,g,x):=f(g(x))
cube(x):=x3 cuberoot(x):=x1/3
funlist:=[sin cos cube]T invlist:=[asin acos cuberoot]T
invfunlist(x):= {vectorize}compose(invlist,funlist,x){/vectorize}
x:= 0.5
invfunlist(x)= {results of evaluation appears here) invfunlist([x √2 3]T)= {results)
apply(f,x):=f(x) apply(f,x):={vectorize}apply(f,x){/vectorize}
apply(funlist,x)= {results} + ... several more examples
Mathematica / Wolfram Language
Built-in function that takes any amount of function-arguments:
Composition[f, g][x]
Composition[f, g, h, i][x]
gives back:
f[g[x]]
f[g[h[i[x]]]]
Custom function:
compose[f_, g_][x_] := f[g[x]]
compose[Sin, Cos][r]
gives back:
Sin[Cos[r]]
Composition can be done in more than 1 way:
Composition[f,g,h][x]
f@g@h@x
x//h//g//f
all give back:
f[g[h[x]]]
The built-in function has a couple of automatic simplifications:
Composition[f, Identity, g]
Composition[f, InverseFunction[f], h][x]
becomes:
f[g[x]]
h[x]
Maxima
/* built-in */
load(to_poly_solver);
compose_functions([sin, cos]);
/* lambda([%g0],sin(cos(%g0)))*/
/* An implementation, to show a use of buildq */
compose(f, g) := buildq([f, g], lambda([x], f(g(x))));
min
Since min is both concatenative and homoiconic, function composition is equivalent to list concatenation. Example:
(1 +) (2 *) concat print
- Output:
(1 + 2 *)
MiniScript
funcA = function(x)
return x * 10
end function
funcB = function(x)
return x + 5
end function
compose = function(f, g)
return function(x)
return f(g(x))
end function
end function
f = compose(@funcA, @funcB)
print f(3) // should be equal to (3+5)*10
- Output:
80
Nemerle
using System;
using System.Console;
using System.Math;
module Composition
{
Compose[T](f : T -> T, g : T -> T, x : T) : T
{
f(g(x))
}
Main() : void
{
def SinAsin = Compose(Sin, Asin, _);
WriteLine(SinAsin(0.5));
}
}
Never
func compose(f(i : int) -> int, g(i : int) -> int) -> (int) -> int
{
let func (i : int) -> int { f(g(i)) }
}
func dec(i : int) -> int { 10 * i }
func succ(i : int) -> int { i + 1 }
func main() -> int
{
let h = compose(dec, succ);
print(h(1));
0
}
NewLISP
> (define (compose f g) (expand (lambda (x) (f (g x))) 'f 'g))
(lambda (f g) (expand (lambda (x) (f (g x))) 'f 'g))
> ((compose sin asin) 0.5)
0.5
Nim
import sugar
proc compose[A,B,C](f: B -> C, g: A -> B): A -> C = (x: A) => f(g(x))
proc plustwo(x: int): int = x + 2
proc minustwo(x: int): int = x - 2
var plusminustwo = compose(plustwo, minustwo)
echo plusminustwo(10)
Objeck
bundle Default {
class Test {
@f : static : (Int) ~ Int;
@g : static : (Int) ~ Int;
function : Main(args : String[]) ~ Nil {
compose := Composer(F(Int) ~ Int, G(Int) ~ Int);
compose(13)->PrintLine();
}
function : F(a : Int) ~ Int {
return a + 14;
}
function : G(a : Int) ~ Int {
return a + 15;
}
function : Compose(x : Int) ~ Int {
return @f(@g(x));
}
function : Composer(f : (Int) ~ Int, g : (Int) ~ Int) ~ (Int) ~ Int {
@f := f;
@g := g;
return Compose(Int) ~ Int;
}
}
}
prints: 42
ObjectIcon
# -*- ObjectIcon -*-
#
# The Rosetta Code function composition task, in Object Icon.
# Composition will result in a co-expression.
#
# Object Icon co-expressions are closures: they share the local
# variables of the context in which they are created. In Arizona Icon,
# co-expressions obtain only the *values* of those variables. However,
# this difference, despite its significance, is not really important
# to the notion of composition.
#
# This example is adapted from the Unicon implementation of the
# task. To simplify the example, I have removed support for string
# invocations.
#
import io
procedure main (arglist)
local f, g
# f gets a co-expression that is a composition of three procedures.
f := compose(append_exclamation, string_repeat, double_it)
write(123@f)
# g gets a co-expression that is a composition of a procedure and f.
g := compose(string_repeat, f)
write(123@g)
end
procedure double_it (n)
return n + n
end
procedure string_repeat (x)
return string(x) || string(x)
end
procedure append_exclamation (s)
return s || "!"
end
procedure compose (rfL[])
local x, f, saveSource, fL, cf
every push(fL := [], !rfL)
cf := create {
saveSource := &source
repeat {
x := x@saveSource
saveSource := &source
every f := !fL do {
case type(f) of {
"co-expression": x := x@f
default: x := f(x)
}
}
}
}
# Co-expressions often need to be "primed" before they can be
# used.
@cf
return cf
end
- Output:
$ oit -s function_composition-OI.icn && ./function_composition-OI 246246! 246246!246246!
Objective-C
We restrict ourselves to functions that take and return one object.
#include <Foundation/Foundation.h>
typedef id (^Function)(id);
// a commodity for "encapsulating" double f(double)
typedef double (*func_t)(double);
Function encapsulate(func_t f) {
return ^(id x) { return @(f([x doubleValue])); };
}
Function compose(Function a, Function b) {
return ^(id x) { return a(b(x)); };
}
// functions outside...
double my_f(double x)
{
return x+1.0;
}
double my_g(double x)
{
return x*x;
}
int main()
{
@autoreleasepool {
Function f = encapsulate(my_f);
Function g = encapsulate(my_g);
Function composed = compose(f, g);
printf("g(2.0) = %lf\n", [g(@2.0) doubleValue]);
printf("f(2.0) = %lf\n", [f(@2.0) doubleValue]);
printf("f(g(2.0)) = %lf\n", [composed(@2.0) doubleValue]);
}
return 0;
}
OCaml
let compose f g x = f (g x)
Example use:
# let compose f g x = f (g x);;
val compose : ('a -> 'b) -> ('c -> 'a) -> 'c -> 'b = <fun>
# let sin_asin = compose sin asin;;
val sin_asin : float -> float = <fun>
# sin_asin 0.5;;
- : float = 0.5
Octave
function r = compose(f, g)
r = @(x) f(g(x));
endfunction
r = compose(@exp, @sin);
r(pi/3)
Oforth
Oforth uses RPN notation. Function composition of f and g is just calling :
g f
If a block is needed, a compose function can be implemented :
: compose(f, g) #[ g perform f perform ] ;
Usage :
1.2 compose(#asin, #sin) perform
[ 1, 2, 3, 4, 5 ] compose(#[ map(#sqrt) ], #[ filter(#isEven) ]) perform
The last line returns : [1.4142135623731, 2]
Ol
(define (compose f g)
(lambda (x) (f (g x))))
;; or:
(define ((compose f g) x) (f (g x)))
Order
Order supplies the built-in function 8compose
for this purpose. However, a manual implementation might be:
#include <order/interpreter.h>
#define ORDER_PP_DEF_8comp ORDER_PP_FN( \
8fn(8F, 8G, 8fn(8X, 8ap(8F, 8ap(8G, 8X)))) )
Interpreter limitations mean that local variables containing functions must be called with the 8ap
operator, but the functions themselves are still first-class values.
Oz
declare
fun {Compose F G}
fun {$ X}
{F {G X}}
end
end
SinAsin = {Compose Float.sin Float.asin}
in
{Show {SinAsin 0.5}}
PARI/GP
compose(f, g)={
x -> f(g(x))
};
compose(x->sin(x),x->cos(x)(1)
Usage note: In Pari/GP 2.4.3, this can be expressed more succinctly:
compose(sin,cos)(1)
Pascal
See Delphi
Perl
sub compose {
my ($f, $g) = @_;
sub {
$f -> ($g -> (@_))
};
}
use Math::Trig;
print compose(sub {sin $_[0]}, \&asin)->(0.5), "\n";
Phix
There is not really any direct support for this sort of thing in Phix, but it is all pretty trivial to manage explicitly.
In the following, as it stands, you cannot use constant m in the same way as a routine_id, or pass a standard routine_id to call_composite(), but tagging the ctable entries so that you know precisely what to do with each entry does not sound the least bit difficult to me.
sequence ctable = {} function compose(integer f, integer g) ctable = append(ctable,{f,g}) return length(ctable) end function function call_composite(integer f, atom x) integer g {f,g} = ctable[f] return call_func(f,{call_func(g,{x})}) end function function plus1(atom x) return x+1 end function function halve(atom x) return x/2 end function constant m = compose(routine_id("halve"),routine_id("plus1")) ?call_composite(m,1) -- displays 1 ?call_composite(m,4) -- displays 2.5
Phixmonti
def *2 2 * enddef
def ++ 1 + enddef
def composite swap exec swap exec enddef
getid ++ getid *2 3 composite print /# result: 7 #/
PHP
<?php
function compose($f, $g) {
return function($x) use ($f, $g) { return $f($g($x)); };
}
$trim_strlen = compose('strlen', 'trim');
echo $result = $trim_strlen(' Test '), "\n"; // prints 4
?>
works with regular functions as well as functions created by create_function()
<?php
function compose($f, $g) {
return create_function('$x', 'return '.var_export($f,true).'('.var_export($g,true).'($x));');
}
$trim_strlen = compose('strlen', 'trim');
echo $result = $trim_strlen(' Test '), "\n"; // prints 4
?>
PicoLisp
(de compose (F G)
(curry (F G) (X)
(F (G X)) ) )
(def 'a (compose inc dec))
(def 'b (compose 'inc 'dec))
(def 'c (compose '((A) (inc A)) '((B) (dec B))))
: (a 7)
-> 7
: (b 7)
-> 7
: (c 7)
-> 7
PostScript
/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
/square { dup mul } def
/plus1 { 1 add } def
/sqPlus1 /square load /plus1 load compose def
PowerShell
You can simply call g inside f like this:
function g ($x) {
$x + $x
}
function f ($x) {
$x*$x*$x
}
f (g 1)
Or g and f can become paramaters of a new function fg
function fg (${function:f}, ${function:g}, $x) {
f (g $x)
}
fg f g 1
In both cases the answer is:
8
Prolog
Works with SWI-Prolog and module lambda, written by Ulrich Neumerkel found there http://www.complang.tuwien.ac.at/ulrich/Prolog-inedit/lambda.pl
:- use_module(lambda).
compose(F,G, FG) :-
FG = \X^Z^(call(G,X,Y), call(F,Y,Z)).
- Output:
?- compose(sin, asin, F), call(F, 0.5, Y). F = \_G4586^_G4589^ (call(asin,_G4586,_G4597),call(sin,_G4597,_G4589)), Y = 0.5.
PureBasic
;Declare how our function looks like
Prototype.i Func(Arg.i)
; Make a procedure that composes any functions of type "Func"
Procedure Compose(*a.Func,*b.Func, x)
ProcedureReturn *a(*b(x))
EndProcedure
; Just a procedure fitting "Func"
Procedure f(n)
ProcedureReturn 2*n
EndProcedure
; Yet another procedure fitting "Func"
Procedure g(n)
ProcedureReturn n+1
EndProcedure
;- Test it
X=Random(100)
Title$="With x="+Str(x)
Body$="Compose(f(),g(), x) ="+Str(Compose(@f(),@g(),X))
MessageRequester(Title$,Body$)
Purity
data compose = f => g => $f . $g
Python
Simple composition of two functions
compose = lambda f, g: lambda x: f( g(x) )
Example use:
>>> compose = lambda f, g: lambda x: f( g(x) )
>>> from math import sin, asin
>>> sin_asin = compose(sin, asin)
>>> sin_asin(0.5)
0.5
>>>
Or, expanding slightly:
from math import (acos, cos, asin, sin)
# compose (<<<) :: (b -> c) -> (a -> b) -> a -> c
def compose(g, f):
'''Right to left function composition.'''
return lambda x: g(f(x))
# main :: IO ()
def main():
'''Test'''
print(list(map(
lambda f: f(0.5),
zipWith(compose)(
[sin, cos, lambda x: x ** 3.0]
)([asin, acos, lambda x: x ** (1 / 3.0)])
)))
# GENERIC FUNCTIONS ---------------------------------------
# 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: (
map(f, xs, ys)
)
if __name__ == '__main__':
main()
- Output:
[0.49999999999999994, 0.5000000000000001, 0.5000000000000001]
Multiple composition
Nested composition of several functions can be streamlined by using functools.reduce.
from functools import reduce
from math import sqrt
def compose(*fs):
'''Composition, from right to left,
of an arbitrary number of functions.
'''
def go(f, g):
return lambda x: f(g(x))
return reduce(go, fs, lambda x: x)
# ------------------------- TEST -------------------------
def main():
'''Composition of three functions.'''
f = compose(
half,
succ,
sqrt
)
print(
f(5)
)
# ----------------------- GENERAL ------------------------
def half(n):
return n / 2
def succ(n):
return 1 + n
if __name__ == '__main__':
main()
- Output:
1.618033988749895
composition via operator overloading
Here need composition of several functions is reduced with classes.
# Contents of `pip install compositions'
class Compose(object):
def __init__(self, func):
self.func = func
def __call__(self, x):
return self.func(x)
def __mul__(self, neighbour):
return Compose(lambda x: self.func(neighbour.func(x)))
# from composition.composition import Compose
if __name__ == "__main__":
# Syntax 1
@Compose
def f(x):
return x
# Syntax 2
g = Compose(lambda x: x)
print((f * g)(2))
Qi
Qi supports partial applications, but only when calling a function with one argument.
(define compose
F G -> (/. X
(F (G X))))
((compose (+ 1) (+ 2)) 3) \ (Outputs 6) \
Alternatively, it can be done like this:
(define compose F G X -> (F (G X)))
(((compose (+ 1)) (+ 2)) 3) \ (Outputs 6) \
Quackery
[ nested swap
nested swap join ] is compose ( g f --> [ )
( ----- demonstration ----- )
( create a named nest -- equivalent to a function )
[ 2 * ] is double ( n --> n )
( "[ 4 + ]" is an unnamed nest
-- equivalent to a lambda function. )
( "quoting" a nest with ' puts it on the stack
rather than it being evaluated. "do" evaluates
the top of stack. )
19 ' double ' [ 4 + ] compose do echo
- Output:
42
R
compose <- function(f,g) function(x) { f(g(x)) }
r <- compose(sin, cos)
print(r(.5))
Racket
(define (compose f g)
(lambda (x) (f (g x))))
Also available as a compose1 builtin, and a more general compose where one function can produce multiple arguments that are sent the the next function in the chain. (Note however that this is rarely desired.)
Raku
(formerly Perl 6)
The function composition operator is ∘, U+2218 RING OPERATOR (with a "Texas" version o for the Unicode challenged). Here we compose a routine, an operator, and a lambda:
sub triple($n) { 3 * $n }
my &f = &triple ∘ &prefix:<-> ∘ { $^n + 2 };
say &f(5); # prints "-21".
REBOL
REBOL [
Title: "Functional Composition"
URL: http://rosettacode.org/wiki/Functional_Composition
]
; "compose" means something else in REBOL, therefore I use a 'compose-functions name.
compose-functions: func [
{compose the given functions F and G}
f [any-function!]
g [any-function!]
] [
func [x] compose [(:f) (:g) x]
]
Functions "foo" and "bar" are used to prove that composition actually took place by attaching their signatures to the result.
foo: func [x] [reform ["foo:" x]]
bar: func [x] [reform ["bar:" x]]
foo-bar: compose-functions :foo :bar
print ["Composition of foo and bar:" mold foo-bar "test"]
sin-asin: compose-functions :sine :arcsine
print [crlf "Composition of sine and arcsine:" sin-asin 0.5]
- Output:
Composition of foo and bar: "foo: bar: test" Composition of sine and arcsine: 0.5
REXX
compose: procedure; parse arg f,g,x; interpret 'return' f"(" g'(' x "))"
exit /*control should never gets here, but this was added just in case.*/
Ring
# Project : Function composition
sumprod = func1(:func2,2,3)
see sumprod + nl
func func1(func2,x,y)
temp = call func2(x,y)
res = temp + x + y
return res
func func2(x,y)
res = x * y
return res
Output:
11
RPL
« →STR SWAP →STR + DUP "»«" POS " " REPL STR→ » 'FCOMP' STO @ ( « f » « g » → « f o g » ) ≪ ALOG ≫ ≪ COS ≫ FCOMP ≪ ALOG ≫ ≪ COS ≫ FCOMP 0 EVAL ≪ ALOG ≫ ≪ COS ≫ FCOMP 'x' EVAL
- Output:
3: ≪ COS ALOG ≫ 2: 10 1: 'ALOG(COS(x))'
Ruby
This compose method gets passed two Method objects or Proc objects
def compose(f,g)
lambda {|x| f[g[x]]}
end
s = compose(Math.method(:sin), Math.method(:cos))
p s[0.5] # => 0.769196354841008
# verify
p Math.sin(Math.cos(0.5)) # => 0.769196354841008
Rust
In order to return a closure (anonymous function) in Stable Rust, it must be wrapped in a layer of indirection via a heap allocation. However, there is a feature coming down the pipeline (currently available in Nightly) which makes this possible. Both of the versions below are in the most general form i.e. their arguments may be functions or closures with the only restriction being that the output of g
is the same type as the input of f
.
Stable
Function is allocated on the heap and is called via dynamic dispatch
fn compose<'a,F,G,T,U,V>(f: F, g: G) -> Box<Fn(T) -> V + 'a>
where F: Fn(U) -> V + 'a,
G: Fn(T) -> U + 'a,
{
Box::new(move |x| f(g(x)))
}
Nightly
Function is returned on the stack and is called via static dispatch (monomorphized)
#![feature(conservative_impl_trait)]
fn compose<'a,F,G,T,U,V>(f: F, g: G) -> impl Fn(T) -> V + 'a
where F: Fn(U) -> V + 'a,
G: Fn(T) -> U + 'a,
{
move |x| f(g(x))
}
Scala
def compose[A](f: A => A, g: A => A) = { x: A => f(g(x)) }
def add1(x: Int) = x+1
val add2 = compose(add1, add1)
We can achieve a more natural style by creating a container class for composable functions, which provides the compose method 'o':
class Composable[A](f: A => A) {
def o (g: A => A) = compose(f, g)
}
implicit def toComposable[A](f: A => A) = new Composable(f)
val add3 = (add1 _) o add2
> (add2 o add3)(37) res0: Int = 42
Scheme
(define (compose f g) (lambda (x) (f (g x))))
;; or:
(define ((compose f g) x) (f (g x)))
;; or to compose an arbitrary list of 1 argument functions:
(define-syntax compose
(lambda (x)
(syntax-case x ()
((_) #'(lambda (y) y))
((_ f) #'f)
((_ f g h ...) #'(lambda (y) (f ((compose g h ...) y)))))))
Example:
(display ((compose sin asin) 0.5))
(newline)
- Output:
0.5
Sidef
func compose(f, g) {
func(x) { f(g(x)) }
}
var fg = compose(func(x){ sin(x) }, func(x){ cos(x) })
say fg(0.5) # => 0.76919635484100842185251475805107
Slate
Function (method) composition is standard:
[| :x | x + 1] ** [| :x | x squared] applyTo: {3}
Smalltalk
| composer fg |
composer := [ :f :g | [ :x | f value: (g value: x) ] ].
fg := composer value: [ :x | x + 1 ]
value: [ :x | x * x ].
(fg value:3) displayNl.
Standard ML
This is already defined as the o operator in Standard ML.
fun compose (f, g) x = f (g x)
Example use:
- fun compose (f, g) x = f (g x);
val compose = fn : ('a -> 'b) * ('c -> 'a) -> 'c -> 'b
- val sin_asin = compose (Math.sin, Math.asin);
val sin_asin = fn : real -> real
- sin_asin 0.5;
val it = 0.5 : real
SuperCollider
has a function composition operator (the message `<>`):
f = { |x| x + 1 };
g = { |x| x * 2 };
h = g <> f;
h.(8); // returns 18
Swift
func compose<A,B,C>(f: (B) -> C, g: (A) -> B) -> (A) -> C {
return { f(g($0)) }
}
let sin_asin = compose(sin, asin)
println(sin_asin(0.5))
- Output:
0.5
Tcl
This creates a compose
procedure that returns an anonymous function term that should be expanded as part of application to its argument.
package require Tcl 8.5
namespace path {::tcl::mathfunc}
proc compose {f g} {
list apply [list {f g x} {{*}$f [{*}$g $x]}] $f $g]
}
set sin_asin [compose sin asin]
{*}$sin_asin 0.5 ;# ==> 0.5
{*}[compose abs int] -3.14 ;# ==> 3
Transd
#lang transd
MainModule: {
// Make a short alias for a function type that takes a string and
// returns a string. Call it 'Shader'.
Shader: typealias(Lambda<String String>),
// 'composer' function takes two Shaders, combines them into
// a single Shader, which is a capturing closure, аnd returns
// this closure to the caller.
// [[f1,f2]] is a list of captured variables
composer: (λ f1 Shader() f2 Shader()
(ret Shader(λ[[f1,f2]] s String() (exec f1 (exec f2 s))))),
_start: (λ
// create a combined shader as a local variable 'render'
locals: render (composer
Shader(λ s String() (ret (toupper s)))
Shader(λ s String() (ret (+ s "!"))))
// call this combined shader as a usual shader with passing
// a string to it, аnd receiving from it the combined result of
// its two captured shaders
(textout (exec render "hello")))
}
- Output:
HELLO!
TypeScript
function compose<T, U, V> (fn1: (input: T) => U, fn2: (input: U) => V){
return function(value: T) {
return fn2(fn1(value))
}
}
function size (s: string): number { return s.length; }
function isEven(x: number): boolean { return x % 2 === 0; }
const evenSize = compose(size, isEven);
console.log(evenSize("ABCD")) // true
console.log(evenSize("ABC")) // false
uBasic/4tH
Print FUNC(_Compose (_f, _g, 3))
End
_Compose Param (3) : Return (FUNC(a@(FUNC(b@(c@)))))
_f Param (1) : Return (a@ + 1)
_g Param (1) : Return (a@ * 2)
UNIX Shell
Each function takes its argument from standard input,
and puts its result to standard output.
Then the composition of f and g is a shell pipeline, c() { g | f; }
.
compose() {
eval "$1() { $3 | $2; }"
}
downvowel() { tr AEIOU aeiou; }
upcase() { tr a-z A-Z; }
compose c downvowel upcase
echo 'Cozy lummox gives smart squid who asks for job pen.' | c
# => CoZY LuMMoX GiVeS SMaRT SQuiD WHo aSKS FoR JoB PeN.
This solution uses no external tools, just Bash itself.
#compose a new function consisting of the application of 2 unary functions
compose () { f="$1"; g="$2"; x="$3"; "$f" "$("$g" "$x")";}
chartolowervowel()
# Usage: chartolowervowel "A" --> "a"
#Based on a to_upper script in Chris F. A. Johnson's book Pro Bash Programming Ch7. String Manipulation
#(with minor tweaks to use local variables and return the value of the converted character
#http://cfajohnson.com/books/cfajohnson/pbp/
#highly recommended I have a copy and have bought another for a friend
{
local LWR="";
case $1 in
A*) _LWR=a ;;
# B*) _LWR=b ;;
# C*) _LWR=c ;;
# D*) _LWR=d ;;
E*) _LWR=e ;;
# F*) _LWR=f ;;
# G*) _LWR=g ;;
# H*) _LWR=h ;;
I*) _LWR=i ;;
# J*) _LWR=j ;;
# K*) _LWR=k ;;
# L*) _LWR=L ;;
# M*) _LWR=m ;;
# N*) _LWR=n ;;
O*) _LWR=o ;;
# P*) _LWR=p ;;
# Q*) _LWR=q ;;
# R*) _LWR=r ;;
# S*) _LWR=s ;;
# T*) _LWR=t ;;
U*) _LWR=u ;;
# V*) _LWR=v ;;
# W*) _LWR=w ;;
# X*) _LWR=x ;;
# Y*) _LWR=y ;;
# Z*) _LWR=z ;;
*) _LWR=${1%${1#?}} ;;
esac;
echo "$_LWR";
}
strdownvowel()
# Usage: strdownvowel "STRING" --> "STRiNG"
#Based on an upword script in Chris F. A. Johnson's book Pro Bash Programming Ch7. String Manipulation
#(with minor tweaks to use local variables and return the value of the converted string
#http://cfajohnson.com/books/cfajohnson/pbp/
#highly recommended I have a copy and have bought another for a friend
{
local _DWNWORD=""
local word="$1"
while [ -n "$word" ] ## loop until nothing is left in $word
do
chartolowervowel "$word" >> /dev/null
_DWNWORD=$_DWNWORD$_LWR
word=${word#?} ## remove the first character from $word
done
Echo "$_DWNWORD"
}
chartoupper()
# Usage: chartoupper "s" --> "S"
#From Chris F. A. Johnson's book Pro Bash Programming Ch7. String Manipulation
#(with minor tweaks to use local variables and return the value of the converted character
#http://cfajohnson.com/books/cfajohnson/pbp/
#highly recommended I have a copy and have bought another for a friend
{
local UPR="";
case $1 in
a*) _UPR=A ;;
b*) _UPR=B ;;
c*) _UPR=C ;;
d*) _UPR=D ;;
e*) _UPR=E ;;
f*) _UPR=F ;;
g*) _UPR=G ;;
h*) _UPR=H ;;
i*) _UPR=I ;;
j*) _UPR=J ;;
k*) _UPR=K ;;
l*) _UPR=L ;;
m*) _UPR=M ;;
n*) _UPR=N ;;
o*) _UPR=O ;;
p*) _UPR=P ;;
q*) _UPR=Q ;;
r*) _UPR=R ;;
s*) _UPR=S ;;
t*) _UPR=T ;;
u*) _UPR=U ;;
v*) _UPR=V ;;
w*) _UPR=W ;;
x*) _UPR=X ;;
y*) _UPR=Y ;;
z*) _UPR=Z ;;
*) _UPR=${1%${1#?}} ;;
esac;
echo "$_UPR";
}
strupcase()
# Usage: strupcase "string" --> "STRING"
#Based on an upword script in Chris F. A. Johnson's book Pro Bash Programming Ch7. String Manipulation
#(with minor tweaks to use local variables and return the value of the converted string
#http://cfajohnson.com/books/cfajohnson/pbp/
#highly recommended I have a copy and have bought another for a friend
{
local _UPWORD=""
local word="$1"
while [ -n "$word" ] ## loop until nothing is left in $word
do
chartoupper "$word" >> /dev/null
_UPWORD=$_UPWORD$_UPR
word=${word#?} ## remove the first character from $word
done
Echo "$_UPWORD"
}
compose strdownvowel strupcase "Cozy lummox gives smart squid who asks for job pen."
# --> CoZY LuMMoX GiVeS SMaRT SQuiD WHo aSKS FoR JoB PeN.
es
With shell pipelines:
fn compose f g {
result @ {$g | $f}
}
fn downvowel {tr AEIOU aeiou}
fn upcase {tr a-z A-Z}
fn-c = <={compose $fn-downvowel $fn-upcase}
echo 'Cozy lummox gives smart squid who asks for job pen.' | c
# => CoZY LuMMoX GiVeS SMaRT SQuiD WHo aSKS FoR JoB PeN.
With function arguments:
fn compose f g {
result @ x {result <={$f <={$g $x}}}
}
fn downvowel x {result `` '' {tr AEIOU aeiou <<< $x}}
fn upcase x {result `` '' {tr a-z A-Z <<< $x}}
fn-c = <={compose $fn-downvowel $fn-upcase}
echo <={c 'Cozy lummox gives smart squid who asks for job pen.'}
# => CoZY LuMMoX GiVeS SMaRT SQuiD WHo aSKS FoR JoB PeN.
Unlambda
``s`ksk
Ursala
Functional composition is a built in operation expressible as f+g for functions f and g, hence hardly worth defining. However, it could be defined without using the operator like this.
compose("f","g") "x" = "f" "g" "x"
test program:
#import nat
#cast %n
test = compose(successor,double) 3
- Output:
7
VBScript
I'm not convinced that this is really a 'closure'. It looks to me more like a cute trick with Eval().
Implementation
option explicit
class closure
private composition
sub compose( f1, f2 )
composition = f2 & "(" & f1 & "(p1))"
end sub
public default function apply( p1 )
apply = eval( composition )
end function
public property get formula
formula = composition
end property
end class
Invocation
dim c
set c = new closure
c.compose "ucase", "lcase"
wscript.echo c.formula
wscript.echo c("dog")
c.compose "log", "exp"
wscript.echo c.formula
wscript.echo c(12.3)
function inc( n )
inc = n + 1
end function
c.compose "inc", "inc"
wscript.echo c.formula
wscript.echo c(12.3)
function twice( n )
twice = n * 2
end function
c.compose "twice", "inc"
wscript.echo c.formula
wscript.echo c(12.3)
- Output:
lcase(ucase(p1)) dog exp(log(p1)) 12.3 inc(inc(p1)) 14.3 inc(twice(p1)) 25.6
WDTE
The simplest way is with a lambda:
let compose f g => (@ c x => g x -> f);
Alternatively, you can take advantage of partial function calls:
let compose f g x => g x -> f;
Both can be used as follows:
(compose (io.writeln io.stdout) !) true;
Output:
false
Wortel
The @
operator applied to a array literal will compose the functions in the array and ^
with a group literal will do the same, but also quotes operators.
! @[f g] x ; f(g(x))
! ^(f g) x ; f(g(x))
Defining the compose
function
@var compose &[f g] &x !f!g x
Wren
var compose = Fn.new { |f, g| Fn.new { |x| f.call(g.call(x)) } }
var double = Fn.new { |x| 2 * x }
var addOne = Fn.new { |x| x + 1 }
System.print(compose.call(double, addOne).call(3))
- Output:
8
zkl
Utils.Helpers.fcomp('+(1),'*(2))(5) //-->11
Which is implemented with a closure (.fp1), which fixes the second paramter
fcn fcomp(f,g,h,etc){
{ fcn(x,hgf){ T(x).pump(Void,hgf.xplode()) }.fp1(vm.arglist.reverse()); }
ZX Spectrum Basic
DEF FN commands can be nested, making this appear trivial:
10 DEF FN f(x)=SQR x
20 DEF FN g(x)=ABS x
30 DEF FN c(x)=FN f(FN g(x))
40 PRINT FN c(-4)
Which gets you f(g(x)), for sure. But if you want g(f(x)) you need to DEF a whole new FN. Instead we can pass the function names as strings to a new function and numerically evaluate the string:
10 DEF FN f(x)=SQR x
20 DEF FN g(x)=ABS x
30 DEF FN c(a$,b$,x)=VAL ("FN "+a$+"(FN "+b$+"(x))")
40 PRINT FN c("f","g",-4)
50 PRINT FN c("g","f",-4)
- Output:
2 A Invalid argument, 50:1
- Programming Tasks
- Higher-order functions
- 11l
- ActionScript
- Ada
- Agda
- Aikido
- Aime
- ALGOL 68
- Amazing Hopper
- AntLang
- AppleScript
- Applesoft BASIC
- Argile
- Arturo
- ATS
- AutoHotkey
- BBC BASIC
- Bori
- Binary Lambda Calculus
- BQN
- Bracmat
- Brat
- Bruijn
- C
- C sharp
- C++
- Clojure
- CoffeeScript
- Common Lisp
- Crystal
- D
- Delphi
- Diego
- Dylan
- Déjà Vu
- E
- EchoLisp
- Ela
- Elena
- Elixir
- Emacs Lisp
- Erlang
- Euphoria/Omit
- F Sharp
- Factor
- Fantom
- Forth
- Fortran
- Fortress
- FreeBASIC
- FunL
- Fōrmulæ
- GAP
- Go
- Groovy
- Haskell
- Hy
- Icon
- Unicon
- J
- Janet
- Java
- JavaScript
- Joy
- Jq
- Julia
- K
- Klingphix
- Kotlin
- Lambdatalk
- Lang
- LFE
- Lingo
- LOLCODE
- Lua
- M2000 Interpreter
- Mathcad
- Mathematica
- Wolfram Language
- Maxima
- Min
- MiniScript
- Nemerle
- Never
- NewLISP
- Nim
- Objeck
- ObjectIcon
- Objective-C
- OCaml
- Octave
- Oforth
- Ol
- Order
- Oz
- PARI/GP
- Pascal
- Perl
- Phix
- Phixmonti
- PHP
- PicoLisp
- PostScript
- PowerShell
- Prolog
- PureBasic
- Purity
- Python
- Qi
- Quackery
- R
- Racket
- Raku
- REBOL
- REXX
- Ring
- RPL
- Ruby
- Rust
- Scala
- Scheme
- Sidef
- Slate
- Smalltalk
- Standard ML
- SuperCollider
- Swift
- Tcl
- Transd
- TypeScript
- UBasic/4tH
- UNIX Shell
- Es
- Unlambda
- Ursala
- TI-83 BASIC/Omit
- TI-89 BASIC/Omit
- Fortran/Omit
- VBScript
- WDTE
- Wortel
- Wren
- Zkl
- ZX Spectrum Basic
- Pages with too many expensive parser function calls