Function composition: Difference between revisions

m
syntax hghlighting fixup automation
m (syntax hghlighting fixup automation)
Line 20:
{{trans|Python}}
 
<langsyntaxhighlight lang="11l">V compose = (f, g) -> (x -> @f(@g(x)))
V sin_asin = compose(x -> sin(x), x -> asin(x))
print(sin_asin(0.5))</langsyntaxhighlight>
 
{{out}}
Line 31:
=={{header|ActionScript}}==
ActionScript supports closures, making function composition very straightforward.
<langsyntaxhighlight ActionScriptlang="actionscript">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));
}</langsyntaxhighlight>
 
=={{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):
<langsyntaxhighlight lang="ada">generic
type Argument is private;
package Functions is
Line 52:
private
type Func is array (Positive range <>) of Primitive_Operation;
end Functions;</langsyntaxhighlight>
Here is an implementation;
<langsyntaxhighlight lang="ada">package body Functions is
function "*" (Left : Func; Right : Argument) return Argument is
Result : Argument := Right;
Line 78:
return (Left, Right);
end "*";
end Functions;</langsyntaxhighlight>
The following is an example of use:
<langsyntaxhighlight lang="ada">with Ada.Numerics.Elementary_Functions; use Ada.Numerics.Elementary_Functions;
with Ada.Text_IO; use Ada.Text_IO;
with Functions;
Line 91:
begin
Put_Line (Float'Image (Sin_Arcsin * 0.5));
end Test_Compose;</langsyntaxhighlight>
{{out}}
<pre>
Line 98:
 
=={{header|Agda}}==
<langsyntaxhighlight Agdalang="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)</langsyntaxhighlight>
 
=={{header|Aikido}}==
<langsyntaxhighlight lang="aikido">
import math
 
Line 115:
println (func(0.5)) // 0.5
 
</syntaxhighlight>
</lang>
 
=={{header|Aime}}==
<langsyntaxhighlight lang="aime">compose_i(,,)
{
($0)(($1)($2));
Line 143:
 
0;
}</langsyntaxhighlight>
{{Out}}
<pre>6400</pre>
Line 154:
violates standard '''ALGOL 68''''s scoping rules. [[ALGOL 68G]] warns about this during
parsing, and then rejects during runtime.
<langsyntaxhighlight lang="algol68">MODE F = PROC(REAL)REAL; # ALGOL 68 is strong typed #
 
# As a procedure for real to real functions #
Line 163:
# Example use: #
F sin arc sin = compose(sin, arc sin);
print((sin arc sin(0.5), (sin O arc sin)(0.5), new line))</langsyntaxhighlight>
{{out}}
<pre>
Line 172:
{{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}}
<langsyntaxhighlight lang="algol68">MODE F = PROC(REAL)REAL; # ALGOL 68 is strong typed #
 
# As a procedure for real to real functions #
Line 182:
# Example use: #
F sin arc sin = compose(sin, arc sin);
print((sin arc sin(0.5), (sin O arc sin)(0.5), new line))</langsyntaxhighlight>
 
=={{header|AntLang}}==
<langsyntaxhighlight AntLanglang="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]}}</langsyntaxhighlight>
 
=={{header|AppleScript}}==
<langsyntaxhighlight lang="applescript">-- Compose two functions where each function is
-- a script object with a call(x) handler.
on compose(f, g)
Line 214:
 
compose(sqrt, twice)'s call(32)
-- Result: 8.0</langsyntaxhighlight>
 
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:
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).
 
<langsyntaxhighlight lang="applescript">------------ COMPOSITION OF A LIST OF FUNCTIONS ----------
 
-- compose :: [(a -> a)] -> (a -> a)
Line 285:
end script
end if
end mReturn</langsyntaxhighlight>
{{Out}}
<pre>1.61803398875</pre>
 
=={{header|Applesoft BASIC}}==
<langsyntaxhighlight ApplesoftBasiclang="applesoftbasic">10 F$ = "SIN"
20 DEF FN A(P) = ATN(P/SQR(-P*P+1))
30 G$ = "FN A"
Line 307:
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</langsyntaxhighlight>
 
=={{header|Argile}}==
Only works for functions taking real and returning real (double precision, 64 bits)
{{works with|Argile|1.0.0}}
<langsyntaxhighlight Argilelang="argile">use std, math
 
let my_asin = new Function (.:<any,real x>:. -> real {asin x})
Line 354:
f.func = func
f.data = data
f</langsyntaxhighlight>
 
=={{header|Arturo}}==
 
<langsyntaxhighlight lang="rebol">compose: function [f,g] ->
return function [x].import:[f,g][
call f @[call g @[x]]
Line 365:
splitupper: compose 'split 'upper
 
print call 'splitupper ["done"]</langsyntaxhighlight>
 
{{out}}
Line 381:
In ATS we have closures, but of more than one kind.
 
<langsyntaxhighlight lang="ats">(*
The task:
 
Line 426:
println! (z : double);
println! (w : double)
end</langsyntaxhighlight>
 
{{out}}
Line 435:
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:
 
<langsyntaxhighlight lang="ats">#include "share/atspre_staload.hats"
 
fn {t1, t2, t3 : t@ype}
Line 462:
println! (z : double);
println! (w : double)
end</langsyntaxhighlight>
 
{{out}}
Line 471:
One could even make the composition procedures themselves be closures:
 
<langsyntaxhighlight lang="ats">#include "share/atspre_staload.hats"
 
fn {t1, t2, t3 : t@ype}
Line 499:
println! (z : double);
println! (w : double)
end</langsyntaxhighlight>
 
{{out}}
Line 508:
=={{header|AutoHotkey}}==
contributed by Laszlo on the ahk [http://www.autohotkey.com/forum/post-276379.html#276379 forum]
<langsyntaxhighlight AutoHotkeylang="autohotkey">MsgBox % compose("sin","cos",1.5)
 
compose(f,g,x) { ; function composition
Return %f%(%g%(x))
}</langsyntaxhighlight>
 
=={{header|BBC BASIC}}==
{{works with|BBC BASIC for Windows}}
<langsyntaxhighlight lang="bbcbasic"> REM Create some functions for testing:
DEF FNsqr(a) = SQR(a)
DEF FNabs(a) = ABS(a)
Line 532:
\ CHR$&A4 + "(&" + STR$~(p%+4) + ")(x))"
DIM p% LEN(f$) + 4 : $(p%+4) = f$ : !p% = p%+4
= p%</langsyntaxhighlight>
{{out}}
<pre>
Line 539:
 
=={{header|Bori}}==
<langsyntaxhighlight lang="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)); }
Line 547:
double d = compose(sin, asin, 0.5);
label1.setText(d.toString(9));
}</langsyntaxhighlight>
{{out}} on Android phone:
<syntaxhighlight lang ="bori">0.500000000</langsyntaxhighlight>
 
=={{header|BQN}}==
Line 555:
As a 2-modifier:
 
<syntaxhighlight lang ="bqn">_compose_ ← ∘</langsyntaxhighlight>
 
Or:
 
<syntaxhighlight lang ="bqn">_compose_ ← {𝔽𝔾𝕩}</langsyntaxhighlight>
 
As a dyadic function:
 
<syntaxhighlight lang ="bqn">Compose ← {𝕏∘𝕎}</langsyntaxhighlight>
 
This is how you can use it:
Line 578:
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>.
 
<langsyntaxhighlight Bracmatlang="bracmat">( ( compose
= f g
. !arg:(?f.?g)&'(.($f)$(($g)$!arg))
Line 597:
& FahrenheitToCelsiusExample$0
& FahrenheitToCelsiusExample$100
)</langsyntaxhighlight>
 
<pre>0 °F in °C = -1,78*10E1
Line 603:
 
=={{header|Brat}}==
<langsyntaxhighlight lang="brat">compose = { f, g | { x | f g x } }
#Test
Line 609:
double = { x | x * 2 }
b = compose(->double ->add1)
p b 1 #should print 4</langsyntaxhighlight>
 
=={{header|C}}==
Only works for functions taking a double and returning a double:
<langsyntaxhighlight lang="c">#include <stdlib.h>
 
/* generic interface for functors from double to double */
Line 676:
 
return 0;
}</langsyntaxhighlight>
 
=={{header|C sharp|C#}}==
<langsyntaxhighlight lang="csharp">using System;
class Program
{
Line 696:
}
}
}</langsyntaxhighlight>
 
=={{header|C++}}==
<langsyntaxhighlight lang="cpp">#include <functional>
#include <cmath>
#include <iostream>
Line 733:
 
return 0;
}</langsyntaxhighlight>
 
{{works with|C++11}} composing <code>std::function</code>
<langsyntaxhighlight lang="cpp">#include <iostream>
#include <functional>
#include <cmath>
Line 749:
std::function<double(double)> g = asin;
std::cout << compose(f, g)(0.5) << std::endl;
}</langsyntaxhighlight>
 
{{Works with|C++14}}
This much simpler version uses <code>decltype(auto)</code>.
<langsyntaxhighlight lang="cpp">#include <iostream>
#include <cmath>
Line 763:
int main() {
std::cout << compose(sin, asin)(0.5) << "\n";
}</langsyntaxhighlight>
 
{{works with|GCC}} Not standard C++, but GCC has a built-in compose function
<langsyntaxhighlight lang="cpp">#include <iostream>
#include <cmath>
#include <ext/functional>
Line 772:
int main() {
std::cout << __gnu_cxx::compose1(std::ptr_fun(::sin), std::ptr_fun(::asin))(0.5) << std::endl;
}</langsyntaxhighlight>
 
'''Works with:''' C++20
<langsyntaxhighlight lang="cpp">#include <iostream>
#include <cmath>
Line 785:
std::cout << compose(sin, asin)(0.5) << "\n";
}
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 794:
 
A manual implementation could look like this:
<langsyntaxhighlight lang="clojure">(defn compose [f g]
(fn [x]
(f (g x))))
Line 800:
; Example
(def inc2 (compose inc inc))
(println (inc2 5)) ; prints 7</langsyntaxhighlight>
 
=={{header|CoffeeScript}}==
<langsyntaxhighlight lang="coffeescript">
compose = ( f, g ) -> ( x ) -> f g x
 
Line 819:
console.log "addFirst 2 #=> #{ addFirst 2 }"
console.log "multiple 2 #=> #{ multiple 2 }"
</syntaxhighlight>
</lang>
 
{{out}}
Line 832:
Or, extending the <code>Function</code> prototype.
 
<langsyntaxhighlight lang="coffeescript">
Function::of = (f) -> (args...) => @ f args...
 
Line 848:
console.log "addFirst 2 #=> #{ addFirst 2 }"
console.log "multiple 2 #=> #{ multiple 2 }"
</syntaxhighlight>
</lang>
 
Output is identical.
Line 854:
=={{header|Common Lisp}}==
<code>compose</code> returns a function that closes on the lexical variables f and g.
<langsyntaxhighlight lang="lisp">(defun compose (f g) (lambda (x) (funcall f (funcall g x))))</langsyntaxhighlight>
 
Example use:
<langsyntaxhighlight lang="lisp">>(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</langsyntaxhighlight>
 
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.
 
<langsyntaxhighlight lang="lisp">(defun compose (f g)
(eval `(lambda (x) (funcall ',f (funcall ',g x)))))</langsyntaxhighlight>
 
----
 
In this last example, a macro is used to compose any number of single parameter functions.
<langsyntaxhighlight lang="lisp">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))))</langsyntaxhighlight>
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)
Line 892:
=={{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>.
<langsyntaxhighlight lang="ruby">require "math"
 
def compose(f : Proc(T, _), g : Proc(_, _)) forall T
Line 898:
end
 
compose(->Math.sin(Float64), ->Math.asin(Float64)).call(0.5) #=> 0.5</langsyntaxhighlight>
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}}==
<langsyntaxhighlight lang="d">import std.stdio;
 
T delegate(S) compose(T, U, S)(in T delegate(U) f,
Line 912:
writeln(compose((int x) => x + 15, (int x) => x ^^ 2)(10));
writeln(compose((int x) => x ^^ 2, (int x) => x + 15)(10));
}</langsyntaxhighlight>
{{out}}
<pre>115
Line 921:
Anonymous methods were introduced in Delphi 2009, so next code works with Delphi 2009 and above:
 
<langsyntaxhighlight Delphilang="delphi">program AnonCompose;
 
{$APPTYPE CONSOLE}
Line 957:
Writeln(Func3(6)); // 36 = 6 * 3 * 2
Readln;
end.</langsyntaxhighlight>
 
=={{header|Diego}}==
Function composition of two simple functions:
<langsyntaxhighlight lang="diego">set_namespace(rosettacode);
 
begin_funct(compose)_arg(f, g);
Line 969:
me_msg()_funct(compose)_arg(f)_sin()_arg(g)_asin()_var(x)_value(0.5); // result: 0.5
 
reset_namespace[];</langsyntaxhighlight>
 
Function composition of two calculated functions:
<langsyntaxhighlight lang="diego">set_namespace(rosettacode);
 
with_funct(f)_arg({int}, x)_ret()_calc([x] * [x]);
Line 984:
// or me_msg()_funct(compose)_arg({f}, f)_arg({g}, g)_var(x)_v(10);
 
reset_ns[];</langsyntaxhighlight>
 
=={{header|Dylan}}==
Line 990:
compose[https://opendylan.org/books/drm/Functional_Operations#compose] is already part of the language standard, with a more complete definition than this.
 
<langsyntaxhighlight lang="dylan">
define method compose(f,g)
method(x) f(g(x)) end
end;
</syntaxhighlight>
</lang>
 
=={{header|Déjà Vu}}==
It is already defined in the standard library as <code>$</code>.
 
<langsyntaxhighlight lang="dejavu">compose f g:
labda:
f g</langsyntaxhighlight>
 
=={{header|E}}==
 
<langsyntaxhighlight lang="e">def compose(f, g) {
return fn x { return f(g(x)) }
}</langsyntaxhighlight>
 
=={{header|EchoLisp}}==
<langsyntaxhighlight lang="lisp">
;; By decreasing order of performance
;; 1) user definition : lambda and closure
Line 1,027:
(define (sincos x) (sin (cos x)))
sincos → (λ (_x) (⭕️ #sin (#cos _x)))
</syntaxhighlight>
</lang>
{{out}}
<langsyntaxhighlight lang="lisp">
((ucompose sin cos) 3) → -0.8360218615377305
((compose sin cos) 3) → -0.8360218615377305
(sincos 3) → -0.8360218615377305
</syntaxhighlight>
</lang>
 
=={{header|Ela}}==
It is already defined in standard prelude as (<<) operator.
 
<langsyntaxhighlight lang="ela">let compose f g x = f (g x)</langsyntaxhighlight> =={{header|Ela}}==
It is already defined in standard prelude as (<<) operator.
 
<langsyntaxhighlight lang="ela">compose f g x = f (g x)</langsyntaxhighlight>
 
=={{header|Elena}}==
ELENA 4.x :
<langsyntaxhighlight lang="elena">import extensions;
extension op : Func1
Line 1,058:
console.printLine(fg(3))
}</langsyntaxhighlight>
{{out}}
<pre>
Line 1,066:
=={{header|Elixir}}==
{{trans|Erlang}}
<langsyntaxhighlight lang="elixir">defmodule RC do
def compose(f, g), do: fn(x) -> f.(g.(x)) end
Line 1,076:
 
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)</langsyntaxhighlight>
 
{{out}}
Line 1,089:
Lexical binding is supported as of Emacs 24.1, allowing the use of a closure for function composition.
 
<langsyntaxhighlight Lisplang="lisp">;; lexical-binding: t
(defun compose (f g)
(lambda (x)
Line 1,095:
 
(let ((func (compose '1+ '1+)))
(funcall func 5)) ;=> 7</langsyntaxhighlight>
 
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.
 
<langsyntaxhighlight Lisplang="lisp">(defun compose (f g)
`(lambda (x) (,f (,g x))))
 
(let ((func (compose '1+ '1+)))
(funcall func 5)) ;=> 7</langsyntaxhighlight>
 
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>.
 
<langsyntaxhighlight Lisplang="lisp">(defmacro compose (f g)
`(lambda (x) (,f (,g x))))
 
(let ((func (compose 1+ 1+)))
(funcall func 5)) ;=> 7</langsyntaxhighlight>
 
=={{header|Erlang}}==
<langsyntaxhighlight lang="erlang">-module(fn).
-export([compose/2, multicompose/1]).
 
Line 1,120:
 
multicompose(Fs) ->
lists:foldl(fun compose/2, fun(X) -> X end, Fs).</langsyntaxhighlight>
 
Using them:
<langsyntaxhighlight lang="erlang">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</langsyntaxhighlight>
 
{{omit from|Euphoria}}
Line 1,138:
 
We can implement composition manually like this (F# Interactive session):
<langsyntaxhighlight lang="fsharp">> let compose f g x = f (g x);;
 
val compose : ('a -> 'b) -> ('c -> 'a) -> 'c -> 'b</langsyntaxhighlight>
Usage:
<langsyntaxhighlight lang="fsharp">> let sin_asin = compose sin asin;;
 
val sin_asin : (float -> float)
 
> sin_asin 0.5;;
val it : float = 0.5</langsyntaxhighlight>
 
=={{header|Factor}}==
Line 1,154:
To compose quotations (anonymous functions), <code>compose</code> may be used:
 
<langsyntaxhighlight lang="factor">( scratchpad ) [ 2 * ] [ 1 + ] compose .
[ 2 * 1 + ]
( scratchpad ) 4 [ 2 * ] [ 1 + ] compose call .
9</langsyntaxhighlight>
 
=={{header|Fantom}}==
<langsyntaxhighlight lang="fantom">
class Compose
{
Line 1,176:
}
}
</syntaxhighlight>
</lang>
 
=={{header|Forth}}==
<langsyntaxhighlight lang="forth">: compose ( xt1 xt2 -- xt3 )
>r >r :noname
r> compile,
Line 1,187:
 
' 2* ' 1+ compose ( xt )
3 swap execute . \ 7</langsyntaxhighlight>
 
=={{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.
 
<langsyntaxhighlight lang="fortran">
module functions_module
implicit none
Line 1,272:
write(*,*) "run compose:", compose(0.5)
end program test_compose
</syntaxhighlight>
</lang>
 
=={{header|Fortress}}==
Line 1,281:
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.
 
<langsyntaxhighlight lang="fortress">
compose[\A, B, C\](f:A->B, g:B->C, i:Any): A->C = do
f(g(i))
Line 1,287:
 
composed(i:RR64): RR64 = compose(sin, cos, i)
</syntaxhighlight>
</lang>
 
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.
<langsyntaxhighlight lang="fortress">
alt_compose(f:Number->RR64, g:Number->RR64, i:RR64): ()->RR64 = do
f(g(i))
Line 1,298:
 
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.
 
<langsyntaxhighlight lang="fortress">
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.
Line 1,310:
=={{header|FreeBASIC}}==
Illustrating with functions that take and return integers.
<langsyntaxhighlight lang="freebasic">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</langsyntaxhighlight>
If you have functions named, say, foo and bar you would call compose with
<pre>compose( @foo, @bar, n )</pre> for some integer n.
 
=={{header|FunL}}==
<langsyntaxhighlight lang="funl">import math.{sin, asin}
 
def compose( f, g ) = x -> f( g(x) )
Line 1,325:
sin_asin = compose( sin, asin )
 
println( sin_asin(0.5) )</langsyntaxhighlight>
 
{{out}}
Line 1,342:
 
=={{header|GAP}}==
<langsyntaxhighlight lang="gap">Composition := function(f, g)
return x -> f(g(x));
end;
Line 1,348:
h := Composition(x -> x+1, x -> x*x);
h(5);
# 26</langsyntaxhighlight>
 
=={{header|Go}}==
<langsyntaxhighlight lang="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.
Line 1,361:
return f(g(x))
}
}</langsyntaxhighlight>
Example use:
<langsyntaxhighlight lang="go">package main
 
import "math"
Line 1,379:
sin_asin := compose(math.Sin, math.Asin)
fmt.Println(sin_asin(.5))
}</langsyntaxhighlight>
{{out}}
<pre>
Line 1,387:
=={{header|Groovy}}==
Test program:
<langsyntaxhighlight lang="groovy">final times2 = { it * 2 }
final plus1 = { it + 1 }
 
Line 1,394:
 
assert plus1_then_times2(3) == 8
assert times2_then_plus1(3) == 7</langsyntaxhighlight>
 
=={{header|Haskell}}==
This is already defined as the '''.''' (dot) operator in Haskell:
 
<langsyntaxhighlight lang="haskell">Prelude> let sin_asin = sin . asin
Prelude> sin_asin 0.5
0.49999999999999994</langsyntaxhighlight>
 
Ways to use directly:
<langsyntaxhighlight lang="haskell">(sin . asin) 0.5</langsyntaxhighlight>
<langsyntaxhighlight lang="haskell">sin . asin $ 0.5</langsyntaxhighlight>
 
 
Implementing compose function from scratch:
<langsyntaxhighlight lang="haskell">compose f g x = f (g x)</langsyntaxhighlight>
Example use:
<langsyntaxhighlight lang="haskell">Prelude> let compose f g x = f (g x)
Prelude> let sin_asin = compose sin asin
Prelude> sin_asin 0.5
0.5</langsyntaxhighlight>
 
 
Right to left composition of a list of functions could be defined as ''flip (foldr id)'':
 
<langsyntaxhighlight lang="haskell">composeList :: [a -> a] -> a -> a
composeList = flip (foldr id)
 
main :: IO ()
main = print $ composeList [(/ 2), succ, sqrt] 5</langsyntaxhighlight>
{{Out}}
<pre>1.618033988749895</pre>
 
=={{header|Hy}}==
<langsyntaxhighlight lang="clojure">(defn compose [f g]
(fn [x]
(f (g x))))</langsyntaxhighlight>
 
=={{header|Icon}} and {{header|Unicon}}==
Line 1,441:
 
The solution below can be adapted to work in Icon by reverting to the old syntax for invoking co-expressions.
<langsyntaxhighlight Iconlang="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</langsyntaxhighlight>
See [[Icon%2BUnicon/Intro#Minor_Differences|Icon and Unicon Introduction:Minor Differences]] for more information
 
<langsyntaxhighlight Uniconlang="unicon">procedure main(arglist)
h := compose(sqrt,abs)
k := compose(integer,"sqrt",ord)
Line 1,475:
return (@cf, cf) # 'prime' the co-expr before returning it
 
end</langsyntaxhighlight>
 
{{out}}
Line 1,492:
 
'''Solution''':
<langsyntaxhighlight lang="j">compose =: @</langsyntaxhighlight>
 
'''Example''':
<syntaxhighlight lang ="j">f compose g</langsyntaxhighlight>
 
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,501:
Tentative new example:
 
<langsyntaxhighlight lang="j">f=: >.@(1&o.)@%:
g=: 1&+@|@(2&o.)
h=: f@g</langsyntaxhighlight>
 
Example use:
<langsyntaxhighlight lang="j"> (f, g, h) 1p1
1 2 1</langsyntaxhighlight>
 
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|Java}}==
<langsyntaxhighlight lang="java">public class Compose {
 
// Java doesn't have function type so we define an interface
Line 1,544:
System.out.println(sin_asin.call(0.5)); // prints "0.5"
}
}</langsyntaxhighlight>
 
===Java 8===
Line 1,550:
Java 8's <code>Function</code> interface already has a <code>.compose()</code> default method:
{{works with|Java|8+}}
<langsyntaxhighlight lang="java">import java.util.function.Function;
 
public class Compose {
Line 1,558:
System.out.println(sin_asin.apply(0.5)); // prints "0.5"
}
}</langsyntaxhighlight>
 
Implementing it yourself as a static method:
{{works with|Java|8+}}
<langsyntaxhighlight lang="java">import java.util.function.Function;
 
public class Compose {
Line 1,574:
System.out.println(sin_asin.apply(0.5)); // prints "0.5"
}
}</langsyntaxhighlight>
 
=={{header|JavaScript}}==
===ES5===
====Simple composition of two functions====
<langsyntaxhighlight lang="javascript">function compose(f, g) {
return function(x) {
return f(g(x));
};
}</langsyntaxhighlight>
Example:
<langsyntaxhighlight lang="javascript">var id = compose(Math.sin, Math.asin);
console.log(id(0.5)); // 0.5</langsyntaxhighlight>
 
 
Line 1,596:
# 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.
 
<langsyntaxhighlight JavaScriptlang="javascript">(function () {
'use strict';
 
Line 1,645:
});
})();
</syntaxhighlight>
</lang>
 
{{Out}}
Line 1,655:
 
====Simple composition of two functions====
<langsyntaxhighlight lang="javascript">function compose(f, g) {
return x => f(g(x));
}</langsyntaxhighlight>
or
<langsyntaxhighlight lang="javascript">var compose = (f, g) => x => f(g(x));</langsyntaxhighlight>
Example:
<langsyntaxhighlight lang="javascript">var id = compose(Math.sin, Math.asin);
console.log(id(0.5)); // 0.5</langsyntaxhighlight>
 
 
====Multiple composition====
<langsyntaxhighlight JavaScriptlang="javascript">(() => {
"use strict";
 
Line 1,689:
 
// --> 1.618033988749895
})();</langsyntaxhighlight>
{{Out}}
<pre>1.618033988749895</pre>
Line 1,695:
=={{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.
<syntaxhighlight lang=Joy"joy">g f</syntaxhighlight>
And yes, there should be a space between the two names.
 
Line 1,702:
 
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
def compose(f; g): g | f;
</syntaxhighlight>
</lang>
Example: 0.5 | compose(asin; sin)
 
Line 1,713:
{{works with|Julia|0.6}}
'''Built-in''':
<langsyntaxhighlight lang="julia">@show (asin ∘ sin)(0.5)</langsyntaxhighlight>
 
'''Alternative''':
<langsyntaxhighlight lang="julia">compose(f::Function, g::Function) = (x) -> g(f(x))
@show compose(sin, asin)(0.5)</langsyntaxhighlight>
 
=={{header|K}}==
The K syntax for APL tacit (point free) function composition is the dyadic form of apostrophe ('), here is a cover function
<syntaxhighlight lang ="k">compose:{'[x;y]}</langsyntaxhighlight>
 
An equivalent explicit definition would be
<langsyntaxhighlight lang="k">compose:{x[y[z]]}</langsyntaxhighlight>
 
'''Example:'''
<langsyntaxhighlight lang="k"> sin_asin:compose[sin;asin] // or compose . (sin;asin)
sin_asin 0.5
0.5</langsyntaxhighlight>
 
=={{header|Klingphix}}==
<langsyntaxhighlight Klingphixlang="klingphix">include ..\Utilitys.tlhy
 
:*2 2 * ;
Line 1,740:
@++ @*2 3 composite ? { result: 7 }
 
"End " input</langsyntaxhighlight>
 
=={{header|Kotlin}}==
<langsyntaxhighlight lang="scala">// version 1.0.6
 
fun f(x: Int): Int = x * x
Line 1,754:
val x = 10
println(compose(::f, ::g)(x))
}</langsyntaxhighlight>
 
{{out}}
Line 1,762:
 
=={{header|Lambdatalk}}==
<syntaxhighlight lang="scheme">
<lang Scheme>
{def compose
{lambda {:f :g :x}
Line 1,779:
{{f} 3}
-> 80
</syntaxhighlight>
</lang>
 
=={{header|LFE}}==
<langsyntaxhighlight lang="lisp">
(defun compose (f g)
(lambda (x)
Line 1,799:
(io:format '"Expected answer: ~p~n" (list expected))
(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:
<langsyntaxhighlight lang="lisp">
> (funcall (compose #'math:sin/1 #'math:asin/1)
0.5)
Line 1,816:
ok
>
</syntaxhighlight>
</lang>
 
=={{header|Lingo}}==
Line 1,834:
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":
 
<langsyntaxhighlight lang="lingo">-- in some movie script
----------------------------------------
-- Composes 2 call-functions, returns a new call-function
Line 1,843:
on compose (f, g)
return script("Composer").new(f, g)
end</langsyntaxhighlight>
 
<langsyntaxhighlight lang="lingo">-- parent script "Composer"
 
property _f
Line 1,878:
return _movie.call(me._f, _movie, value(cmd))
end if
end</langsyntaxhighlight>
 
Usage:
<langsyntaxhighlight lang="lingo">-- compose new function based on built-in function 'sin' and user-defined function 'asin'
f1 = compose(#asin, #sin)
put call(f1, _movie, 0.5)
Line 1,896:
f3 = compose(f2, f1)
put call(f3, _movie, 0.5)
-- 3.0000</langsyntaxhighlight>
 
User-defined custom functions used in demo code above:
<langsyntaxhighlight lang="lingo">-- in some movie script
on asin (x)
res = atan(sqrt(x*x/(1-x*x)))
Line 1,912:
on triple (x)
return x*3
end</langsyntaxhighlight>
 
=={{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.
<langsyntaxhighlight LOLCODElang="lolcode">HAI 1.3
 
I HAS A fx, I HAS A gx
Line 1,942:
VISIBLE I IZ sqrincin YR 10 MKAY BTW, prints 121
 
KTHXBYE</langsyntaxhighlight>
 
=={{header|Lua}}==
<langsyntaxhighlight lang="lua">function compose(f, g) return function(...) return f(g(...)) end end</langsyntaxhighlight>
 
=={{header|M2000 Interpreter}}==
===Using Lambda functions===
<syntaxhighlight lang="m2000 interpreter">
<lang M2000 Interpreter>
Module CheckIt {
Compose = lambda (f, g)->{
Line 1,960:
}
CheckIt
</syntaxhighlight>
</lang>
===Using EVAL and EVAL$===
<syntaxhighlight lang="m2000 interpreter">
<lang M2000 Interpreter>
class Compose {
private:
Line 2,000:
UcaseLcase$=ComposeStr$("Ucase$", "Lcase$")
Print UcaseLcase$("GOOD")
</syntaxhighlight>
</lang>
 
=={{header|Mathcad}}==
Line 2,026:
=={{header|Mathematica}} / {{header|Wolfram Language}}==
Built-in function that takes any amount of function-arguments:
<langsyntaxhighlight Mathematicalang="mathematica">Composition[f, g][x]
Composition[f, g, h, i][x]</langsyntaxhighlight>
gives back:
<langsyntaxhighlight Mathematicalang="mathematica">f[g[x]]
f[g[h[i[x]]]]</langsyntaxhighlight>
Custom function:
<langsyntaxhighlight Mathematicalang="mathematica">compose[f_, g_][x_] := f[g[x]]
compose[Sin, Cos][r]</langsyntaxhighlight>
gives back:
<syntaxhighlight lang Mathematica="mathematica">Sin[Cos[r]]</langsyntaxhighlight>
Composition can be done in more than 1 way:
<langsyntaxhighlight Mathematicalang="mathematica">Composition[f,g,h][x]
f@g@h@x
x//h//g//f</langsyntaxhighlight>
all give back:
<syntaxhighlight lang Mathematica="mathematica">f[g[h[x]]]</langsyntaxhighlight>
The built-in function has a couple of automatic simplifications:
<langsyntaxhighlight Mathematicalang="mathematica">Composition[f, Identity, g]
Composition[f, InverseFunction[f], h][x]</langsyntaxhighlight>
becomes:
<langsyntaxhighlight Mathematicalang="mathematica">f[g[x]]
h[x]</langsyntaxhighlight>
 
=={{header|Maxima}}==
<langsyntaxhighlight lang="maxima">/* built-in */
load(to_poly_solver);
 
Line 2,057:
 
/* An implementation, to show a use of buildq */
compose(f, g) := buildq([f, g], lambda([x], f(g(x))));</langsyntaxhighlight>
 
=={{header|min}}==
{{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:
<langsyntaxhighlight lang="min">(1 +) (2 *) concat print</langsyntaxhighlight>
{{out}}
<pre>
Line 2,069:
 
=={{header|MiniScript}}==
<langsyntaxhighlight MiniScriptlang="miniscript">funcA = function(x)
return x * 10
end function
Line 2,084:
 
f = compose(@funcA, @funcB)
print f(3) // should be equal to (3+5)*10</langsyntaxhighlight>
{{out}}
<pre>80</pre>
 
=={{header|Nemerle}}==
<langsyntaxhighlight Nemerlelang="nemerle">using System;
using System.Console;
using System.Math;
Line 2,105:
WriteLine(SinAsin(0.5));
}
}</langsyntaxhighlight>
 
=={{header|Never}}==
<syntaxhighlight lang="never">
<lang Never>
func compose(f(i : int) -> int, g(i : int) -> int) -> (int) -> int
{
Line 2,126:
0
}
</syntaxhighlight>
</lang>
 
=={{header|NewLISP}}==
 
<langsyntaxhighlight NewLISPlang="newlisp">> (define (compose f g) (expand (lambda (x) (f (g x))) 'f 'g))
(lambda (f g) (expand (lambda (x) (f (g x))) 'f 'g))
> ((compose sin asin) 0.5)
0.5
</syntaxhighlight>
</lang>
 
=={{header|Nim}}==
<langsyntaxhighlight lang="nim">import sugar
 
proc compose[A,B,C](f: A -> B, g: B -> C): A -> C = (x: A) => f(g(x))
Line 2,145:
 
var plusminustwo = compose(plustwo, minustwo)
echo plusminustwo(10)</langsyntaxhighlight>
 
=={{header|Objeck}}==
<langsyntaxhighlight lang="objeck">
bundle Default {
class Test {
Line 2,178:
}
}
</syntaxhighlight>
</lang>
prints: 42
 
Line 2,185:
 
 
<langsyntaxhighlight lang="objecticon"># -*- ObjectIcon -*-
#
# The Rosetta Code function composition task, in Object Icon.
Line 2,250:
 
return cf
end</langsyntaxhighlight>
 
{{out}}
Line 2,262:
We restrict ourselves to functions that take and return one object.
 
<langsyntaxhighlight lang="objc">#include <Foundation/Foundation.h>
 
typedef id (^Function)(id);
Line 2,303:
}
return 0;
}</langsyntaxhighlight>
 
=={{header|OCaml}}==
<langsyntaxhighlight lang="ocaml">let compose f g x = f (g x)</langsyntaxhighlight>
Example use:
<langsyntaxhighlight lang="ocaml"># 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</langsyntaxhighlight>
 
=={{header|Octave}}==
 
<langsyntaxhighlight lang="octave">function r = compose(f, g)
r = @(x) f(g(x));
endfunction
 
r = compose(@exp, @sin);
r(pi/3)</langsyntaxhighlight>
 
=={{header|Oforth}}==
 
Oforth uses RPN notation. Function composition of f and g is just calling :
<syntaxhighlight lang Oforth="oforth">g f</langsyntaxhighlight>
If a block is needed, a compose function can be implemented :
<langsyntaxhighlight Oforthlang="oforth">: compose(f, g) #[ g perform f perform ] ;</langsyntaxhighlight>
Usage :
<langsyntaxhighlight Oforthlang="oforth">1.2 compose(#asin, #sin) perform
[ 1, 2, 3, 4, 5 ] compose(#[ map(#sqrt) ], #[ filter(#isEven) ]) perform</langsyntaxhighlight>
The last line returns : [1.4142135623731, 2]
 
=={{header|Ol}}==
<langsyntaxhighlight lang="scheme">
(define (compose f g)
(lambda (x) (f (g x))))
Line 2,343:
 
(define ((compose f g) x) (f (g x)))
</syntaxhighlight>
</lang>
 
=={{header|Order}}==
Order supplies the built-in function <code>8compose</code> for this purpose. However, a manual implementation might be:
<langsyntaxhighlight lang="c">#include <order/interpreter.h>
 
#define ORDER_PP_DEF_8comp ORDER_PP_FN( \
8fn(8F, 8G, 8fn(8X, 8ap(8F, 8ap(8G, 8X)))) )</langsyntaxhighlight>
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}}==
<langsyntaxhighlight lang="oz">declare
fun {Compose F G}
fun {$ X}
Line 2,363:
SinAsin = {Compose Float.sin Float.asin}
in
{Show {SinAsin 0.5}}</langsyntaxhighlight>
 
=={{header|PARI/GP}}==
{{works with|PARI/GP|2.4.2 and above}}
<langsyntaxhighlight lang="parigp">compose(f, g)={
x -> f(g(x))
};
 
compose(x->sin(x),x->cos(x)(1)</langsyntaxhighlight>
 
Usage note: In Pari/GP 2.4.3, this can be expressed more succinctly:
<syntaxhighlight lang ="parigp">compose(sin,cos)(1)</langsyntaxhighlight>
 
=={{header|Pascal}}==
Line 2,380:
 
=={{header|Perl}}==
<langsyntaxhighlight lang="perl">sub compose {
my ($f, $g) = @_;
 
Line 2,389:
 
use Math::Trig;
print compose(sub {sin $_[0]}, \&asin)->(0.5), "\n";</langsyntaxhighlight>
 
=={{header|Phix}}==
There is not really any direct support for this sort of thing in Phix, but it is all pretty trivial to manage explicitly.<br>
In the following, as it stands, 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.
<!--<langsyntaxhighlight Phixlang="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>
Line 2,420:
<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
<!--</langsyntaxhighlight>-->
 
=={{header|Phixmonti}}==
<langsyntaxhighlight Phixmontilang="phixmonti">def *2 2 * enddef
def ++ 1 + enddef
def composite swap exec swap exec enddef
 
getid ++ getid *2 3 composite print /# result: 7 #/</langsyntaxhighlight>
 
=={{header|PHP}}==
{{works with|PHP|5.3+}}
<langsyntaxhighlight lang="php"><?php
function compose($f, $g) {
return function($x) use ($f, $g) { return $f($g($x)); };
Line 2,438:
$trim_strlen = compose('strlen', 'trim');
echo $result = $trim_strlen(' Test '), "\n"; // prints 4
?></langsyntaxhighlight>
 
{{works with|PHP|pre-5.3 and 5.3+}}
works with regular functions as well as functions created by <tt>create_function()</tt>
<langsyntaxhighlight lang="php"><?php
function compose($f, $g) {
return create_function('$x', 'return '.var_export($f,true).'('.var_export($g,true).'($x));');
Line 2,449:
$trim_strlen = compose('strlen', 'trim');
echo $result = $trim_strlen(' Test '), "\n"; // prints 4
?></langsyntaxhighlight>
 
=={{header|PicoLisp}}==
<langsyntaxhighlight PicoLisplang="picolisp">(de compose (F G)
(curry (F G) (X)
(F (G X)) ) )</langsyntaxhighlight>
<langsyntaxhighlight PicoLisplang="picolisp">(def 'a (compose inc dec))
(def 'b (compose 'inc 'dec))
(def 'c (compose '((A) (inc A)) '((B) (dec B))))</langsyntaxhighlight>
<langsyntaxhighlight PicoLisplang="picolisp">: (a 7)
-> 7
 
Line 2,465:
 
: (c 7)
-> 7</langsyntaxhighlight>
 
=={{header|PostScript}}==
<syntaxhighlight lang="postscript">
<lang PostScript>
/compose { % f g -> { g f }
[ 3 1 roll exch
Line 2,481:
/plus1 { 1 add } def
/sqPlus1 /square load /plus1 load compose def
</syntaxhighlight>
</lang>
 
=={{header|PowerShell}}==
You can simply call g inside f like this:
<syntaxhighlight lang="powershell">
<lang PowerShell>
function g ($x) {
$x + $x
Line 2,493:
}
f (g 1)
</syntaxhighlight>
</lang>
 
Or g and f can become paramaters of a new function fg
 
<syntaxhighlight lang="powershell">
<lang PowerShell>
function fg (${function:f}, ${function:g}, $x) {
f (g $x)
}
fg f g 1
</syntaxhighlight>
</lang>
 
In both cases the answer is:
Line 2,509:
=={{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
<langsyntaxhighlight Prologlang="prolog">:- use_module(lambda).
 
compose(F,G, FG) :-
FG = \X^Z^(call(G,X,Y), call(F,Y,Z)).
</syntaxhighlight>
</lang>
{{out}}
<pre> ?- compose(sin, asin, F), call(F, 0.5, Y).
Line 2,521:
 
=={{header|PureBasic}}==
<langsyntaxhighlight PureBasiclang="purebasic">;Declare how our function looks like
Prototype.i Func(Arg.i)
 
Line 2,543:
Title$="With x="+Str(x)
Body$="Compose(f(),g(), x) ="+Str(Compose(@f(),@g(),X))
MessageRequester(Title$,Body$)</langsyntaxhighlight>
 
=={{header|Purity}}==
<syntaxhighlight lang="purity">
<lang Purity>
data compose = f => g => $f . $g
</syntaxhighlight>
</lang>
 
=={{header|Python}}==
===Simple composition of two functions===
<langsyntaxhighlight lang="python">compose = lambda f, g: lambda x: f( g(x) )</langsyntaxhighlight>
Example use:
<langsyntaxhighlight lang="python">>>> 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
>>></langsyntaxhighlight>
 
 
Or, expanding slightly:
{{Works with|Python|3}}
<langsyntaxhighlight lang="python">from math import (acos, cos, asin, sin)
 
 
Line 2,599:
 
if __name__ == '__main__':
main()</langsyntaxhighlight>
{{Out}}
<pre>[0.49999999999999994, 0.5000000000000001, 0.5000000000000001]</pre>
Line 2,607:
 
{{Works with|Python|3}}
<langsyntaxhighlight lang="python">from functools import reduce
from math import sqrt
 
Line 2,646:
 
if __name__ == '__main__':
main()</langsyntaxhighlight>
{{Out}}
<pre>1.618033988749895</pre>
Line 2,653:
Here need composition of several functions is reduced with classes.
{{Works with|Python|3}}
<langsyntaxhighlight lang="python">
# Contents of `pip install compositions'
 
Line 2,676:
g = Compose(lambda x: x)
 
print((f * g)(2))</langsyntaxhighlight>
 
=={{header|Qi}}==
Qi supports partial applications, but only when calling a function with one argument.
<syntaxhighlight lang="qi">
<lang qi>
(define compose
F G -> (/. X
Line 2,686:
 
((compose (+ 1) (+ 2)) 3) \ (Outputs 6) \
</syntaxhighlight>
</lang>
 
Alternatively, it can be done like this:
 
<syntaxhighlight lang="qi">
<lang qi>
(define compose F G X -> (F (G X)))
 
(((compose (+ 1)) (+ 2)) 3) \ (Outputs 6) \
</syntaxhighlight>
</lang>
 
=={{header|Quackery}}==
 
<langsyntaxhighlight Quackerylang="quackery"> [ nested swap
nested swap join ] is compose ( g f --> [ )
 
Line 2,715:
 
19 ' double ' [ 4 + ] compose do echo
</syntaxhighlight>
</lang>
 
{{out}}
Line 2,722:
 
=={{header|R}}==
<langsyntaxhighlight Rlang="r">compose <- function(f,g) function(x) { f(g(x)) }
r <- compose(sin, cos)
print(r(.5))</langsyntaxhighlight>
 
=={{header|Racket}}==
<langsyntaxhighlight lang="racket">
(define (compose f g)
(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.)
Line 2,738:
{{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:
<syntaxhighlight lang="raku" perl6line>sub triple($n) { 3 * $n }
my &f = &triple ∘ &prefix:<-> ∘ { $^n + 2 };
say &f(5); # prints "-21".</langsyntaxhighlight>
 
=={{header|REBOL}}==
<langsyntaxhighlight REBOLlang="rebol">REBOL [
Title: "Functional Composition"
URL: http://rosettacode.org/wiki/Functional_Composition
Line 2,756:
] [
func [x] compose [(:f) (:g) x]
]</langsyntaxhighlight>
 
Functions "foo" and "bar" are used to prove that composition
actually took place by attaching their signatures to the result.
 
<langsyntaxhighlight REBOLlang="rebol">foo: func [x] [reform ["foo:" x]]
bar: func [x] [reform ["bar:" x]]
 
Line 2,768:
 
sin-asin: compose-functions :sine :arcsine
print [crlf "Composition of sine and arcsine:" sin-asin 0.5]</langsyntaxhighlight>
 
{{out}}
Line 2,776:
 
=={{header|REXX}}==
<langsyntaxhighlight 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.*/</langsyntaxhighlight>
 
=={{header|Ring}}==
<langsyntaxhighlight lang="ring">
# Project : Function composition
 
Line 2,795:
res = x * y
return res
</syntaxhighlight>
</lang>
Output:
<pre>
Line 2,803:
=={{header|Ruby}}==
This <tt>compose</tt> method gets passed two Method objects or Proc objects
<langsyntaxhighlight lang="ruby">def compose(f,g)
lambda {|x| f[g[x]]}
end
Line 2,810:
 
# verify
p Math.sin(Math.cos(0.5)) # => 0.769196354841008</langsyntaxhighlight>
 
=={{header|Rust}}==
Line 2,817:
===Stable===
Function is allocated on the heap and is called via dynamic dispatch
<langsyntaxhighlight 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,
G: Fn(T) -> U + 'a,
{
Box::new(move |x| f(g(x)))
}</langsyntaxhighlight>
 
===Nightly===
Function is returned on the stack and is called via static dispatch (monomorphized)
<langsyntaxhighlight lang="rust">#![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,
Line 2,832:
{
move |x| f(g(x))
}</langsyntaxhighlight>
 
=={{header|Scala}}==
<langsyntaxhighlight lang="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)</langsyntaxhighlight>
 
We can achieve a more natural style by creating a container class for composable functions, which provides
the compose method 'o':
 
<langsyntaxhighlight lang="scala">class Composable[A](f: A => A) {
def o (g: A => A) = compose(f, g)
}
Line 2,849:
implicit def toComposable[A](f: A => A) = new Composable(f)
 
val add3 = (add1 _) o add2</langsyntaxhighlight>
 
<pre>
Line 2,857:
 
=={{header|Scheme}}==
<langsyntaxhighlight lang="scheme">(define (compose f g) (lambda (x) (f (g x))))
 
;; or:
Line 2,872:
((_ f g h ...) #'(lambda (y) (f ((compose g h ...) y)))))))
 
</syntaxhighlight>
</lang>
Example:
<langsyntaxhighlight lang="scheme">
(display ((compose sin asin) 0.5))
(newline)</langsyntaxhighlight>
{{out}}
<syntaxhighlight lang="text">0.5</langsyntaxhighlight>
 
=={{header|Sidef}}==
<langsyntaxhighlight lang="ruby">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</langsyntaxhighlight>
 
=={{header|Slate}}==
Function (method) composition is standard:
<langsyntaxhighlight lang="slate">[| :x | x + 1] ** [| :x | x squared] applyTo: {3}</langsyntaxhighlight>
 
=={{header|Smalltalk}}==
<langsyntaxhighlight lang="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.</langsyntaxhighlight>
 
=={{header|Standard ML}}==
This is already defined as the '''o''' operator in Standard ML.
<langsyntaxhighlight lang="sml">fun compose (f, g) x = f (g x)</langsyntaxhighlight>
Example use:
<langsyntaxhighlight lang="sml">- 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</langsyntaxhighlight>
 
=={{header|SuperCollider}}==
has a function composition operator (the message `<>`):
<syntaxhighlight lang="supercollider">
<lang SuperCollider>
f = { |x| x + 1 };
g = { |x| x * 2 };
h = g <> f;
h.(8); // returns 18
</syntaxhighlight>
</lang>
 
=={{header|Swift}}==
<langsyntaxhighlight lang="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))</langsyntaxhighlight>
{{out}}
<pre>
Line 2,935:
{{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.
<langsyntaxhighlight lang="tcl">package require Tcl 8.5
namespace path {::tcl::mathfunc}
 
Line 2,944:
set sin_asin [compose sin asin]
{*}$sin_asin 0.5 ;# ==> 0.5
{*}[compose abs int] -3.14 ;# ==> 3</langsyntaxhighlight>
 
=={{header|TypeScript}}==
<syntaxhighlight lang="typescript">
<lang TypeScript>
function compose<T, U, V> (fn1: (input: T) => U, fn2: (input: U) => V){
return function(value: T) {
Line 2,962:
console.log(evenSize("ABCD")) // true
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)</langsyntaxhighlight>
 
=={{header|UNIX Shell}}==
Line 2,978:
 
{{works with|Bourne Shell}}
<langsyntaxhighlight lang="bash">compose() {
eval "$1() { $3 | $2; }"
}
Line 2,986:
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.</langsyntaxhighlight>
 
{{works with|Bourne Again SHell}}
This solution uses no external tools, just Bash itself.
 
<langsyntaxhighlight lang="bash">
#compose a new function consisting of the application of 2 unary functions
 
Line 3,128:
 
compose strdownvowel strupcase "Cozy lummox gives smart squid who asks for job pen."
# --> CoZY LuMMoX GiVeS SMaRT SQuiD WHo aSKS FoR JoB PeN.</langsyntaxhighlight>
 
 
Line 3,134:
With shell pipelines:
 
<langsyntaxhighlight lang="es">fn compose f g {
result @ {$g | $f}
}
Line 3,142:
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.</langsyntaxhighlight>
 
With function arguments:
 
<langsyntaxhighlight lang="es">fn compose f g {
result @ x {result <={$f <={$g $x}}}
}
Line 3,154:
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.</langsyntaxhighlight>
 
=={{header|Unlambda}}==
Line 3,165:
for functions f and g, hence hardly worth defining. However, it could
be defined without using the operator like this.
<langsyntaxhighlight Ursalalang="ursala">compose("f","g") "x" = "f" "g" "x"</langsyntaxhighlight>
test program:
<langsyntaxhighlight Ursalalang="ursala">#import nat
#cast %n
 
test = compose(successor,double) 3</langsyntaxhighlight>
{{out}}
<pre>7</pre>
Line 3,181:
 
'''Implementation'''
<syntaxhighlight lang="vb">
<lang vb>
option explicit
class closure
Line 3,200:
end class
</syntaxhighlight>
</lang>
 
'''Invocation'''
<syntaxhighlight lang="vb">
<lang vb>
dim c
set c = new closure
Line 3,230:
wscript.echo c.formula
wscript.echo c(12.3)
</syntaxhighlight>
</lang>
 
{{out}}
Line 3,248:
The simplest way is with a lambda:
 
<langsyntaxhighlight WDTElang="wdte">let compose f g => (@ c x => g x -> f);</langsyntaxhighlight>
 
Alternatively, you can take advantage of partial function calls:
 
<langsyntaxhighlight WDTElang="wdte">let compose f g x => g x -> f;</langsyntaxhighlight>
 
Both can be used as follows:
 
<langsyntaxhighlight WDTElang="wdte">(compose (io.writeln io.stdout) !) true;</langsyntaxhighlight>
 
Output:
 
<syntaxhighlight lang WDTE="wdte">false</langsyntaxhighlight>
 
=={{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.
<langsyntaxhighlight lang="wortel">! @[f g] x ; f(g(x))</langsyntaxhighlight>
<langsyntaxhighlight lang="wortel">! ^(f g) x ; f(g(x))</langsyntaxhighlight>
Defining the <code>compose</code> function
<langsyntaxhighlight lang="wortel">@var compose &[f g] &x !f!g x</langsyntaxhighlight>
 
=={{header|Wren}}==
<langsyntaxhighlight lang="ecmascript">var compose = Fn.new { |f, g| Fn.new { |x| f.call(g.call(x)) } }
 
var double = Fn.new { |x| 2 * x }
Line 3,276:
var addOne = Fn.new { |x| x + 1 }
 
System.print(compose.call(double, addOne).call(3))</langsyntaxhighlight>
 
{{out}}
Line 3,284:
 
=={{header|zkl}}==
<langsyntaxhighlight lang="zkl">Utils.Helpers.fcomp('+(1),'*(2))(5) //-->11</langsyntaxhighlight>
Which is implemented with a closure (.fp1), which fixes the second paramter
<langsyntaxhighlight lang="zkl">fcn fcomp(f,g,h,etc){
{ fcn(x,hgf){ T(x).pump(Void,hgf.xplode()) }.fp1(vm.arglist.reverse()); }</langsyntaxhighlight>
 
=={{header|ZX Spectrum Basic}}==
DEF FN commands can be nested, making this appear trivial:
<langsyntaxhighlight lang="zxbasic">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)</langsyntaxhighlight>
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:
<langsyntaxhighlight lang="zxbasic">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)</langsyntaxhighlight>
{{out}}
<pre>2
10,327

edits