Function composition: Difference between revisions
m
→{{header|Amazing Hopper}}
(36 intermediate revisions by 20 users not shown) | |||
Line 20:
{{trans|Python}}
<
V sin_asin = compose(x -> sin(x), x -> asin(x))
print(sin_asin(0.5))</
{{out}}
Line 31:
=={{header|ActionScript}}==
ActionScript supports closures, making function composition very straightforward.
<
return function(x:Object) {return f(g(x));};
}
function test() {
trace(compose(Math.atan, Math.tan)(0.5));
}</
=={{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):
<
type Argument is private;
package Functions is
Line 52:
private
type Func is array (Positive range <>) of Primitive_Operation;
end Functions;</
Here is an implementation;
<
function "*" (Left : Func; Right : Argument) return Argument is
Result : Argument := Right;
Line 78:
return (Left, Right);
end "*";
end Functions;</
The following is an example of use:
<
with Ada.Text_IO; use Ada.Text_IO;
with Functions;
Line 91:
begin
Put_Line (Float'Image (Sin_Arcsin * 0.5));
end Test_Compose;</
{{out}}
<pre>
Line 98:
=={{header|Agda}}==
<
→ (B → C)
→ (A → B)
→ A → C
compose f g x = f (g x)</
=={{header|Aikido}}==
<
import math
Line 115:
println (func(0.5)) // 0.5
</syntaxhighlight>
=={{header|Aime}}==
<
{
($0)(($1)($2));
Line 143:
0;
}</
{{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.
<
# 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))</
{{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}}
<
# 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))</
=={{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}}==
<
compose1: {f: x; g: y; {f[g[x]]}}
/Extra: apply to multiple arguments
compose: {f: x; g: y; {f[g apply args]}}</
=={{header|AppleScript}}==
<
-- a script object with a call(x) handler.
on compose(f, g)
Line 214 ⟶ 267:
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.
Line 220 ⟶ 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).
<
-- compose :: [(a -> a)] -> (a -> a)
Line 285 ⟶ 338:
end script
end if
end mReturn</
{{Out}}
<pre>1.61803398875</pre>
=={{header|Applesoft BASIC}}==
<
20 DEF FN A(P) = ATN(P/SQR(-P*P+1))
30 G$ = "FN A"
Line 307 ⟶ 360:
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</
=={{header|Argile}}==
Only works for functions taking real and returning real (double precision, 64 bits)
{{works with|Argile|1.0.0}}
<
let my_asin = new Function (.:<any,real x>:. -> real {asin x})
Line 354 ⟶ 407:
f.func = func
f.data = data
f</
=={{header|Arturo}}==
<
return function [x].import:[f,g][
call f @[call g @[x]]
Line 365 ⟶ 418:
splitupper: compose 'split 'upper
print call 'splitupper ["done"]</
{{out}}
<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}}==
contributed by Laszlo on the ahk [http://www.autohotkey.com/forum/post-276379.html#276379 forum]
<
compose(f,g,x) { ; function composition
Return %f%(%g%(x))
}</
=={{header|BBC BASIC}}==
{{works with|BBC BASIC for Windows}}
<
DEF FNsqr(a) = SQR(a)
DEF FNabs(a) = ABS(a)
Line 397 ⟶ 585:
\ CHR$&A4 + "(&" + STR$~(p%+4) + ")(x))"
DIM p% LEN(f$) + 4 : $(p%+4) = f$ : !p% = p%+4
= p%</
{{out}}
<pre>
Line 404 ⟶ 592:
=={{header|Bori}}==
<
double asin (double v) { return Math.asin(v); }
Var compose (Func f, Func g, double d) { return f(g(d)); }
Line 412 ⟶ 600:
double d = compose(sin, asin, 0.5);
label1.setText(d.toString(9));
}</
{{out}} on Android phone:
<syntaxhighlight lang
=={{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}}==
Line 420 ⟶ 614:
As a 2-modifier:
<syntaxhighlight lang
Or:
<syntaxhighlight lang
As a dyadic function:
<syntaxhighlight lang
This is how you can use it:
Line 443 ⟶ 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>.
<
= f g
. !arg:(?f.?g)&'(.($f)$(($g)$!arg))
Line 462 ⟶ 656:
& FahrenheitToCelsiusExample$0
& FahrenheitToCelsiusExample$100
)</
<pre>0 °F in °C = -1,78*10E1
Line 468 ⟶ 662:
=={{header|Brat}}==
<
#Test
Line 474 ⟶ 668:
double = { x | x * 2 }
b = compose(->double ->add1)
p b 1 #should print 4</
=={{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}}==
Only works for functions taking a double and returning a double:
<
/* generic interface for functors from double to double */
Line 541 ⟶ 761:
return 0;
}</
=={{header|C sharp|C#}}==
<
class Program
{
Line 561 ⟶ 781:
}
}
}</
=={{header|C++}}==
<
#include <cmath>
#include <iostream>
Line 598 ⟶ 818:
return 0;
}</
{{works with|C++11}} composing <code>std::function</code>
<
#include <functional>
#include <cmath>
Line 614 ⟶ 834:
std::function<double(double)> g = asin;
std::cout << compose(f, g)(0.5) << std::endl;
}</syntaxhighlight>
{{Works with|C++14}}
This much simpler version uses <code>decltype(auto)</code>.
<
#include <cmath>
Line 630 ⟶ 848:
int main() {
std::cout << compose(sin, asin)(0.5) << "\n";
}</syntaxhighlight>
{{works with|GCC}}
<
#include <cmath>
#include <ext/functional>
Line 641 ⟶ 857:
int main() {
std::cout << __gnu_cxx::compose1(std::ptr_fun(::sin), std::ptr_fun(::asin))(0.5) << std::endl;
}</syntaxhighlight>
'''Works with:''' C++20
<syntaxhighlight lang="cpp">#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";
}
</syntaxhighlight>
{{out}}
<pre>
0.5</pre>
=={{header|Clojure}}==
Line 649 ⟶ 879:
A manual implementation could look like this:
<
(fn [x]
(f (g x))))
Line 655 ⟶ 885:
; Example
(def inc2 (compose inc inc))
(println (inc2 5)) ; prints 7</
=={{header|CoffeeScript}}==
<
compose = ( f, g ) -> ( x ) -> f g x
Line 674 ⟶ 904:
console.log "addFirst 2 #=> #{ addFirst 2 }"
console.log "multiple 2 #=> #{ multiple 2 }"
</syntaxhighlight>
{{out}}
Line 687 ⟶ 917:
Or, extending the <code>Function</code> prototype.
<
Function::of = (f) -> (args...) => @ f args...
Line 703 ⟶ 933:
console.log "addFirst 2 #=> #{ addFirst 2 }"
console.log "multiple 2 #=> #{ multiple 2 }"
</syntaxhighlight>
Output is identical.
Line 709 ⟶ 939:
=={{header|Common Lisp}}==
<code>compose</code> returns a function that closes on the lexical variables f and g.
<
Example use:
<
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.
<
(eval `(lambda (x) (funcall ',f (funcall ',g x)))))</
----
In this last example, a macro is used to compose any number of single parameter functions.
<
(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.
<pre>CL-USER> (compose f #'ceiling #'sin #'sqrt)
Line 747 ⟶ 977:
=={{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>.
<
def compose(f : Proc(T, _), g : Proc(_, _)) forall T
Line 753 ⟶ 983:
end
compose(->Math.sin(Float64), ->Math.asin(Float64)).call(0.5) #=> 0.5</
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}}==
<
T delegate(S) compose(T, U, S)(in T delegate(U) f,
Line 767 ⟶ 997:
writeln(compose((int x) => x + 15, (int x) => x ^^ 2)(10));
writeln(compose((int x) => x ^^ 2, (int x) => x + 15)(10));
}</
{{out}}
<pre>115
Line 776 ⟶ 1,006:
Anonymous methods were introduced in Delphi 2009, so next code works with Delphi 2009 and above:
<
{$APPTYPE CONSOLE}
Line 812 ⟶ 1,042:
Writeln(Func3(6)); // 36 = 6 * 3 * 2
Readln;
end.</
=={{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}}==
Line 818 ⟶ 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.
<
define method compose(f,g)
method(x) f(g(x)) end
end;
</syntaxhighlight>
=={{header|Déjà Vu}}==
It is already defined in the standard library as <code>$</code>.
<
labda:
f g</
=={{header|E}}==
<
return fn x { return f(g(x)) }
}</
=={{header|EchoLisp}}==
<
;; By decreasing order of performance
;; 1) user definition : lambda and closure
Line 855 ⟶ 1,112:
(define (sincos x) (sin (cos x)))
sincos → (λ (_x) (⭕️ #sin (#cos _x)))
</syntaxhighlight>
{{out}}
<
((ucompose sin cos) 3) → -0.8360218615377305
((compose sin cos) 3) → -0.8360218615377305
(sincos 3) → -0.8360218615377305
</syntaxhighlight>
=={{header|Ela}}==
It is already defined in standard prelude as (<<) operator.
<
It is already defined in standard prelude as (<<) operator.
<
=={{header|Elena}}==
ELENA
<
extension op : Func1
Line 883 ⟶ 1,140:
public program()
{
var fg := (x => x + 1).compose::(x => x * x);
console.printLine(fg(3))
}</
{{out}}
<pre>
Line 894 ⟶ 1,151:
=={{header|Elixir}}==
{{trans|Erlang}}
<
def compose(f, g), do: fn(x) -> f.(g.(x)) end
Line 904 ⟶ 1,161:
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)</
{{out}}
Line 917 ⟶ 1,174:
Lexical binding is supported as of Emacs 24.1, allowing the use of a closure for function composition.
<
(defun compose (f g)
(lambda (x)
Line 923 ⟶ 1,180:
(let ((func (compose '1+ '1+)))
(funcall func 5)) ;=> 7</
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.
<
`(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 <code>lambda</code>.
<
`(lambda (x) (,f (,g x))))
(let ((func (compose 1+ 1+)))
(funcall func 5)) ;=> 7</
=={{header|Erlang}}==
<
-export([compose/2, multicompose/1]).
Line 948 ⟶ 1,205:
multicompose(Fs) ->
lists:foldl(fun compose/2, fun(X) -> X end, Fs).</
Using them:
<
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</
{{omit from|Euphoria}}
Line 966 ⟶ 1,223:
We can implement composition manually like this (F# Interactive session):
<
val compose : ('a -> 'b) -> ('c -> 'a) -> 'c -> 'b</
Usage:
<
val sin_asin : (float -> float)
> sin_asin 0.5;;
val it : float = 0.5</
=={{header|Factor}}==
Line 982 ⟶ 1,239:
To compose quotations (anonymous functions), <code>compose</code> may be used:
<
[ 2 * 1 + ]
( scratchpad ) 4 [ 2 * ] [ 1 + ] compose call .
9</
=={{header|Fantom}}==
<
class Compose
{
Line 1,004 ⟶ 1,261:
}
}
</syntaxhighlight>
=={{header|Forth}}==
<
>r >r :noname
r> compile,
Line 1,015 ⟶ 1,272:
' 2* ' 1+ compose ( xt )
3 swap execute . \ 7</
=={{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.
<
module functions_module
implicit none
Line 1,100 ⟶ 1,357:
write(*,*) "run compose:", compose(0.5)
end program test_compose
</syntaxhighlight>
=={{header|Fortress}}==
Line 1,109 ⟶ 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.
<
compose[\A, B, C\](f:A->B, g:B->C, i:Any): A->C = do
f(g(i))
Line 1,115 ⟶ 1,372:
composed(i:RR64): RR64 = compose(sin, cos, i)
</syntaxhighlight>
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))
Line 1,126 ⟶ 1,383:
alt_composed(i:RR64): RR64 = compose(sin, cos, i)
</syntaxhighlight>
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)
</syntaxhighlight>
Should you need to, you could also mix both methods by overloading the COMPOSE operator.
Line 1,138 ⟶ 1,395:
=={{header|FreeBASIC}}==
Illustrating with functions that take and return integers.
<
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
<pre>compose( @foo, @bar, n )</pre> for some integer n.
=={{header|FunL}}==
<
def compose( f, g ) = x -> f( g(x) )
Line 1,153 ⟶ 1,410:
sin_asin = compose( sin, asin )
println( sin_asin(0.5) )</
{{out}}
Line 1,163 ⟶ 1,420:
=={{header|Fōrmulæ}}==
{{FormulaeEntry|page=https://formulae.org/?script=examples/Function_composition}}
'''Solution'''
[[File:Fōrmulæ - Function composition 01.png]]
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}}==
<
return x -> f(g(x));
end;
Line 1,176 ⟶ 1,467:
h := Composition(x -> x+1, x -> x*x);
h(5);
# 26</
=={{header|Go}}==
<
// readability and maintainability. This example is written to
// the following function type, which uses float64.
Line 1,189 ⟶ 1,480:
return f(g(x))
}
}</
Example use:
<
import "math"
Line 1,207 ⟶ 1,498:
sin_asin := compose(math.Sin, math.Asin)
fmt.Println(sin_asin(.5))
}</
{{out}}
<pre>
Line 1,215 ⟶ 1,506:
=={{header|Groovy}}==
Test program:
<
final plus1 = { it + 1 }
Line 1,222 ⟶ 1,513:
assert plus1_then_times2(3) == 8
assert times2_then_plus1(3) == 7</
=={{header|Haskell}}==
This is already defined as the '''.''' (dot) operator in Haskell:
<
Prelude> sin_asin 0.5
0.49999999999999994</
Ways to use directly:
<
<
Implementing compose function from scratch:
<
Example use:
<
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 = flip (foldr id)
main :: IO ()
main = print $ composeList [(/ 2), succ, sqrt] 5</
{{Out}}
<pre>1.618033988749895</pre>
=={{header|Hy}}==
<
(fn [x]
(f (g x))))</
=={{header|Icon}} and {{header|Unicon}}==
Line 1,269 ⟶ 1,560:
The solution below can be adapted to work in Icon by reverting to the old syntax for invoking co-expressions.
<
every push(fL := [],!rfL) # use this instead of reverse(fL) as the Icon reverse applies only to strings</
See [[Icon%2BUnicon/Intro#Minor_Differences|Icon and Unicon Introduction:Minor Differences]] for more information
<
h := compose(sqrt,abs)
k := compose(integer,"sqrt",ord)
Line 1,303 ⟶ 1,594:
return (@cf, cf) # 'prime' the co-expr before returning it
end</
{{out}}
Line 1,320 ⟶ 1,611:
'''Solution''':
<
'''Example''':
<syntaxhighlight lang
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 ⟶ 1,620:
Tentative new example:
<
g=: 1&+@|@(2&o.)
h=: f@g</
Example use:
<
1 2 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}}==
<
// Java doesn't have function type so we define an interface
Line 1,372 ⟶ 1,678:
System.out.println(sin_asin.call(0.5)); // prints "0.5"
}
}</
===Java 8===
Line 1,378 ⟶ 1,684:
Java 8's <code>Function</code> interface already has a <code>.compose()</code> default method:
{{works with|Java|8+}}
<
public class Compose {
Line 1,386 ⟶ 1,692:
System.out.println(sin_asin.apply(0.5)); // prints "0.5"
}
}</
Implementing it yourself as a static method:
{{works with|Java|8+}}
<
public class Compose {
Line 1,402 ⟶ 1,708:
System.out.println(sin_asin.apply(0.5)); // prints "0.5"
}
}</
=={{header|JavaScript}}==
===ES5===
====Simple composition of two functions====
<
return function(x) {
return f(g(x));
};
}</
Example:
<
console.log(id(0.5)); // 0.5</
Line 1,424 ⟶ 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.
<
'use strict';
Line 1,473 ⟶ 1,779:
});
})();
</syntaxhighlight>
{{Out}}
Line 1,483 ⟶ 1,789:
====Simple composition of two functions====
<
return x => f(g(x));
}</
or
<
Example:
<
console.log(id(0.5)); // 0.5</
====Multiple composition====
<
// -------------- MULTIPLE COMPOSITION ---------------
// compose (<<<) ::
const compose = (...fs) =>
// A function defined by the right-to-left
// composition of all
(f, g) => x => f(g(x)),
x => x
);
// ---------------------- TEST -----------------------
const
sqrt = Math.sqrt,
Line 1,511 ⟶ 1,821:
return compose(half, succ, sqrt)(5);
// --> 1.618033988749895
})();</
{{Out}}
<pre>1.618033988749895</pre>
Line 1,519 ⟶ 1,829:
=={{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
And yes, there should be a space between the two names.
=={{header|jq}}==
Line 1,525 ⟶ 1,836:
We therefore illustrate here how a function that composes two 0-arity filters can be written:
<syntaxhighlight lang="jq">
# apply g first and then f
def compose(f; g): g | f;
</syntaxhighlight>
Example: 0.5 | compose(asin; sin)
Line 1,536 ⟶ 1,847:
{{works with|Julia|0.6}}
'''Built-in''':
<
'''Alternative''':
<
@show compose(sin, asin)(0.5)</
=={{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
An equivalent explicit definition would be
<
'''Example:'''
<
sin_asin 0.5
0.5</
=={{header|Klingphix}}==
<
:*2 2 * ;
Line 1,563 ⟶ 1,874:
@++ @*2 3 composite ? { result: 7 }
"End " input</
=={{header|Kotlin}}==
<syntaxhighlight lang="kotlin">
fun f(x: Int): Int = x * x
fun g(x: Int): Int = x + 2
fun <T, V, R> compose(f: (
fun main(
val x
println(compose(::f, ::g)(x))
}</
{{out}}
Line 1,585 ⟶ 1,895:
=={{header|Lambdatalk}}==
<syntaxhighlight lang="scheme">
{def compose
{lambda {:f :g :x}
Line 1,602 ⟶ 1,912:
{{f} 3}
-> 80
</syntaxhighlight>
=={{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}}==
<
(defun compose (f g)
(lambda (x)
Line 1,622 ⟶ 1,951:
(io:format '"Expected answer: ~p~n" (list expected))
(io:format '"Answer with compose: ~p~n" (list compose-result))))
</syntaxhighlight>
If you pasted those into the LFE REPL, you can do the following:
<
> (funcall (compose #'math:sin/1 #'math:asin/1)
0.5)
Line 1,639 ⟶ 1,968:
ok
>
</syntaxhighlight>
=={{header|Lingo}}==
Line 1,657 ⟶ 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":
<
----------------------------------------
-- Composes 2 call-functions, returns a new call-function
Line 1,666 ⟶ 1,995:
on compose (f, g)
return script("Composer").new(f, g)
end</
<
property _f
Line 1,701 ⟶ 2,030:
return _movie.call(me._f, _movie, value(cmd))
end if
end</
Usage:
<
f1 = compose(#asin, #sin)
put call(f1, _movie, 0.5)
Line 1,719 ⟶ 2,048:
f3 = compose(f2, f1)
put call(f3, _movie, 0.5)
-- 3.0000</
User-defined custom functions used in demo code above:
<
on asin (x)
res = atan(sqrt(x*x/(1-x*x)))
Line 1,735 ⟶ 2,064:
on triple (x)
return x*3
end</
=={{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.
<
I HAS A fx, I HAS A gx
Line 1,765 ⟶ 2,094:
VISIBLE I IZ sqrincin YR 10 MKAY BTW, prints 121
KTHXBYE</
=={{header|Lua}}==
<
=={{header|M2000 Interpreter}}==
===Using Lambda functions===
<syntaxhighlight lang="m2000 interpreter">
Module CheckIt {
Compose = lambda (f, g)->{
Line 1,783 ⟶ 2,112:
}
CheckIt
</syntaxhighlight>
===Using EVAL and EVAL$===
<syntaxhighlight lang="m2000 interpreter">
class Compose {
private:
Line 1,823 ⟶ 2,152:
UcaseLcase$=ComposeStr$("Ucase$", "Lcase$")
Print UcaseLcase$("GOOD")
</syntaxhighlight>
=={{header|Mathcad}}==
Line 1,849 ⟶ 2,178:
=={{header|Mathematica}} / {{header|Wolfram Language}}==
Built-in function that takes any amount of function-arguments:
<
Composition[f, g, h, i][x]</
gives back:
<
f[g[h[i[x]]]]</
Custom function:
<
compose[Sin, Cos][r]</
gives back:
<syntaxhighlight lang
Composition can be done in more than 1 way:
<
f@g@h@x
x//h//g//f</
all give back:
<syntaxhighlight lang
The built-in function has a couple of automatic simplifications:
<
Composition[f, InverseFunction[f], h][x]</
becomes:
<
h[x]</
=={{header|Maxima}}==
<
load(to_poly_solver);
Line 1,880 ⟶ 2,209:
/* An implementation, to show a use of buildq */
compose(f, g) := buildq([f, g], lambda([x], f(g(x))));</
=={{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:
<
{{out}}
<pre>
Line 1,892 ⟶ 2,221:
=={{header|MiniScript}}==
<
return x * 10
end function
Line 1,907 ⟶ 2,236:
f = compose(@funcA, @funcB)
print f(3) // should be equal to (3+5)*10</
{{out}}
<pre>80</pre>
=={{header|Nemerle}}==
<
using System.Console;
using System.Math;
Line 1,928 ⟶ 2,257:
WriteLine(SinAsin(0.5));
}
}</
=={{header|Never}}==
<syntaxhighlight lang="never">
func compose(f(i : int) -> int, g(i : int) -> int) -> (int) -> int
{
Line 1,949 ⟶ 2,278:
0
}
</syntaxhighlight>
=={{header|NewLISP}}==
<
(lambda (f g) (expand (lambda (x) (f (g x))) 'f 'g))
> ((compose sin asin) 0.5)
0.5
</syntaxhighlight>
=={{header|Nim}}==
<
proc compose[A,B,C](f:
proc plustwo(x: int): int = x + 2
Line 1,968 ⟶ 2,297:
var plusminustwo = compose(plustwo, minustwo)
echo plusminustwo(10)</
=={{header|Objeck}}==
<
bundle Default {
class Test {
Line 2,001 ⟶ 2,330:
}
}
</syntaxhighlight>
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}}==
Line 2,008 ⟶ 2,414:
We restrict ourselves to functions that take and return one object.
<
typedef id (^Function)(id);
Line 2,049 ⟶ 2,455:
}
return 0;
}</
=={{header|OCaml}}==
<
Example use:
<
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</
=={{header|Octave}}==
<
r = @(x) f(g(x));
endfunction
r = compose(@exp, @sin);
r(pi/3)</
=={{header|Oforth}}==
Oforth uses RPN notation. Function composition of f and g is just calling :
<syntaxhighlight lang
If a block is needed, a compose function can be implemented :
<
Usage :
<
[ 1, 2, 3, 4, 5 ] compose(#[ map(#sqrt) ], #[ filter(#isEven) ]) perform</
The last line returns : [1.4142135623731, 2]
=={{header|Ol}}==
<
(define (compose f g)
(lambda (x) (f (g x))))
Line 2,089 ⟶ 2,495:
(define ((compose f g) x) (f (g x)))
</syntaxhighlight>
=={{header|Order}}==
Order supplies the built-in function <code>8compose</code> for this purpose. However, a manual implementation might be:
<
#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 <code>8ap</code> operator, but the functions themselves are still first-class values.
=={{header|Oz}}==
<
fun {Compose F G}
fun {$ X}
Line 2,109 ⟶ 2,515:
SinAsin = {Compose Float.sin Float.asin}
in
{Show {SinAsin 0.5}}</
=={{header|PARI/GP}}==
{{works with|PARI/GP|2.4.2 and above}}
<
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:
<syntaxhighlight lang
=={{header|Pascal}}==
Line 2,126 ⟶ 2,532:
=={{header|Perl}}==
<
my ($f, $g) = @_;
Line 2,135 ⟶ 2,541:
use Math::Trig;
print compose(sub {sin $_[0]}, \&asin)->(0.5), "\n";</
=={{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.
<!--<
<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 ⟶ 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;">4<span style="color: #0000FF;">)</span> <span style="color: #000080;font-style:italic;">-- displays 2.5
<!--</
=={{header|Phixmonti}}==
<
def ++ 1 + enddef
def composite swap exec swap exec enddef
getid ++ getid *2 3 composite print /# result: 7 #/</
=={{header|PHP}}==
{{works with|PHP|5.3+}}
<
function compose($f, $g) {
return function($x) use ($f, $g) { return $f($g($x)); };
Line 2,184 ⟶ 2,590:
$trim_strlen = compose('strlen', 'trim');
echo $result = $trim_strlen(' Test '), "\n"; // prints 4
?></
{{works with|PHP|pre-5.3 and 5.3+}}
works with regular functions as well as functions created by <tt>create_function()</tt>
<
function compose($f, $g) {
return create_function('$x', 'return '.var_export($f,true).'('.var_export($g,true).'($x));');
Line 2,195 ⟶ 2,601:
$trim_strlen = compose('strlen', 'trim');
echo $result = $trim_strlen(' Test '), "\n"; // prints 4
?></
=={{header|PicoLisp}}==
<
(curry (F G) (X)
(F (G X)) ) )</
<
(def 'b (compose 'inc 'dec))
(def 'c (compose '((A) (inc A)) '((B) (dec B))))</
<
-> 7
Line 2,211 ⟶ 2,617:
: (c 7)
-> 7</
=={{header|PostScript}}==
<syntaxhighlight lang="postscript">
/compose { % f g -> { g f }
[ 3 1 roll exch
Line 2,227 ⟶ 2,633:
/plus1 { 1 add } def
/sqPlus1 /square load /plus1 load compose def
</syntaxhighlight>
=={{header|PowerShell}}==
You can simply call g inside f like this:
<syntaxhighlight lang="powershell">
function g ($x) {
$x + $x
Line 2,239 ⟶ 2,645:
}
f (g 1)
</syntaxhighlight>
Or g and f can become paramaters of a new function fg
<syntaxhighlight lang="powershell">
function fg (${function:f}, ${function:g}, $x) {
f (g $x)
}
fg f g 1
</syntaxhighlight>
In both cases the answer is:
Line 2,255 ⟶ 2,661:
=={{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
<
compose(F,G, FG) :-
FG = \X^Z^(call(G,X,Y), call(F,Y,Z)).
</syntaxhighlight>
{{out}}
<pre> ?- compose(sin, asin, F), call(F, 0.5, Y).
Line 2,267 ⟶ 2,673:
=={{header|PureBasic}}==
<
Prototype.i Func(Arg.i)
Line 2,289 ⟶ 2,695:
Title$="With x="+Str(x)
Body$="Compose(f(),g(), x) ="+Str(Compose(@f(),@g(),X))
MessageRequester(Title$,Body$)</
=={{header|Purity}}==
<syntaxhighlight lang="purity">
data compose = f => g => $f . $g
</syntaxhighlight>
=={{header|Python}}==
===Simple composition of two functions===
<
Example use:
<
>>> from math import sin, asin
>>> sin_asin = compose(sin, asin)
>>> sin_asin(0.5)
0.5
>>></
Or, expanding slightly:
{{Works with|Python|3}}
<
Line 2,345 ⟶ 2,751:
if __name__ == '__main__':
main()</
{{Out}}
<pre>[0.49999999999999994, 0.5000000000000001, 0.5000000000000001]</pre>
Line 2,353 ⟶ 2,759:
{{Works with|Python|3}}
<
from
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():
'''
f =
succ,
print(
Line 2,372 ⟶ 2,788:
#
def half(n):
return n / 2
def succ(n):
return 1 + n
if __name__ == '__main__':
main()</
{{Out}}
<pre>1.618033988749895</pre>
=== composition via operator overloading===
Here need composition of several functions is reduced with classes.
{{Works with|Python|3}}
<
# Contents of `pip install compositions'
Line 2,426 ⟶ 2,828:
g = Compose(lambda x: x)
print((f * g)(2))</
=={{header|Qi}}==
Qi supports partial applications, but only when calling a function with one argument.
<syntaxhighlight lang="qi">
(define compose
F G -> (/. X
Line 2,436 ⟶ 2,838:
((compose (+ 1) (+ 2)) 3) \ (Outputs 6) \
</syntaxhighlight>
Alternatively, it can be done like this:
<syntaxhighlight lang="qi">
(define compose F G X -> (F (G X)))
(((compose (+ 1)) (+ 2)) 3) \ (Outputs 6) \
</syntaxhighlight>
=={{header|Quackery}}==
<
nested swap join ] is compose ( g f --> [ )
Line 2,465 ⟶ 2,867:
19 ' double ' [ 4 + ] compose do echo
</syntaxhighlight>
{{out}}
Line 2,472 ⟶ 2,874:
=={{header|R}}==
<
r <- compose(sin, cos)
print(r(.5))</
=={{header|Racket}}==
<
(define (compose f g)
(lambda (x) (f (g x))))
</syntaxhighlight>
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 ⟶ 2,890:
{{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"
my &f = &triple ∘ &prefix:<-> ∘ { $^n + 2 };
say &f(5); # prints "-21".</
=={{header|REBOL}}==
<
Title: "Functional Composition"
URL: http://rosettacode.org/wiki/Functional_Composition
Line 2,506 ⟶ 2,908:
] [
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.
<
bar: func [x] [reform ["bar:" x]]
Line 2,518 ⟶ 2,920:
sin-asin: compose-functions :sine :arcsine
print [crlf "Composition of sine and arcsine:" sin-asin 0.5]</
{{out}}
Line 2,526 ⟶ 2,928:
=={{header|REXX}}==
<
exit /*control should never gets here, but this was added just in case.*/</
=={{header|Ring}}==
<
# Project : Function composition
Line 2,545 ⟶ 2,947:
res = x * y
return res
</syntaxhighlight>
Output:
<pre>
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>
=={{header|Ruby}}==
This <tt>compose</tt> method gets passed two Method objects or Proc objects
<
lambda {|x| f[g[x]]}
end
Line 2,560 ⟶ 2,978:
# verify
p Math.sin(Math.cos(0.5)) # => 0.769196354841008</
=={{header|Rust}}==
Line 2,567 ⟶ 2,985:
===Stable===
Function is allocated on the heap and is called via dynamic dispatch
<
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)
<
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,582 ⟶ 3,000:
{
move |x| f(g(x))
}</
=={{header|Scala}}==
<
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':
<
def o (g: A => A) = compose(f, g)
}
Line 2,599 ⟶ 3,017:
implicit def toComposable[A](f: A => A) = new Composable(f)
val add3 = (add1 _) o add2</
<pre>
Line 2,607 ⟶ 3,025:
=={{header|Scheme}}==
<
;; or:
Line 2,622 ⟶ 3,040:
((_ f g h ...) #'(lambda (y) (f ((compose g h ...) y)))))))
</syntaxhighlight>
Example:
<
(display ((compose sin asin) 0.5))
(newline)</
{{out}}
<syntaxhighlight lang="text">0.5</
=={{header|Sidef}}==
<
func(x) { f(g(x)) }
}
var fg = compose(func(x){ sin(x) }, func(x){ cos(x) })
say fg(0.5) # => 0.76919635484100842185251475805107</
=={{header|Slate}}==
Function (method) composition is standard:
<
=={{header|Smalltalk}}==
<
composer := [ :f :g | [ :x | f value: (g value: x) ] ].
fg := composer value: [ :x | x + 1 ]
value: [ :x | x * x ].
(fg value:3) displayNl.</
=={{header|Standard ML}}==
This is already defined as the '''o''' operator in Standard ML.
<
Example use:
<
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</
=={{header|SuperCollider}}==
has a function composition operator (the message `<>`):
<syntaxhighlight lang="supercollider">
f = { |x| x + 1 };
g = { |x| x * 2 };
h = g <> f;
h.(8); // returns 18
</syntaxhighlight>
=={{header|Swift}}==
<
return { f(g($0)) }
}
let sin_asin = compose(sin, asin)
println(sin_asin(0.5))</
{{out}}
<pre>
Line 2,685 ⟶ 3,103:
{{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.
<
namespace path {::tcl::mathfunc}
Line 2,694 ⟶ 3,112:
set sin_asin [compose sin asin]
{*}$sin_asin 0.5 ;# ==> 0.5
{*}[compose abs int] -3.14 ;# ==> 3</
=={{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}}==
<syntaxhighlight lang="typescript">
function compose<T, U, V> (fn1: (input: T) => U, fn2: (input: U) => V){
return function(value: T) {
Line 2,712 ⟶ 3,165:
console.log(evenSize("ABCD")) // true
console.log(evenSize("ABC")) // false
</syntaxhighlight>
=={{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}}==
Line 2,720 ⟶ 3,181:
{{works with|Bourne Shell}}
<
eval "$1() { $3 | $2; }"
}
Line 2,728 ⟶ 3,189:
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.</
{{works with|Bourne Again SHell}}
This solution uses no external tools, just Bash itself.
<
#compose a new function consisting of the application of 2 unary functions
Line 2,870 ⟶ 3,331:
compose strdownvowel strupcase "Cozy lummox gives smart squid who asks for job pen."
# --> CoZY LuMMoX GiVeS SMaRT SQuiD WHo aSKS FoR JoB PeN.</
Line 2,876 ⟶ 3,337:
With shell pipelines:
<
result @ {$g | $f}
}
Line 2,884 ⟶ 3,345:
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:
<
result @ x {result <={$f <={$g $x}}}
}
Line 2,896 ⟶ 3,357:
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.</
=={{header|Unlambda}}==
Line 2,907 ⟶ 3,368:
for functions f and g, hence hardly worth defining. However, it could
be defined without using the operator like this.
<
test program:
<
#cast %n
test = compose(successor,double) 3</
{{out}}
<pre>7</pre>
Line 2,923 ⟶ 3,384:
'''Implementation'''
<syntaxhighlight lang="vb">
option explicit
class closure
Line 2,942 ⟶ 3,403:
end class
</syntaxhighlight>
'''Invocation'''
<syntaxhighlight lang="vb">
dim c
set c = new closure
Line 2,972 ⟶ 3,433:
wscript.echo c.formula
wscript.echo c(12.3)
</syntaxhighlight>
{{out}}
Line 2,990 ⟶ 3,451:
The simplest way is with a lambda:
<
Alternatively, you can take advantage of partial function calls:
<
Both can be used as follows:
<
Output:
<syntaxhighlight lang
=={{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.
<
<
Defining the <code>compose</code> function
<
=={{header|Wren}}==
<
var double = Fn.new { |x| 2 * x }
Line 3,018 ⟶ 3,479:
var addOne = Fn.new { |x| x + 1 }
System.print(compose.call(double, addOne).call(3))</
{{out}}
Line 3,026 ⟶ 3,487:
=={{header|zkl}}==
<
Which is implemented with a closure (.fp1), which fixes the second paramter
<
{ fcn(x,hgf){ T(x).pump(Void,hgf.xplode()) }.fp1(vm.arglist.reverse()); }</
=={{header|ZX Spectrum Basic}}==
DEF FN commands can be nested, making this appear trivial:
<
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:
<
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)</
{{out}}
<pre>2
|