Function composition: Difference between revisions
(→{{header|Scala}}: Minor fix) |
m (Fixed lang tags.) |
||
Line 11: | Line 11: | ||
=={{header|Ada}}== |
=={{header|Ada}}== |
||
The interface of a generic functions package. The package can be instantiated with any type that has value semantics. Functions are composed using the operation '*'. The same operation applied to an argument evaluates it there: f * x. Functions can be composed with pointers to [[Ada]] functions. (In [[Ada]] functions are not first-class): |
The interface of a generic functions package. The package can be instantiated with any type that has value semantics. Functions are composed using the operation '*'. The same operation applied to an argument evaluates it there: f * x. Functions can be composed with pointers to [[Ada]] functions. (In [[Ada]] functions are not first-class): |
||
<lang ada> |
<lang ada>generic |
||
generic |
|||
type Argument is private; |
type Argument is private; |
||
package Functions is |
package Functions is |
||
Line 24: | Line 23: | ||
private |
private |
||
type Func is array (Positive range <>) of Primitive_Operation; |
type Func is array (Positive range <>) of Primitive_Operation; |
||
end Functions; |
end Functions;</lang> |
||
⚫ | |||
Here is an implementation; |
Here is an implementation; |
||
<lang ada> |
<lang ada>package body Functions is |
||
package body Functions is |
|||
function "*" (Left : Func; Right : Argument) return Argument is |
function "*" (Left : Func; Right : Argument) return Argument is |
||
Result : Argument := Right; |
Result : Argument := Right; |
||
Line 52: | Line 49: | ||
return (Left, Right); |
return (Left, Right); |
||
end "*"; |
end "*"; |
||
end Functions; |
end Functions;</lang> |
||
⚫ | |||
The following is an example of use: |
The following is an example of use: |
||
⚫ | |||
⚫ | |||
⚫ | |||
with Ada.Text_IO; use Ada.Text_IO; |
with Ada.Text_IO; use Ada.Text_IO; |
||
with Functions; |
with Functions; |
||
Line 67: | Line 62: | ||
begin |
begin |
||
Put_Line (Float'Image (Sin_Arcsin * 0.5)); |
Put_Line (Float'Image (Sin_Arcsin * 0.5)); |
||
end Test_Compose; |
end Test_Compose;</lang> |
||
⚫ | |||
Sample output: |
Sample output: |
||
<pre> |
<pre> |
||
Line 81: | Line 75: | ||
violates standard '''ALGOL 68''''s scoping rules. [[ALGOL 68G]] warns about this during |
violates standard '''ALGOL 68''''s scoping rules. [[ALGOL 68G]] warns about this during |
||
parsing, and then rejects during runtime. |
parsing, and then rejects during runtime. |
||
<lang |
<lang algol68>MODE F = PROC(REAL)REAL; # ALGOL 68 is strong typed # |
||
# As a procedure for real to real functions # |
# As a procedure for real to real functions # |
||
Line 99: | Line 93: | ||
{{works with|ALGOL 68|Standard - Jan 1975 Boston SC allowed Partial Parametrization. }} |
{{works with|ALGOL 68|Standard - Jan 1975 Boston SC allowed Partial Parametrization. }} |
||
{{works with|ALGOL 68G|Any - tested with release mk15-0.8b.fc9.i386}} |
{{works with|ALGOL 68G|Any - tested with release mk15-0.8b.fc9.i386}} |
||
<lang |
<lang algol68>MODE F = PROC(REAL)REAL; # ALGOL 68 is strong typed # |
||
# As a procedure for real to real functions # |
# As a procedure for real to real functions # |
||
Line 112: | Line 106: | ||
=={{header|AutoHotkey}}== |
=={{header|AutoHotkey}}== |
||
contributed by Laszlo on the ahk [http://www.autohotkey.com/forum/post-276379.html#276379 forum] |
contributed by Laszlo on the ahk [http://www.autohotkey.com/forum/post-276379.html#276379 forum] |
||
<lang AutoHotkey> |
<lang AutoHotkey>MsgBox % compose("sin","cos",1.5) |
||
MsgBox % compose("sin","cos",1.5) |
|||
compose(f,g,x) { ; function composition |
compose(f,g,x) { ; function composition |
||
Line 225: | Line 218: | ||
=={{header|C sharp|C#}}== |
=={{header|C sharp|C#}}== |
||
<lang csharp> |
<lang csharp>using System; |
||
using System; |
|||
class Program |
class Program |
||
{ |
{ |
||
Line 243: | Line 235: | ||
} |
} |
||
} |
} |
||
⚫ | |||
⚫ | |||
</lang> |
|||
=={{header|Common Lisp}}== |
=={{header|Common Lisp}}== |
||
Line 257: | Line 248: | ||
=={{header|D}}== |
=={{header|D}}== |
||
'''D 2.0 version''' of compose function (template). |
'''D 2.0 version''' of compose function (template). |
||
<lang D> |
<lang D>import std.stdio; |
||
import std.math; |
|||
import std.math; |
|||
T delegate(S) compose(T, U, S)(T delegate(U) f, U delegate(S) g) { |
|||
return (S s) { return f(g(s)); }; |
|||
⚫ | |||
} |
|||
</lang> |
|||
Compose working both in D 1.0 and 2.0: |
Compose working both in D 1.0 and 2.0: |
||
⚫ | |||
<lang D> |
|||
struct Wrapper { |
|||
⚫ | |||
typeof(f) fcp; |
|||
typeof(g) gcp; |
|||
T foobar(S s) { return fcp(gcp(s)); } |
|||
T foobar(S s) { return fcp(gcp(s)); } |
|||
} |
|||
⚫ | |||
⚫ | |||
⚫ | |||
⚫ | |||
} |
} |
||
⚫ | |||
</lang> |
|||
⚫ | |||
⚫ | |||
⚫ | |||
⚫ | |||
=={{header|E}}== |
=={{header|E}}== |
||
<lang e>def compose(f, g) { |
|||
return fn x { return f(g(x)) } |
|||
⚫ | |||
} |
|||
=={{header|Erlang}}== |
=={{header|Erlang}}== |
||
<lang erlang> |
<lang erlang>-module(fn). |
||
-module(fn). |
|||
-export([compose/1, multicompose/2]). |
-export([compose/1, multicompose/2]). |
||
Line 295: | Line 281: | ||
multicompose(Fs) -> |
multicompose(Fs) -> |
||
lists:foldl(fun compose/2, fun(X) -> X end, Fs). |
lists:foldl(fun compose/2, fun(X) -> X end, Fs).</lang> |
||
</lang> |
|||
Using them: |
Using them: |
||
⚫ | |||
<lang erlang> |
|||
⚫ | |||
0.5 |
0.5 |
||
2> Sin_asin_plus1 = fn:multicompose([fun math:sin/1, fun math:asin/1, fun(X) -> X + 1 end]). |
2> Sin_asin_plus1 = fn:multicompose([fun math:sin/1, fun math:asin/1, fun(X) -> X + 1 end]). |
||
#Fun<tests.0.59446746> |
#Fun<tests.0.59446746> |
||
82> Sin_asin_plus1(0.5). |
82> Sin_asin_plus1(0.5). |
||
1.5 |
1.5</lang> |
||
</lang> |
|||
=={{header|F_Sharp|F#}}== |
=={{header|F_Sharp|F#}}== |
||
The composition operator in F# is >> for forward composition and << for reverse. |
The composition operator in F# is >> for forward composition and << for reverse. |
||
<lang fsharp>let compose f g = f << g ;;</lang> |
|||
Usage: |
Usage: |
||
<lang fsharp>> let sin_asin = compose sin asin ;; |
|||
val sin_asin : (float -> float) |
|||
> sin_asin 0.5 ;; |
|||
val it : float = 0.5</lang> |
|||
To see that this can be a closure we can use arithmetic functions: |
To see that this can be a closure we can use arithmetic functions: |
||
<lang fsharp>> let add_then_halve = compose (fun n -> n / 2) (fun n -> n + 10) ;; |
|||
val add_then_halve : (int -> int) |
|||
> add_then_halve 6 ;; |
|||
val it : int = 8</lang> |
|||
=={{header|Forth}}== |
=={{header|Forth}}== |
||
<lang forth> |
<lang forth>: compose ( xt1 xt2 -- xt3 ) |
||
: compose ( xt1 xt2 -- xt3 ) |
|||
>r >r :noname |
>r >r :noname |
||
r> compile, |
r> compile, |
||
Line 332: | Line 314: | ||
' 2* ' 1+ compose ( xt ) |
' 2* ' 1+ compose ( xt ) |
||
3 swap execute . \ 7 |
3 swap execute . \ 7</lang> |
||
</lang> |
|||
=={{header|Groovy}}== |
=={{header|Groovy}}== |
||
Line 375: | Line 356: | ||
'''Solution''': |
'''Solution''': |
||
<lang j>compose =: @</lang> |
|||
'''Example''': |
'''Example''': |
||
<lang j>f compose g</lang> |
|||
Of course, given that <tt>@</tt> is only one character long and is a built-in primitive, there is no need for the cover function <tt>compose</tt>. And <tt>@</tt> is not the only composition primitive; composition is a very important concept in J. For more details, see the [[Talk:Functional Composition#J|talk page]]. |
Of course, given that <tt>@</tt> is only one character long and is a built-in primitive, there is no need for the cover function <tt>compose</tt>. And <tt>@</tt> 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 418: | Line 399: | ||
=={{header|JavaScript}}== |
=={{header|JavaScript}}== |
||
<lang javascript> |
<lang javascript>function compose(f, g) { |
||
⚫ | |||
function compose(f, g) { |
|||
⚫ | |||
⚫ | |||
} |
|||
var id = compose(Math.sin, Math.asin) |
|||
print id(0.5) // 0.5</lang> |
|||
</lang> |
|||
=={{header|Joy}}== |
=={{header|Joy}}== |
||
Composition is the default operation in Joy. The composition of two functions is the concatenation of those functions, in the order in which they are to be applied. |
Composition is the default operation in Joy. The composition of two functions is the concatenation of those functions, in the order in which they are to be applied. |
||
<lang joy> |
<lang joy>g f</lang> |
||
g f |
|||
</lang> |
|||
=={{header|Objective-C}}== |
=={{header|Objective-C}}== |
||
Line 557: | Line 534: | ||
=={{header|Mathematica}}== |
=={{header|Mathematica}}== |
||
Built-in function that takes any amount of function-arguments: |
Built-in function that takes any amount of function-arguments: |
||
<lang Mathematica> |
<lang Mathematica>Composition[f, g][x] |
||
Composition[f, g, h, i][x]</lang> |
|||
Composition[f, g, h, i][x] |
|||
</lang> |
|||
gives back: |
gives back: |
||
<lang Mathematica> |
<lang Mathematica>f[g[x]] |
||
f[g[h[i[x]]]]</lang> |
|||
f[g[h[i[x]]]] |
|||
</lang> |
|||
Custom function: |
Custom function: |
||
<lang Mathematica> |
<lang Mathematica>compose[f_, g_][x_] := f[g[x]] |
||
compose[Sin, Cos][r]</lang> |
|||
compose[Sin, Cos][r] |
|||
</lang> |
|||
gives back: |
gives back: |
||
<lang Mathematica> |
<lang Mathematica>Sin[Cos[r]]</lang> |
||
Sin[Cos[r]] |
|||
</lang> |
|||
Composition can be done in more than 1 way: |
Composition can be done in more than 1 way: |
||
<lang Mathematica> |
<lang Mathematica>Composition[f,g,h][x] |
||
Composition[f,g,h][x] |
|||
f@g@h@x |
f@g@h@x |
||
x//h//g//f |
x//h//g//f</lang> |
||
</lang> |
|||
all give back: |
all give back: |
||
<lang Mathematica> |
<lang Mathematica>f[g[h[x]]]</lang> |
||
f[g[h[x]]] |
|||
</lang> |
|||
The built-in function has a couple of automatic simplifications: |
The built-in function has a couple of automatic simplifications: |
||
<lang Mathematica> |
<lang Mathematica>Composition[f, Identity, g] |
||
Composition[f, InverseFunction[f], h][x]</lang> |
|||
Composition[f, InverseFunction[f], h][x] |
|||
</lang> |
|||
becomes: |
becomes: |
||
<lang Mathematica> |
<lang Mathematica>f[g[x]] |
||
h[x]</lang> |
|||
h[x] |
|||
</lang> |
|||
=={{header|OCaml}}== |
=={{header|OCaml}}== |
||
Line 644: | Line 605: | ||
>>> sin_asin(0.5) |
>>> sin_asin(0.5) |
||
0.5 |
0.5 |
||
>>> |
>>></lang> |
||
=={{header|R}}== |
=={{header|R}}== |
||
Line 671: | Line 632: | ||
=={{header|Scala}}== |
=={{header|Scala}}== |
||
⚫ | |||
<lang scala> |
|||
⚫ | |||
def add1(x: Int) = x+1 |
def add1(x: Int) = x+1 |
||
val add2 = compose(add1, add1) |
val add2 = compose(add1, add1)</lang> |
||
</lang> |
|||
We can achieve a more natural style by creating a container class for composable functions, which provides |
We can achieve a more natural style by creating a container class for composable functions, which provides |
||
the compose method 'o': |
the compose method 'o': |
||
<lang scala> |
<lang scala>class Composable[A](f: A => A) { |
||
class Composable[A](f: A => A) { |
|||
def o (g: A => A) = compose(f, g) |
def o (g: A => A) = compose(f, g) |
||
} |
} |
||
Line 688: | Line 646: | ||
implicit def toComposable[A](f: A => A) = new Composable(f) |
implicit def toComposable[A](f: A => A) = new Composable(f) |
||
val add3 = (add1 _) o add2 |
val add3 = (add1 _) o add2</lang> |
||
</lang> |
|||
<pre> |
<pre> |
||
Line 706: | Line 663: | ||
=={{header|Slate}}== |
=={{header|Slate}}== |
||
Function (method) composition is standard: |
Function (method) composition is standard: |
||
⚫ | |||
<lang slate> |
|||
⚫ | |||
</lang> |
|||
=={{header|Smalltalk}}== |
=={{header|Smalltalk}}== |
||
Line 746: | Line 701: | ||
Composition is built in to Clojure. Simply call the <code>comp</code> function |
Composition is built in to Clojure. Simply call the <code>comp</code> function |
||
⚫ | |||
<lang clojure> |
|||
⚫ | |||
</lang> |
|||
=={{header|Ursala}}== |
=={{header|Ursala}}== |
Revision as of 15:18, 20 November 2009
You are encouraged to solve this task according to the task description, using any language you may know.
Create a function, compose, whose two arguments f and g, are both functions with one argument. The result of compose is to be a function of one argument, (lets call the argument x), which works like applying function f to the result of applying function g to x.
I.e:
compose(f, g)(x) == f( g(x) )
Reference: Function composition
Hint: Implementing compose correctly requires creating a closure. If your language does not support closures directly, you will need to implement it yourself.
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): <lang ada>generic
type Argument is private;
package Functions is
type Primitive_Operation is not null access function (Value : Argument) return Argument; type Func (<>) is private; function "*" (Left : Func; Right : Argument) return Argument; function "*" (Left : Func; Right : Primitive_Operation) return Func; function "*" (Left, Right : Primitive_Operation) return Func; function "*" (Left, Right : Func) return Func;
private
type Func is array (Positive range <>) of Primitive_Operation;
end Functions;</lang> Here is an implementation; <lang ada>package body Functions is
function "*" (Left : Func; Right : Argument) return Argument is Result : Argument := Right; begin for I in reverse Left'Range loop Result := Left (I) (Result); end loop; return Result; end "*";
function "*" (Left, Right : Func) return Func is begin return Left & Right; end "*";
function "*" (Left : Func; Right : Primitive_Operation) return Func is begin return Left & (1 => Right); end "*"; function "*" (Left, Right : Primitive_Operation) return Func is begin return (Left, Right); end "*";
end Functions;</lang> The following is an example of use: <lang ada>with Ada.Numerics.Elementary_Functions; use Ada.Numerics.Elementary_Functions; with Ada.Text_IO; use Ada.Text_IO; with Functions;
procedure Test_Compose is
package Float_Functions is new Functions (Float); use Float_Functions;
Sin_Arcsin : Func := Sin'Access * Arcsin'Access;
begin
Put_Line (Float'Image (Sin_Arcsin * 0.5));
end Test_Compose;</lang> Sample output:
5.00000E-01
ALGOL 68
Note: Returning PROC (REAL x)REAL: f1(f2(x))
from a function apparently
violates standard ALGOL 68's scoping rules. ALGOL 68G warns about this during
parsing, and then rejects during runtime.
<lang algol68>MODE F = PROC(REAL)REAL; # ALGOL 68 is strong typed #
- As a procedure for real to real functions #
PROC compose = (F f, g)F: (REAL x)REAL: f(g(x));
OP (F,F)F O = compose; # or an OPerator that can be overloaded #
- Example use: #
F sin arc sin = compose(sin, arc sin); print((sin arc sin(0.5), (sin O arc sin)(0.5), new line))</lang> Output:
+.500000000000000e +0 +.500000000000000e +0
ALGOL 68 is a stack based language, and the following apparently does not violate it's scoping rules.
<lang algol68>MODE F = PROC(REAL)REAL; # ALGOL 68 is strong typed #
- As a procedure for real to real functions #
PROC compose = (F f, g)F: ((F f2, g2, REAL x)REAL: f2(g2(x)))(f, g, ); # Curry #
PRIO O = 7; OP (F,F)F O = compose; # or an OPerator that can be overloaded #
- Example use: #
F sin arc sin = compose(sin, arc sin); print((sin arc sin(0.5), (sin O arc sin)(0.5), new line))</lang>
AutoHotkey
contributed by Laszlo on the ahk forum <lang AutoHotkey>MsgBox % compose("sin","cos",1.5)
compose(f,g,x) { ; function composition
Return %f%(%g%(x))
}</lang>
C
Only works for functions taking a double and returning a double: <lang c>#include <stdlib.h>
/* generic interface for functors from double to double */ typedef struct double_to_double {
double (*fn)(struct double_to_double *, double);
} double_to_double;
- define CALL(f, x) f->fn(f, x)
/* functor returned by compose */
typedef struct compose_functor {
double (*fn)(struct compose_functor *, double); double_to_double *f; double_to_double *g;
} compose_functor; /* function to be used in "fn" in preceding functor */ double compose_call(compose_functor *this, double x) {
return CALL(this->f, CALL(this->g, x));
} /* returns functor that is the composition of functors
f & g. caller is responsible for deallocating memory */
double_to_double *compose(double_to_double *f,
double_to_double *g) { compose_functor *result = malloc(sizeof(compose_functor)); result->fn = &compose_call; result->f = f; result->g = g; return (double_to_double *)result;
}
- include <math.h>
/* we can make functors for sin and asin by using
the following as "fn" in a functor */
double sin_call(double_to_double *this, double x) {
return sin(x);
} double asin_call(double_to_double *this, double x) {
return asin(x);
}
- include <stdio.h>
int main() {
double_to_double *my_sin = malloc(sizeof(double_to_double)); my_sin->fn = &sin_call; double_to_double *my_asin = malloc(sizeof(double_to_double)); my_asin->fn = &asin_call;
double_to_double *sin_asin = compose(my_sin, my_asin);
printf("%f\n", CALL(sin_asin, 0.5)); /* prints "0.500000" */
free(sin_asin); free(my_sin); free(my_asin);
return 0;
}</lang>
C++
Note: this is already implemented as __gnu_cxx::compose1()
<lang cpp>#include <functional>
- include <cmath>
- include <iostream>
// functor class to be returned by compose function template <class Fun1, class Fun2> class compose_functor :
public std::unary_function<typename Fun2::argument_type, typename Fun1::result_type>
{ protected:
Fun1 f; Fun2 g;
public:
compose_functor(const Fun1& _f, const Fun2& _g) : f(_f), g(_g) { }
typename Fun1::result_type operator()(const typename Fun2::argument_type& x) const { return f(g(x)); }
};
// we wrap it in a function so the compiler infers the template arguments // whereas if we used the class directly we would have to specify them explicitly template <class Fun1, class Fun2> inline compose_functor<Fun1, Fun2> compose(const Fun1& f, const Fun2& g) { return compose_functor<Fun1,Fun2>(f, g); }
int main() {
std::cout << compose(std::ptr_fun(::sin), std::ptr_fun(::asin))(0.5) << std::endl;
return 0;
}</lang>
C#
<lang csharp>using System; class Program {
static void Main(string[] args) { Func<int, int> outfunc = Composer<int, int, int>.Compose(functA, functB); Console.WriteLine(outfunc(5)); //Prints 100 } static int functA(int i) { return i * 10; } static int functB(int i) { return i + 5; } class Composer<A, B, C> { public static Func<C, A> Compose(Func<B, A> a, Func<C, B> b) { return delegate(C i) { return a(b(i)); }; } }
}</lang>
Common Lisp
<lang lisp>(defun compose (f g) (lambda (x) (funcall f (funcall g x))))</lang> Example use: <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</lang>
D
D 2.0 version of compose function (template). <lang D>import std.stdio; import std.math;
T delegate(S) compose(T, U, S)(T delegate(U) f, U delegate(S) g) {
return (S s) { return f(g(s)); };
}</lang>
Compose working both in D 1.0 and 2.0: <lang D>T delegate(S) compose(T, U, S)(T delegate(U) f, U delegate(S) g) {
struct Wrapper { typeof(f) fcp; typeof(g) gcp; T foobar(S s) { return fcp(gcp(s)); } } Wrapper* hold = new Wrapper; hold.fcp = f; hold.gcp = g; return &hold.foobar;
}</lang>
E
<lang e>def compose(f, g) {
return fn x { return f(g(x)) }
}</lang>
Erlang
<lang erlang>-module(fn). -export([compose/1, multicompose/2]).
compose(F,G) -> fun(X) -> F(G(X)) end.
multicompose(Fs) ->
lists:foldl(fun compose/2, fun(X) -> X end, Fs).</lang>
Using them: <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</lang>
F#
The composition operator in F# is >> for forward composition and << for reverse. <lang fsharp>let compose f g = f << g ;;</lang> Usage: <lang fsharp>> let sin_asin = compose sin asin ;; val sin_asin : (float -> float) > sin_asin 0.5 ;; val it : float = 0.5</lang> To see that this can be a closure we can use arithmetic functions: <lang fsharp>> let add_then_halve = compose (fun n -> n / 2) (fun n -> n + 10) ;; val add_then_halve : (int -> int) > add_then_halve 6 ;; val it : int = 8</lang>
Forth
<lang forth>: compose ( xt1 xt2 -- xt3 )
>r >r :noname r> compile, r> compile, postpone ;
' 2* ' 1+ compose ( xt ) 3 swap execute . \ 7</lang>
Groovy
Solution: <lang groovy>def compose = { f, g -> { x -> f(g(x)) } }</lang>
Test program: <lang groovy>def sq = { it * it } def plus1 = { it + 1 } def minus1 = { it - 1 }
def plus1sqd = compose(sq,plus1) def sqminus1 = compose(minus1,sq) def identity = compose(plus1,minus1) def plus1sqdminus1 = compose(minus1,compose(sq,plus1)) def identity2 = compose(Math.&sin,Math.&asin)
println "(x+1)**2 = (0+1)**2 = " + plus1sqd(0) println "x**2-1 = 20**2-1 = " + sqminus1(20) println "(x+1)-1 = (12+1)-1 = " + identity(12) println "(x+1)**2-1 = (3+1)**2-1 = " + plus1sqdminus1(3) println "sin(asin(x)) = sin(asin(1)) = " + identity2(1)</lang>
Output:
(x+1)**2 = (0+1)**2 = 1 x**2-1 = 20**2-1 = 399 (x+1)-1 = (12+1)-1 = 12 (x+1)**2-1 = (3+1)**2-1 = 15 sin(asin(x)) = sin(asin(1)) = 1.0
Haskell
This is already defined as the . (dot) operator in Haskell. <lang haskell>compose f g x = f (g x)</lang> Example use: <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</lang>
J
Solution: <lang j>compose =: @</lang>
Example: <lang j>f compose g</lang>
Of course, given that @ is only one character long and is a built-in primitive, there is no need for the cover function compose. And @ is not the only composition primitive; composition is a very important concept in J. For more details, see the talk page.
Java
<lang java>public class Compose {
// Java doesn't have function type so we define an interface // of function objects instead public interface Fun<A,B> { B call(A x); }
public static <A,B,C> Fun<A,C> compose(final Fun<B,C> f, final Fun<A,B> g) { return new Fun<A,C>() { public C call(A x) { return f.call(g.call(x)); } }; }
public static void main(String[] args) { Fun<Double,Double> sin = new Fun<Double,Double>() { public Double call(Double x) { return Math.sin(x); } }; Fun<Double,Double> asin = new Fun<Double,Double>() { public Double call(Double x) { return Math.asin(x); } };
Fun<Double,Double> sin_asin = compose(sin, asin);
System.out.println(sin_asin.call(0.5)); // prints "0.5" }
}</lang>
JavaScript
<lang javascript>function compose(f, g) {
return function(x) { return f(g(x)) }
}
var id = compose(Math.sin, Math.asin) print id(0.5) // 0.5</lang>
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. <lang joy>g f</lang>
Objective-C
The FunctionComposer is able to compose any object that conforms to the protocol FunctionCapsule (a selector/method accepting any object as argument and returning another object, i.e. computing a "function" of an object). A FunctionCaps class thought to encapsulate a function returning a double and with a double as argument is shown; anyway, as said, any object conforming to FunctionCapsule protocol can be composed with another object conforming to the same protocol. Argument passed and returned can be of any object type.
<lang objc>#include <Foundation/Foundation.h>
// the protocol of objects that can behave "like function" @protocol FunctionCapsule -(id)computeWith: (id)x; @end
// a commodity for "encapsulating" double f(double)
typedef double (*func_t)(double);
@interface FunctionCaps : NSObject <FunctionCapsule>
{
func_t function;
} +(id)capsuleFor: (func_t)f; -(id)initWithFunc: (func_t)f; @end
@implementation FunctionCaps -(id)initWithFunc: (func_t)f {
self = [self init]; function = f; return self;
} +(id)capsuleFor: (func_t)f {
return [[[self alloc] initWithFunc: f] autorelease];
} -(id)computeWith: (id)x {
return [NSNumber numberWithDouble: function([x doubleValue])];
} @end
// the "functions" composer
@interface FunctionComposer : NSObject <FunctionCapsule>
{
id funcA; id funcB;
} +(id) createCompositeFunctionWith: (id)A and: (id)B; -(id) initComposing: (id)A with: (id)B; -(id) init; -(id) dealloc; @end
@implementation FunctionComposer +(id) createCompositeFunctionWith: (id)A and: (id)B {
return [[[self alloc] initComposing: A with: B] autorelease];
}
-(id) init {
NSLog(@"FunctionComposer: init with initComposing!"); funcA = nil; funcB = nil; return self;
}
-(id) initComposing: (id)A with: (id)B {
self = [super init]; if ( ([A conformsToProtocol: @protocol(FunctionCapsule)] == YES) && ([B conformsToProtocol: @protocol(FunctionCapsule)] == YES) ) { [A retain]; [B retain]; funcA = A; funcB = B; return self; } NSLog(@"FunctionComposer: cannot compose functions not responding to protocol FunctionCapsule!"); return nil;
}
-(id)computeWith: (id)x {
return [funcA computeWith: [funcB computeWith: x]];
} @end
-(void) dealloc {
[funcA release]; [funcB release]; [super dealloc];
}
// functions outside...
double my_f(double x)
{
return x+1.0;
}
double my_g(double x) {
return x*x;
}
int main()
{
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
id funcf = [FunctionCaps capsuleFor: my_f]; id funcg = [FunctionCaps capsuleFor: my_g];
id composed = [FunctionComposer
createCompositeFunctionWith: funcf and: funcg];
printf("g(2.0) = %lf\n", [[funcg computeWith: [NSNumber numberWithDouble: 2.0]] doubleValue]); printf("f(2.0) = %lf\n", [[funcf computeWith: [NSNumber numberWithDouble: 2.0]] doubleValue]); printf("f(g(2.0)) = %lf\n", [[composed computeWith: [NSNumber numberWithDouble: 2.0]] doubleValue]);
[pool release]; return 0;
}</lang>
Mathematica
Built-in function that takes any amount of function-arguments: <lang Mathematica>Composition[f, g][x] Composition[f, g, h, i][x]</lang> gives back: <lang Mathematica>f[g[x]] f[g[h[i[x]]]]</lang> Custom function: <lang Mathematica>compose[f_, g_][x_] := f[g[x]] compose[Sin, Cos][r]</lang> gives back: <lang Mathematica>Sin[Cos[r]]</lang> Composition can be done in more than 1 way: <lang Mathematica>Composition[f,g,h][x] f@g@h@x x//h//g//f</lang> all give back: <lang Mathematica>f[g[h[x]]]</lang> The built-in function has a couple of automatic simplifications: <lang Mathematica>Composition[f, Identity, g] Composition[f, InverseFunction[f], h][x]</lang> becomes: <lang Mathematica>f[g[x]] h[x]</lang>
OCaml
<lang ocaml>let compose f g x = f (g x)</lang> Example use: <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</lang>
Octave
<lang octave>function r = compose(f, g)
r = @(x) f(g(x));
endfunction
r = compose(@exp, @sin); r(pi/3)</lang>
Perl
<lang perl>sub compose
{my ($f, $g) = @_; return sub {$f->($g->(@_))};}
use Math::Trig; print compose(sub {sin $_[0]}, \&asin)->(0.5), "\n";</lang>
Perl 6
<lang perl6>sub infix:<∘> (Callable $f, Callable $g --> Block) {
sub (*@args) { $f($g(|@args)) };
}</lang>
Example of use:
<lang perl6>sub triple($n) { 3 * $n } my $f = &triple ∘ { $^x + 2 }; say $f(5); # Prints "21".</lang>
Python
<lang python>compose = lambda f, g: lambda x: f( g(x) )</lang> Example use: <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 >>></lang>
R
<lang R>compose <- function(f,g) function(x) { f(g(x)) } r <- compose(sin, cos) print(r(.5))</lang>
Ruby
This compose method gets passed two Method objects <lang ruby>def compose(f,g)
lambda {|x| f.call(g.call(x))}
end s = compose(Math.method('sin'), Math.method('cos')) s.call(0.5) # => 0.769196354841008
- verify
Math.sin(Math.cos(0.5)) # => 0.769196354841008</lang>
With this method, you pass two symbols <lang ruby>include Math def compose(f,g)
lambda {|x| send(f, send(g, x))}
end s = compose(:sin, :cos) s.call(0.5) # => 0.769196354841008</lang>
Scala
<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)</lang>
We can achieve a more natural style by creating a container class for composable functions, which provides the compose method 'o':
<lang scala>class Composable[A](f: A => A) {
def o (g: A => A) = compose(f, g)
}
implicit def toComposable[A](f: A => A) = new Composable(f)
val add3 = (add1 _) o add2</lang>
> (add2 o add3)(37) res0: Int = 42
Scheme
<lang scheme>(define (compose f g) (lambda (x) (f (g x))))</lang> Example use: <lang scheme>> (define (compose f g) (lambda (x) (f (g x)))) > (define sin_asin (compose sin asin)) > (sin_asin 0.5) 0.5</lang>
Slate
Function (method) composition is standard: <lang slate>[| :x | x + 1] ** [| :x | x squared] applyTo: {3}</lang>
Smalltalk
<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.</lang>
Standard ML
This is already defined as the o operator in Standard ML. <lang sml>fun compose (f, g) x = f (g x)</lang> Example use: <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</lang>
Tcl
This creates a compose
procedure that returns an anonymous function term that should be expanded as part of application to its argument.
<lang tcl>package require Tcl 8.5
namespace path {::tcl::mathfunc}
proc compose {f g} {
list apply [list {f g x} {{*}$f [{*}$g $x]}] $f $g]
}
set sin_asin [compose sin asin] {*}$sin_asin 0.5 ;# ==> 0.5 {*}[compose abs int] -3.14 ;# ==> 3</lang>
Clojure
Composition is built in to Clojure. Simply call the comp
function
<lang lisp>user=>(comp rest rest);returns a closure that takes the rest of rest.</lang>
Ursala
Functional composition is a built in operation expressible as f+g for functions f and g, hence hardly worth defining. However, it could be defined without using the operator like this. <lang Ursala>compose("f","g") "x" = "f" "g" "x"</lang> test program: <lang Ursala>#import nat
- cast %n
test = compose(successor,double) 3</lang> output:
7