Function composition: Difference between revisions
(→{{header|Déjà Vu}}: Oops, wrong example) |
|||
Line 391: | Line 391: | ||
(def inc2 (compose inc inc)) |
(def inc2 (compose inc inc)) |
||
(println (inc2 5)) ; prints 7</lang> |
(println (inc2 5)) ; prints 7</lang> |
||
=={{header|CoffeeScript}}== |
|||
<lang coffeescript> |
|||
compose = ( f, g ) -> ( x ) -> f g x |
|||
# Example |
|||
add2 = ( x ) -> x + 2 |
|||
mul2 = ( x ) -> x * 2 |
|||
mulFirst = compose add2, mul2 |
|||
addFirst = compose mul2, add2 |
|||
console.log "add2 2 #=> #{ add2 2 }" |
|||
console.log "mul2 2 #=> #{ mul2 2 }" |
|||
console.log "mulFirst 2 #=> #{ mulFirst 2 }" |
|||
console.log "addFirst 2 #=> #{ addFirst 2 }" |
|||
</lang> |
|||
Outputs: |
|||
<pre> |
|||
add2 2 #=> 4 |
|||
mul2 2 #=> 4 |
|||
mulFirst 2 #=> 6 |
|||
addFirst 2 #=> 8 |
|||
</pre> |
|||
=={{header|Common Lisp}}== |
=={{header|Common Lisp}}== |
Revision as of 06:07, 24 September 2013
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: In some languages, implementing compose correctly requires creating a closure.
ActionScript
ActionScript supports closures, making function composition very straightforward. <lang 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)); }</lang>
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
Aikido
<lang aikido> import math
function compose (f, g) {
return function (x) { return f(g(x)) }
}
var func = compose(Math.sin, Math.asin) println (func(0.5)) // 0.5
</lang>
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>
Argile
Only works for functions taking real and returning real (double precision, 64 bits)
<lang Argile>use std, math
let my_asin = new Function (.:<any,real x>:. -> real {asin x}) let my__sin = new Function (.:<any,real x>:. -> real { sin x}) let sinasin = my__sin o my_asin print sin asin 0.5 print *my__sin 0.0 print *sinasin 0.5 ~my_asin ~my__sin ~sinasin
=: <Function f> o <Function g> := -> Function {compose f g}
.:compose <Function f, Function g>:. -> Function
use array let d = (new array of 2 Function) (d[0]) = f ; (d[1]) = g let c = new Function (.:<array of Function fg, real x>:. -> real { *fg[0]( *fg[1](x) ) }) (d) c.del = .:<any>:.{free any} c
class Function
function(any)(real)->(real) func any data function(any) del
=: * <Function f> <real x> := -> real
Cgen "(*("(f.func)"))("(f.data)", "(x)")"
.: del Function <Function f> :.
unless f.del is nil call f.del with f.data free f
=: ~ <Function f> := {del Function f}
.: new Function <function(any)(real)-\>real func> (<any data>):. -> Function
let f = new Function f.func = func f.data = data f</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>
BBC BASIC
<lang bbcbasic> REM Create some functions for testing:
DEF FNsqr(a) = SQR(a) DEF FNabs(a) = ABS(a) REM Create the function composition: SqrAbs = FNcompose(FNsqr(), FNabs()) REM Test calling the composition: x = -2 : PRINT ; x, FN(SqrAbs)(x) END DEF FNcompose(RETURN f%, RETURN g%) LOCAL f$, p% : DIM p% 7 : p%!0 = f% : p%!4 = g% f$ = "(x)=" + CHR$&A4 + "(&" + STR$~p% + ")(" + \ \ CHR$&A4 + "(&" + STR$~(p%+4) + ")(x))" DIM p% LEN(f$) + 4 : $(p%+4) = f$ : !p% = p%+4 = p%</lang>
Output:
-2 1.41421356
Bori
<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)); }
void button1_onClick (Widget widget) { double d = compose(sin, asin, 0.5); label1.setText(d.toString(9)); }</lang> Output on Android phone: <lang bori>0.500000000</lang>
Brat
<lang brat>compose = { f, g | { x | f g x } }
- Test
add1 = { x | x + 1 } double = { x | x * 2 } b = compose(->double ->add1) p b 1 #should print 4</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++
<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>
composing std::function
<lang cpp>#include <iostream>
- include <functional>
- include <cmath>
template <typename A, typename B, typename C> std::function<C(A)> compose(std::function<C(B)> f, std::function<B(A)> g) {
return [f,g](A x) { return f(g(x)); };
}
int main() {
std::function<double(double)> f = sin; std::function<double(double)> g = asin; std::cout << compose(f, g)(0.5) << std::endl;
return 0;
}</lang>
GCC's C++ library has a built-in compose function
<lang cpp>#include <iostream>
- include <cmath>
- include <ext/functional>
int main() {
std::cout << __gnu_cxx::compose1(std::ptr_fun(::sin), std::ptr_fun(::asin))(0.5) << std::endl;
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>
Clojure
Function composition is built in to Clojure. Simply call the comp
function.
A manual implementation could look like this: <lang clojure>(defn compose [f g]
(fn [x] (f (g x))))
- Example
(def inc2 (compose inc inc)) (println (inc2 5)) ; prints 7</lang>
CoffeeScript
<lang coffeescript> compose = ( f, g ) -> ( x ) -> f g x
- Example
add2 = ( x ) -> x + 2 mul2 = ( x ) -> x * 2
mulFirst = compose add2, mul2 addFirst = compose mul2, add2
console.log "add2 2 #=> #{ add2 2 }" console.log "mul2 2 #=> #{ mul2 2 }" console.log "mulFirst 2 #=> #{ mulFirst 2 }" console.log "addFirst 2 #=> #{ addFirst 2 }" </lang>
Outputs:
add2 2 #=> 4 mul2 2 #=> 4 mulFirst 2 #=> 6 addFirst 2 #=> 8
Common Lisp
compose
returns a function that closes on the lexical variables f and g.
<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>
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.
<lang lisp>(defun compose (f g)
(eval `(lambda (x) (funcall ',f (funcall ',g x))))</lang>
In this last example, a macro is used to compose any number of single parameter functions. <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))))</lang> Because this macro expands into a defun form, the function returned by compose is in the function namespace and the use of funcall is not necessary.
CL-USER> (compose f #'ceiling #'sin #'sqrt) F CL-USER> (compose g #'1+ #'abs #'cos) G CL-USER> (compose h #'f #'g) H CL-USER> (values (f pi) (g pi) (h pi)) 1 2.0L0 1 CL-USER>
D
<lang d>import std.stdio;
T delegate(S) compose(T, U, S)(in T delegate(U) f,
in U delegate(S) g) { return s => f(g(s));
}
void main() {
writeln(compose((int x) => x + 15, (int x) => x ^^ 2)(10)); writeln(compose((int x) => x ^^ 2, (int x) => x + 15)(10));
}</lang>
- Output:
115 625
Delphi
Anonymous methods were introduced in Delphi 2009, so next code works with Delphi 2009 and above:
<lang Delphi>program AnonCompose;
{$APPTYPE CONSOLE}
type
TFunc = reference to function(Value: Integer): Integer;
function Compose(F, G: TFunc): TFunc; begin
Result:= function(Value: Integer): Integer begin Result:= F(G(Value)); end
end;
var
Func1, Func2, Func3: TFunc;
begin
Func1:= function(Value: Integer): Integer begin Result:= Value * 2; end;
Func2:= function(Value: Integer): Integer begin Result:= Value * 3; end;
Func3:= Compose(Func1, Func2);
Writeln(Func3(6)); // 36 = 6 * 3 * 2 Readln;
end.</lang>
Déjà Vu
<lang dejavu>compose f g: labda: f g</lang>
Dylan
<lang dylan>define method compose(f,g)
method(x) f(g(x)) end
end;</lang>
Ela
It is already defined in standard prelude as (<<) operator.
<lang ela>let compose f g x = f (g x)</lang>
E
<lang e>def compose(f, g) {
return fn x { return f(g(x)) }
}</lang>
Ela
It is already defined in standard prelude as (<<) operator.
<lang ela>compose f g x = 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 most-used composition operator in F# is >>
. It implements forward composition, i.e. f >> g
is a function which calls f first and then calls g on the result.
The reverse composition operator <<
, on the other hand, exactly fulfills the requirements of the compose function described in this task.
We can implement composition manually like this (F# Interactive session): <lang fsharp>> let compose f g x = f (g x);;
val compose : ('a -> 'b) -> ('c -> 'a) -> 'c -> 'b</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>
Factor
When passing functions around and creating anonymous functions, Factor uses so called quotations. There is already a word (compose
) that provides composition of quotations.
<lang factor>( scratchpad ) [ 2 * ] [ 1 + ] compose .
[ 2 * 1 + ]
( scratchpad ) 4 [ 2 * ] [ 1 + ] compose call .
9</lang>
Fantom
<lang fantom> class Compose {
static |Obj -> Obj| compose (|Obj -> Obj| fn1, |Obj -> Obj| fn2) { return |Obj x -> Obj| { fn2 (fn1 (x)) } }
public static Void main () { double := |Int x -> Int| { 2 * x } |Int -> Int| quad := compose(double, double) echo ("Double 3 = ${double(3)}") echo ("Quadruple 3 = ${quad (3)}") }
} </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>
GAP
<lang gap>Composition := function(f, g)
return x -> f(g(x));
end;
h := Composition(x -> x+1, x -> x*x); h(5);
- 26</lang>
Go
<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. type ffType func(float64) float64
// compose function requested by task func compose(f, g ffType) ffType {
return func(x float64) float64 { return f(g(x)) }
}</lang> Example use: <lang go>package main
import "math" import "fmt"
type ffType func(float64) float64
func compose(f, g ffType) ffType {
return func(x float64) float64 { return f(g(x)) }
}
func main() {
sin_asin := compose(math.Sin, math.Asin) fmt.Println(sin_asin(.5))
}</lang> Output:
0.5
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>
Icon and Unicon
Icon and Unicon don't have a lambda function or native closure; however, they do have co-expressions which are extremely versatile and can be used to achieve the same effect. The list of functions to compose can be a 'procedure', 'co-expression", or an invocable string (i.e. procedure name or unary operator). It will correctly handle compose(compose(...),..).
There are a few limitations to be aware of:
- type(compose(f,g)) returns a co-expression not a procedure
- this construction only handles functions of 1 argument (a closure construct is better for the general case)
The solution below can be adapted to work in Icon by reverting to the old syntax for invoking co-expressions.
<lang Icon> x @ f # use this syntax in Icon instead of the Unicon f(x) to call co-expressions
every push(fL := [],!rfL) # use this instead of reverse(fL) as the Icon reverse applies only to strings</lang>
See Icon and Unicon Introduction:Minor Differences for more information
<lang Unicon>procedure main(arglist)
h := compose(sqrt,abs) k := compose(integer,"sqrt",ord) m := compose("-",k) every write(i := -2 to 2, " h=(sqrt,abs)-> ", h(i)) every write(c := !"1@Q", " k=(integer,\"sqrt\",ord)-> ", k(c)) write(c := "1"," m=(\"-\",k) -> ",m(c))
end
invocable all # permit string invocations
procedure compose(fL[]) #: compose(f1,f2,...) returns the functional composition of f1,f2,... as a co-expression
local x,f,saveSource
every case type(x := !fL) of { "procedure"|"co-expression": &null # procedures and co-expressions are fine "string" : if not proc(x,1) then runnerr(123,fL) # as are invocable strings (unary operators, and procedures) default: runerr(123,fL) }
fL := reverse(fL) # reverse and isolate from mutable side-effects cf := create { saveSource := &source # don't forget where we came from repeat { x := (x@saveSource)[1] # return result and resume here saveSource := &source # ... every f := !fL do x := f(x) # apply the list of 'functions' } } return (@cf, cf) # 'prime' the co-expr before returning it
end</lang>
Sample Output:
-2 h=(sqrt,abs)-> 1.414213562373095 -1 h=(sqrt,abs)-> 1.0 0 h=(sqrt,abs)-> 0.0 1 h=(sqrt,abs)-> 1.0 2 h=(sqrt,abs)-> 1.414213562373095 1 k=(integer,"sqrt",ord)-> 7 @ k=(integer,"sqrt",ord)-> 8 Q k=(integer,"sqrt",ord)-> 9 1 m=("-",k) -> -7
J
Solution: <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.
Tentative new example:
<lang j>f=: >.@(1&o.)@%: g=: 1&+@|@(2&o.) h=: f@g</lang>
Example use: <lang j> (f, g, h) 1p1 1 2 1</lang>
Note: 1&o. is sine (mnemonic: sine is an odd circular function), 2&o. is cosine (cosine is an even circular function), %: is square root, >. is ceiling, | is absolute value and 1&+ adds 1.
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>
<lang java>import java.util.function.Function;
public class Compose {
public static <A,B,C> Function<A,C> compose(Function<B,C> f, Function<A,B> g) { return x -> f.apply(g.apply(x)); }
public static void main(String[] args) { Function<Double,Double> sin_asin = compose(Math::sin, Math::asin);
System.out.println(sin_asin.apply(0.5)); // prints "0.5" }
}</lang>
JavaScript
<lang javascript>function compose(f, g) {
return function(x) { return f(g(x)); };
}</lang> Example: <lang javascript>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>
K
Functions are automatically curried in K if called with missing arguments. <lang k>compose: {x@y@z}</lang> Example: <lang k> sin_asin: compose[_sin;_asin]
sin_asin 0.5
0.5</lang>
LFE
<lang lisp> (defmodule compose
(export all) (import (from math (sin 1) (asin 1))) (import (from io (format 2))))
(defun compose (f g)
(lambda (x) (funcall f (funcall g x))))
(defun check ()
(let* ((sin-asin (compose #'sin/1 #'asin/1)) (expected (sin (asin 0.5))) (compose-result (funcall sin-asin 0.5))) (format '"Expected answer: ~p~n" (list expected)) (format '"Answer with compose: ~p~n" (list compose-result))))
</lang>
Running the code: <lang lisp> > (slurp '"compose.lfe")
- (ok compose)
> (check) Expected answer: 0.49999999999999994 Answer with compose: 0.49999999999999994 ok > </lang>
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. <lang LOLCODE>HAI 1.3
I HAS A fx, I HAS A gx
HOW IZ I composin YR f AN YR g
fx R f, gx R g HOW IZ I composed YR x FOUND YR I IZ fx YR I IZ gx YR x MKAY MKAY IF U SAY SO FOUND YR composed
IF U SAY SO
HOW IZ I incin YR num
FOUND YR SUM OF num AN 1
IF U SAY SO
HOW IZ I sqrin YR num
FOUND YR PRODUKT OF num AN num
IF U SAY SO
I HAS A incsqrin ITZ I IZ composin YR incin AN YR sqrin MKAY VISIBLE I IZ incsqrin YR 10 MKAY BTW, prints 101
I HAS A sqrincin ITZ I IZ composin YR sqrin AN YR incin MKAY VISIBLE I IZ sqrincin YR 10 MKAY BTW, prints 121
KTHXBYE</lang>
Lua
<lang lua>function compose(f, g) return function(...) return f(g(...)) end end</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>
Maxima
<lang maxima>/* built-in */ load(to_poly_solver);
compose_functions([sin, cos]); /* lambda([%g0],sin(cos(%g0)))*/
/* An implementation, to show a use of buildq */ compose(f, g) := buildq([f, g], lambda([x], f(g(x))));</lang>
Nemerle
<lang Nemerle>using System; using System.Console; using System.Math;
module Composition {
Compose[T](f : T -> T, g : T -> T, x : T) : T { f(g(x)) } Main() : void { def SinAsin = Compose(Sin, Asin, _); WriteLine(SinAsin(0.5)); }
}</lang>
NewLISP
<lang NewLISP>> (define (compose f g) (expand (lambda (x) (f (g x))) 'f 'g)) (lambda (f g) (expand (lambda (x) (f (g x))) 'f 'g)) > ((compose sin asin) 0.5) 0.5 </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 <NSObject> -(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 {
if ((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<FunctionCapsule> funcA; id<FunctionCapsule> funcB;
} +(id) createCompositeFunctionWith: (id<FunctionCapsule>)A and: (id<FunctionCapsule>)B; -(id) initComposing: (id<FunctionCapsule>)A with: (id<FunctionCapsule>)B; @end
@implementation FunctionComposer +(id) createCompositeFunctionWith: (id<FunctionCapsule>)A and: (id<FunctionCapsule>)B {
return [[[self alloc] initComposing: A with: B] autorelease];
}
-(id) init {
[self release]; @throw [NSException exceptionWithName:NSInternalInconsistencyException reason:@"FunctionComposer: init with initComposing!" userInfo:nil]; return nil;
}
-(id) initComposing: (id<FunctionCapsule>)A with: (id<FunctionCapsule>)B {
if ((self = [super init])) { if ( [A respondsToSelector: @selector(computeWith:)] && [B respondsToSelector: @selector(computeWith:)] ) { funcA = [A retain]; funcB = [B retain]; return self; } NSLog(@"FunctionComposer: cannot compose functions not responding to protocol FunctionCapsule!"); [self release]; } return nil;
}
-(id)computeWith: (id)x {
return [funcA computeWith: [funcB computeWith: x]];
}
-(void) dealloc {
[funcA release]; [funcB release]; [super dealloc];
} @end
// 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<FunctionCapsule> funcf = [FunctionCaps capsuleFor: my_f]; id<FunctionCapsule> funcg = [FunctionCaps capsuleFor: my_g];
id<FunctionCapsule> 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>
Blocks
As above, we restrict ourselves to functions that take and return one object.
<lang objc>#include <Foundation/Foundation.h>
typedef id (^Function)(id);
// a commodity for "encapsulating" double f(double) typedef double (*func_t)(double); Function encapsulate(func_t f) {
return [[^(id x) { return [NSNumber numberWithDouble: f([x doubleValue])]; } copy] autorelease];
}
Function compose(Function a, Function b) {
return [[^(id x) { return a(b(x)); } copy] autorelease];
}
// 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];
Function f = encapsulate(my_f); Function g = encapsulate(my_g); Function composed = compose(f, g); printf("g(2.0) = %lf\n", [g([NSNumber numberWithDouble: 2.0]) doubleValue]); printf("f(2.0) = %lf\n", [f([NSNumber numberWithDouble: 2.0]) doubleValue]); printf("f(g(2.0)) = %lf\n", [composed([NSNumber numberWithDouble: 2.0]) doubleValue]);
[pool release]; return 0;
}</lang>
Objeck
<lang objeck> bundle Default {
class Test { @f : static : (Int) ~ Int; @g : static : (Int) ~ Int; function : Main(args : String[]) ~ Nil { compose := Composer(F(Int) ~ Int, G(Int) ~ Int); compose(13)->PrintLine(); } function : F(a : Int) ~ Int { return a + 14; }
function : G(a : Int) ~ Int { return a + 15; } function : Compose(x : Int) ~ Int { return @f(@g(x)); } function : Composer(f : (Int) ~ Int, g : (Int) ~ Int) ~ (Int) ~ Int { @f := f; @g := g; return Compose(Int) ~ Int; } }
} </lang> prints: 42
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>
Order
Order supplies the built-in function 8compose
for this purpose. However, a manual implementation might be:
<lang c>#include <order/interpreter.h>
- define ORDER_PP_DEF_8comp ORDER_PP_FN( \
8fn(8F, 8G, 8fn(8X, 8ap(8F, 8ap(8G, 8X)))) )</lang>
Interpreter limitations mean that local variables containing functions must be called with the 8ap
operator, but the functions themselves are still first-class values.
Oz
<lang oz>declare
fun {Compose F G} fun {$ X} {F {G X}} end end
SinAsin = {Compose Float.sin Float.asin}
in
{Show {SinAsin 0.5}}</lang>
PARI/GP
<lang parigp>compose(f, g)={
x -> f(g(x))
};
compose(x->sin(x),x->cos(x)(1)</lang>
Usage note: In Pari/GP 2.4.3, this can be expressed more succinctly: <lang parigp>compose(sin,cos)(1)</lang>
Pascal
See Delphi
Perl
<lang perl>sub compose {
my ($f, $g) = @_;
sub { $f -> ($g -> (@_)) };
}
use Math::Trig; print compose(sub {sin $_[0]}, \&asin)->(0.5), "\n";</lang>
Perl 6
We'll define an infix compose operator from ∘, U+2218 RING OPERATOR. <lang perl6>sub infix:<∘> (&f, &g --> Block) {
-> $args { f g |$args }
}</lang>
Example of composing a routine, an operator, and a lambda:
<lang perl6>sub triple($n) { 3 * $n } my &f = &triple ∘ &prefix:<-> ∘ { $^n + 2 }; say &f(5); # Prints "-21".</lang>
PHP
<lang php><?php function compose($f, $g) {
return function($x) use ($f, $g) { return $f($g($x)); };
}
$trim_strlen = compose('strlen', 'trim'); echo $result = $trim_strlen(' Test '), "\n"; // prints 4 ?></lang>
works with regular functions as well as functions created by create_function() <lang php><?php function compose($f, $g) {
return create_function('$x', 'return '.var_export($f,true).'('.var_export($g,true).'($x));');
}
$trim_strlen = compose('strlen', 'trim'); echo $result = $trim_strlen(' Test '), "\n"; // prints 4 ?></lang>
PicoLisp
<lang PicoLisp>(de compose (F G)
(curry (F G) (X) (F (G X)) ) )</lang>
<lang PicoLisp>(def 'a (compose inc dec)) (def 'b (compose 'inc 'dec)) (def 'c (compose '((A) (inc A)) '((B) (dec B))))</lang> <lang PicoLisp>: (a 7) -> 7
- (b 7)
-> 7
- (c 7)
-> 7</lang>
PostScript
PostScript functions typically pops operand stack for argument, so calling two functions one after another naturally makes a compound function, and making a compound requires just def
ing them:<lang PostScript>/square { dup mul } def
/plus1 { 1 add } def
/sqPlus1{ square plus1 } def
% if the task really demands we make a function called "compose", well /compose { def } def % so now we can say: /sqPlus1 { square plus1 } compose</lang>
Prolog
Works with SWI-Prolog and module lambda, written by Ulrich Neumerkel found there http://www.complang.tuwien.ac.at/ulrich/Prolog-inedit/lambda.pl <lang Prolog>:- use_module(lambda).
compose(F,G, FG) :- FG = \X^Z^(call(G,X,Y), call(F,Y,Z)). </lang> Example of output :
?- compose(sin, asin, F), call(F, 0.5, Y). F = \_G4586^_G4589^ (call(asin,_G4586,_G4597),call(sin,_G4597,_G4589)), Y = 0.5.
PureBasic
<lang PureBasic>;Declare how our function looks like Prototype.i Func(Arg.i)
- Make a procedure that composes any functions of type "Func"
Procedure Compose(*a.Func,*b.Func, x)
ProcedureReturn *a(*b(x))
EndProcedure
- Just a procedure fitting "Func"
Procedure f(n)
ProcedureReturn 2*n
EndProcedure
- Yet another procedure fitting "Func"
Procedure g(n)
ProcedureReturn n+1
EndProcedure
- - Test it
X=Random(100) Title$="With x="+Str(x) Body$="Compose(f(),g(), x) ="+Str(Compose(@f(),@g(),X)) MessageRequester(Title$,Body$)</lang>
Purity
<lang Purity> data compose = f => g => $f . $g </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>
Qi
Qi supports partial applications, but only when calling a function with one argument. <lang qi> (define compose
F G -> (/. X (F (G X))))
((compose (+ 1) (+ 2)) 3) \ (Outputs 6) \ </lang>
Alternatively, it can be done like this:
<lang qi> (define compose F G X -> (F (G X)))
(((compose (+ 1)) (+ 2)) 3) \ (Outputs 6) \ </lang>
R
<lang R>compose <- function(f,g) function(x) { f(g(x)) } r <- compose(sin, cos) print(r(.5))</lang>
Racket
<lang racket> (define (compose f g)
(lambda (x) (f (g x))))
</lang>
Also available as a compose1 builtin, and a more general compose where one function can produce multiple arguments that are sent the the next function in the chain. (Note however that this is rarely desired.)
REBOL
<lang REBOL>REBOL [ Title: "Functional Composition" Author: oofoe Date: 2009-12-06 URL: http://rosettacode.org/wiki/Functional_Composition ]
- "compose" means something else in REBOL, therefore I use a 'compose-functions name.
compose-functions: func [
{compose the given functions F and G} f [any-function!] g [any-function!]
] [
func [x] compose [(:f) (:g) x]
]</lang>
Functions "foo" and "bar" are used to prove that composition actually took place by attaching their signatures to the result.
<lang REBOL>foo: func [x] [reform ["foo:" x]] bar: func [x] [reform ["bar:" x]]
foo-bar: compose-functions :foo :bar print ["Composition of foo and bar:" mold foo-bar "test"]
sin-asin: compose-functions :sine :arcsine print [crlf "Composition of sine and arcsine:" sin-asin 0.5]</lang>
Output:
Composition of foo and bar: "foo: bar: test" Composition of sine and arcsine: 0.5
REXX
<lang rexx>compose: procedure; parse arg f,g,x; interpret 'return' f"(" g'(' x "))" exit /*control never gets here, but this was added just in case.*/</lang>
Ruby
This compose method gets passed two Method objects or Proc objects <lang ruby>def compose(f,g)
lambda {|x| f[g[x]]}
end s = compose(Math.method(:sin), Math.method(:cos)) p s[0.5] # => 0.769196354841008
- verify
p Math.sin(Math.cos(0.5)) # => 0.769196354841008</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))))
- or
(define ((compose f g) x) (f (g x))) </lang> Example: <lang scheme> (display ((compose sin asin) 0.5)) (newline)</lang> Output: <lang>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>
UNIX Shell
Each function takes its argument from standard input, and puts its result to standard output. Then the composition of f and g is a shell pipeline, c() { g | f; }
.
<lang bash>compose() { eval "$1() { $3 | $2; }" }
downvowel() { tr AEIOU aeiou; } upcase() { tr a-z A-Z; } compose c downvowel upcase echo 'Cozy lummox gives smart squid who asks for job pen.' | c
- => CoZY LuMMoX GiVeS SMaRT SQuiD WHo aSKS FoR JoB PeN.</lang>
es
With shell pipelines:
<lang es>fn compose f g { result @ {$g | $f} }
fn downvowel {tr AEIOU aeiou} fn upcase {tr a-z A-Z} fn-c = <={compose $fn-downvowel $fn-upcase} echo 'Cozy lummox gives smart squid who asks for job pen.' | c
- => CoZY LuMMoX GiVeS SMaRT SQuiD WHo aSKS FoR JoB PeN.</lang>
With function arguments:
<lang es>fn compose f g { result @ x {result <={$f <={$g $x}}} }
fn downvowel x {result `` {tr AEIOU aeiou <<< $x}} fn upcase x {result `` {tr a-z A-Z <<< $x}} fn-c = <={compose $fn-downvowel $fn-upcase} echo <={c 'Cozy lummox gives smart squid who asks for job pen.'}
- => CoZY LuMMoX GiVeS SMaRT SQuiD WHo aSKS FoR JoB PeN.</lang>
Unlambda
``s`ksk
Ursala
Functional composition is a built in operation expressible as f+g for functions f and g, hence hardly worth defining. However, it could be defined without using the operator like this. <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
VBScript
I'm not convinced that this is really a 'closure'. It looks to me more like a cute trick with Eval().
Implementation <lang vb> option explicit class closure
private composition
sub compose( f1, f2 ) composition = f2 & "(" & f1 & "(p1))" end sub
public default function apply( p1 ) apply = eval( composition ) end function
public property get formula formula = composition end property
end class </lang>
Invocation <lang vb> dim c set c = new closure
c.compose "ucase", "lcase" wscript.echo c.formula wscript.echo c("dog")
c.compose "log", "exp" wscript.echo c.formula wscript.echo c(12.3)
function inc( n ) inc = n + 1 end function
c.compose "inc", "inc" wscript.echo c.formula wscript.echo c(12.3)
function twice( n ) twice = n * 2 end function
c.compose "twice", "inc" wscript.echo c.formula wscript.echo c(12.3) </lang>
Output
lcase(ucase(p1)) dog exp(log(p1)) 12.3 inc(inc(p1)) 14.3 inc(twice(p1)) 25.6
- Programming Tasks
- Higher-order functions
- ActionScript
- Ada
- Aikido
- ALGOL 68
- Argile
- AutoHotkey
- BBC BASIC
- Bori
- Brat
- C
- C++
- C sharp
- Clojure
- CoffeeScript
- Common Lisp
- D
- Delphi
- Déjà Vu
- Dylan
- Ela
- E
- Erlang
- Euphoria/Omit
- F Sharp
- Factor
- Fantom
- Forth
- GAP
- Go
- Groovy
- Haskell
- Icon
- Unicon
- J
- Java
- JavaScript
- Joy
- K
- LFE
- LOLCODE
- Lua
- Mathematica
- Maxima
- Nemerle
- NewLISP
- Objective-C
- Objeck
- OCaml
- Octave
- Order
- Oz
- PARI/GP
- Pascal
- Perl
- Perl 6
- PHP
- PicoLisp
- PostScript
- Prolog
- PureBasic
- Purity
- Python
- Qi
- R
- Racket
- REBOL
- REXX
- Ruby
- Scala
- Scheme
- Slate
- Smalltalk
- Standard ML
- Tcl
- UNIX Shell
- Es
- Unlambda
- Ursala
- TI-83 BASIC/Omit
- TI-89 BASIC/Omit
- Fortran/Omit
- VBScript