Function composition

From Rosetta Code

Jump to: navigation, search
Task
Function composition
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.

Contents

[edit] ActionScript

ActionScript supports closures, making function composition very straightforward.

function compose(f:Function, g:Function):Function {
return function(x:Object) {return f(g(x));};
}
function test() {
trace(compose(Math.atan, Math.tan)(0.5));
}

[edit] Ada

The interface of a generic functions package. The package can be instantiated with any type that has value semantics. Functions are composed using the operation '*'. The same operation applied to an argument evaluates it there: f * x. Functions can be composed with pointers to Ada functions. (In Ada functions are not first-class):

generic
type Argument is private;
package Functions is
type Primitive_Operation is not null
access function (Value : Argument) return Argument;
type Func (<>) is private;
function "*" (Left : Func; Right : Argument) return Argument;
function "*" (Left : Func; Right : Primitive_Operation) return Func;
function "*" (Left, Right : Primitive_Operation) return Func;
function "*" (Left, Right : Func) return Func;
private
type Func is array (Positive range <>) of Primitive_Operation;
end Functions;

Here is an implementation;

package body Functions is
function "*" (Left : Func; Right : Argument) return Argument is
Result : Argument := Right;
begin
for I in reverse Left'Range loop
Result := Left (I) (Result);
end loop;
return Result;
end "*";
 
function "*" (Left, Right : Func) return Func is
begin
return Left & Right;
end "*";
 
function "*" (Left : Func; Right : Primitive_Operation) return Func is
begin
return Left & (1 => Right);
end "*";
 
function "*" (Left, Right : Primitive_Operation) return Func is
begin
return (Left, Right);
end "*";
end Functions;

The following is an example of use:

with Ada.Numerics.Elementary_Functions;  use Ada.Numerics.Elementary_Functions;
with Ada.Text_IO; use Ada.Text_IO;
with Functions;
 
procedure Test_Compose is
package Float_Functions is new Functions (Float);
use Float_Functions;
 
Sin_Arcsin : Func := Sin'Access * Arcsin'Access;
begin
Put_Line (Float'Image (Sin_Arcsin * 0.5));
end Test_Compose;

Sample output:

 5.00000E-01

[edit] 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
 
 

[edit] ALGOL 68

Translation of: Python

Works with: ELLA ALGOL 68 version Any (with appropriate job cards) - tested with release 1.8.8d.fc9.i386 Note: Returning PROC (REAL x)REAL: f1(f2(x)) from a function apparently violates standard ALGOL 68's scoping rules. ALGOL 68G warns about this during parsing, and then rejects during runtime.

MODE F = PROC(REAL)REAL; # ALGOL 68 is strong typed #
 
# As a procedure for real to real functions #
PROC compose = (F f, g)F: (REAL x)REAL: f(g(x));
 
OP (F,F)F O = compose; # or an OPerator that can be overloaded #
 
# Example use: #
F sin arc sin = compose(sin, arc sin);
print((sin arc sin(0.5), (sin O arc sin)(0.5), new line))

Output:

+.500000000000000e +0 +.500000000000000e +0

ALGOL 68 is a stack based language, and the following apparently does not violate it's scoping rules.

Works with: ALGOL 68 version Standard - Jan 1975 Boston SC allowed Partial Parametrization. Works with: ALGOL 68G version Any - tested with release mk15-0.8b.fc9.i386

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))

[edit] Argile

Only works for functions taking real and returning real (double precision, 64 bits) Works with: Argile version 1.0.0

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


[edit] AutoHotkey

contributed by Laszlo on the ahk forum

MsgBox % compose("sin","cos",1.5)
 
compose(f,g,x) { ; function composition
Return %f%(%g%(x))
}

[edit] C

Only works for functions taking a double and returning a double:

#include <stdlib.h>
 
/* generic interface for functors from double to double */
typedef struct double_to_double {
double (*fn)(struct double_to_double *, double);
} double_to_double;
 
#define CALL(f, x) f->fn(f, x)
 
 
/* functor returned by compose */
typedef struct compose_functor {
double (*fn)(struct compose_functor *, double);
double_to_double *f;
double_to_double *g;
} compose_functor;
/* function to be used in "fn" in preceding functor */
double compose_call(compose_functor *this, double x) {
return CALL(this->f, CALL(this->g, x));
}
/* returns functor that is the composition of functors
f & g. caller is responsible for deallocating memory */

double_to_double *compose(double_to_double *f,
double_to_double *g) {
compose_functor *result = malloc(sizeof(compose_functor));
result->fn = &compose_call;
result->f = f;
result->g = g;
return (double_to_double *)result;
}
 
 
 
#include <math.h>
 
/* we can make functors for sin and asin by using
the following as "fn" in a functor */

double sin_call(double_to_double *this, double x) {
return sin(x);
}
double asin_call(double_to_double *this, double x) {
return asin(x);
}
 
 
 
#include <stdio.h>
 
int main() {
double_to_double *my_sin = malloc(sizeof(double_to_double));
my_sin->fn = &sin_call;
double_to_double *my_asin = malloc(sizeof(double_to_double));
my_asin->fn = &asin_call;
 
double_to_double *sin_asin = compose(my_sin, my_asin);
 
printf("%f\n", CALL(sin_asin, 0.5)); /* prints "0.500000" */
 
free(sin_asin);
free(my_sin);
free(my_asin);
 
return 0;
}

[edit] C++

Note: this is already implemented as __gnu_cxx::compose1()

#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;
}

[edit] C#

using System;
class Program
{
static void Main(string[] args)
{
Func<int, int> outfunc = Composer<int, int, int>.Compose(functA, functB);
Console.WriteLine(outfunc(5)); //Prints 100
}
static int functA(int i) { return i * 10; }
static int functB(int i) { return i + 5; }
class Composer<A, B, C>
{
public static Func<C, A> Compose(Func<B, A> a, Func<C, B> b)
{
return delegate(C i) { return a(b(i)); };
}
}
}

[edit] Clojure

Function composition is built in to Clojure. Simply call the comp function.

A manual implementation could look like this:

(defn compose [f g]
(fn [x]
(f (g x))))
 
; Example
(def inc2 (compose inc inc))
(println (inc2 5)) ; prints 7

[edit] Common Lisp

(defun compose (f g) (lambda (x) (funcall f (funcall g x))))

Example use:

>(defun compose (f g) (lambda (x) (funcall f (funcall g x))))
COMPOSE
>(let ((sin-asin (compose #'sin #'asin))))
(funcall sin-asin 0.5))
0.5

[edit] D

D 2.0 version of compose function (template).

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)); };
}

Compose working both in D 1.0 and 2.0:

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;
}

[edit] Dylan

define method compose(f,g)
method(x) f(g(x)) end
end;

[edit] E

def compose(f, g) {
return fn x { return f(g(x)) }
}

[edit] 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).

Using them:

1> (fn:compose(fun math:sin/1, fun math:asin/1))(0.5).
0.5
2> Sin_asin_plus1 = fn:multicompose([fun math:sin/1, fun math:asin/1, fun(X) -> X + 1 end]).
#Fun<tests.0.59446746>
82> Sin_asin_plus1(0.5).
1.5

[edit] F#

The most-used composition operator in F# is >>. It implements forward composition, i.e. f >> g is a function which calls f first and then calls g on the result.

The reverse composition operator <<, on the other hand, exactly fulfills the requirements of the compose function described in this task.

We can implement composition manually like this (F# Interactive session):

> let compose f g x = f (g x);;
 
val compose : ('a -> 'b) -> ('c -> 'a) -> 'c -> 'b

Usage:

> let sin_asin = compose sin asin;;
 
val sin_asin : (float -> float)
 
> sin_asin 0.5;;
val it : float = 0.5

[edit] 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.

( scratchpad ) [ 2 * ] [ 1 + ] compose .
[ 2 * 1 + ]
( scratchpad ) 4 [ 2 * ] [ 1 + ] compose call .
9

[edit] Forth

: compose ( xt1 xt2 -- xt3 )
>r >r :noname
r> compile,
r> compile,
postpone ;
;
 
' 2* ' 1+ compose ( xt )
3 swap execute . \ 7

[edit] Go

Go doesn't have generics; this particular compose function just composes float functions

func compose(f, g func(float64) float64) func(float64) float64 {
return func(x float64) float64 {
return f(g(x))
}
}

Example use:

package main
import "math"
import "fmt"
 
func compose(f, g func(float64) float64) func(float64) float64 {
return func(x float64) float64 {
return f(g(x))
}
}
 
func main() {
sin_asin := compose(math.Sin, math.Asin)
fmt.Println(sin_asin(0.5))
}

[edit] Groovy

Solution:

def compose = { f, g -> { x -> f(g(x)) } }

Test program:

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)

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

[edit] Haskell

This is already defined as the . (dot) operator in Haskell.

compose f g x = f (g x)

Example use:

Prelude> let compose f g x = f (g x)
Prelude> let sin_asin = compose sin asin
Prelude> sin_asin 0.5
0.5

[edit] 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)

[edit] Icon

The solution below can be adapted to work in Icon by reverting to the old syntax for invoking co-expressions.

   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

See Icon and Unicon Introduction:Minor Differences for more information

[edit] 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

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

[edit] J

Solution:

compose =: @

Example:

f compose g

Of course, given that @ is only one character long and is a built-in primitive, there is no need for the cover function compose. And @ is not the only composition primitive; composition is a very important concept in J. For more details, see the talk page.

[edit] 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"
}
}

[edit] 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

[edit] Joy

Composition is the default operation in Joy. The composition of two functions is the concatenation of those functions, in the order in which they are to be applied.

g f

[edit] Lua

function compose(f, g) return function(...) return f(g(...)) end end

[edit] Mathematica

Built-in function that takes any amount of function-arguments:

Composition[f, g][x]
Composition[f, g, h, i][x]

gives back:

f[g[x]]
f[g[h[i[x]]]]

Custom function:

compose[f_, g_][x_] := f[g[x]]
compose[Sin, Cos][r]

gives back:

Sin[Cos[r]]

Composition can be done in more than 1 way:

Composition[f,g,h][x]
f@g@h@x
x//h//g//f

all give back:

f[g[h[x]]]

The built-in function has a couple of automatic simplifications:

Composition[f, Identity, g]
Composition[f, InverseFunction[f], h][x]

becomes:

f[g[x]]
h[x]

[edit] 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.

#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;
}

[edit] Objeck

 
bundle Default {
class Test {
@f : static : (Int) ~ Int;
@g : static : (Int) ~ Int;
 
function : Main(args : String[]) ~ Nil {
compose := Composer(F(Int) ~ Int, G(Int) ~ Int);
compose(13)->PrintLine();
}
 
function : F(a : Int) ~ Int {
return a + 14;
}
 
function : G(a : Int) ~ Int {
return a + 15;
}
 
function : Compose(x : Int) ~ Int {
return @f(@g(x));
}
 
function : Composer(f : (Int) ~ Int, g : (Int) ~ Int) ~ (Int) ~ Int {
@f := f;
@g := g;
return Compose(Int) ~ Int;
}
}
}
 

prints: 42

[edit] OCaml

let compose f g x = f (g x)

Example use:

# let compose f g x = f (g x);;
val compose : ('a -> 'b) -> ('c -> 'a) -> 'c -> 'b = <fun>
# let sin_asin = compose sin asin;;
val sin_asin : float -> float = <fun>
# sin_asin 0.5;;
- : float = 0.5

[edit] Octave

function r = compose(f, g)
r = @(x) f(g(x));
endfunction
 
r = compose(@exp, @sin);
r(pi/3)

[edit] Oz

declare
fun {Compose F G}
fun {$ X}
{F {G X}}
end
end
 
SinAsin = {Compose Float.sin Float.asin}
in
{Show {SinAsin 0.5}}

[edit] Perl

sub compose
{my ($f, $g) = @_;
return sub {$f->($g->(@_))};}
 
use Math::Trig;
print compose(sub {sin $_[0]}, \&asin)->(0.5), "\n";

[edit] Perl 6

Works with: Rakudo version #23 "Lisbon"

sub infix:<> (&f, &g --> Block) {
sub (*@args) { f g |@args };
}

Example of use:

sub triple($n) { 3 * $n }
my $f = &triple{ $^x + 2 };
say $f(5); # Prints "21".

[edit] PicoLisp

(de compose (F G)
(curry (F G) (X)
(F (G X)) ) )
(def 'a (compose inc dec))
(def 'b (compose 'inc 'dec))
(def 'c (compose '((A) (inc A)) '((B) (dec B))))
: (a 7)
-> 7
 
: (b 7)
-> 7
 
: (c 7)
-> 7

[edit] 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$)

[edit] Python

compose = lambda f, g: lambda x: f( g(x) )

Example use:

>>> compose = lambda f, g: lambda x: f( g(x) )
>>> from math import sin, asin
>>> sin_asin = compose(sin, asin)
>>> sin_asin(0.5)
0.5
>>>

[edit] R

compose <- function(f,g) function(x) { f(g(x)) }
r <- compose(sin, cos)
print(r(.5))

[edit] REBOL

rebol [
Title: "Functional Composition"
Author: oofoe
Date: 2009-12-06
URL: http://rosettacode.org/wiki/Functional_Composition
]

 
; "compose" means something else in REBOL, so I "fashion" an alternative.
 
fashion: func [f1 f2][
do compose/deep [func [x][(:f1) (:f2) x]]]
 
; Functions "foo" and "bar" are used to prove that composition
; actually took place by attaching their signatures to the result.
 
foo: func [x][reform ["foo:" x]]
bar: func [x][reform ["bar:" x]]
 
foo-bar: fashion :foo :bar
print ["Composition of foo and bar:" mold foo-bar "test"]
 
sin-asin: fashion :sine :arcsine
print [crlf "Composition of sine and arcsine:" sin-asin 0.5]

Output:

Composition of foo and bar: "foo: bar: test"

Composition of sine and arcsine: 0.5

[edit] Ruby

This compose method gets passed two Method objects

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

With this method, you pass two symbols

include Math
def compose(f,g)
lambda {|x| send(f, send(g, x))}
end
s = compose(:sin, :cos)
s.call(0.5) # => 0.769196354841008

[edit] Scala

def compose[A](f: A => A, g: A => A) = { x: A => f(g(x)) }
 
def add1(x: Int) = x+1
val add2 = compose(add1, add1)

We can achieve a more natural style by creating a container class for composable functions, which provides the compose method 'o':

class Composable[A](f: A => A) {
def o (g: A => A) = compose(f, g)
}
 
implicit def toComposable[A](f: A => A) = new Composable(f)
 
val add3 = (add1 _) o add2
> (add2 o add3)(37)
res0: Int = 42

[edit] Scheme

(define (compose f g) (lambda (x) (f (g x))))
 
;; or:
 
(define ((compose f g) x) (f (g x)))
 

Example:

 
(display ((compose sin asin) 0.5))
(newline)

Output:

0.5

[edit] Slate

Function (method) composition is standard:

[| :x | x + 1] ** [| :x | x squared] applyTo: {3}

[edit] 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.

[edit] Standard ML

This is already defined as the o operator in Standard ML.

fun compose (f, g) x = f (g x)

Example use:

- fun compose (f, g) x = f (g x);
val compose = fn : ('a -> 'b) * ('c -> 'a) -> 'c -> 'b
- val sin_asin = compose (Math.sin, Math.asin);
val sin_asin = fn : real -> real
- sin_asin 0.5;
val it = 0.5 : real

[edit] Tcl

Works with: Tcl version 8.5
This creates a compose procedure that returns an anonymous function term that should be expanded as part of application to its argument.

package require Tcl 8.5
namespace path {::tcl::mathfunc}
 
proc compose {f g} {
list apply [list {f g x} {{*}$f [{*}$g $x]}] $f $g]
}
 
set sin_asin [compose sin asin]
{*}$sin_asin 0.5 ;# ==> 0.5
{*}[compose abs int] -3.14 ;# ==> 3

[edit] Unlambda

``s`ksk

[edit] Ursala

Functional composition is a built in operation expressible as f+g for functions f and g, hence hardly worth defining. However, it could be defined without using the operator like this.

compose("f","g") "x" = "f" "g" "x"

test program:

#import nat
#cast %n
 
test = compose(successor,double) 3

output:

7

[edit] VBScript

I'm not convinced that this is really a 'closure'. It looks to me more like a cute trick with Eval().

Implementation

 
option explicit
class closure
 
private composition
 
sub compose( f1, f2 )
composition = f2 & "(" & f1 & "(p1))"
end sub
 
public default function apply( p1 )
apply = eval( composition )
end function
 
public property get formula
formula = composition
end property
 
end class
 

Invocation

 
dim c
set c = new closure
 
c.compose "ucase", "lcase"
wscript.echo c.formula
wscript.echo c("dog")
 
c.compose "log", "exp"
wscript.echo c.formula
wscript.echo c(12.3)
 
function inc( n )
inc = n + 1
end function
 
c.compose "inc", "inc"
wscript.echo c.formula
wscript.echo c(12.3)
 
function twice( n )
twice = n * 2
end function
 
c.compose "twice", "inc"
wscript.echo c.formula
wscript.echo c(12.3)
 

Output

lcase(ucase(p1))
dog
exp(log(p1))
12.3
inc(inc(p1))
14.3
inc(twice(p1))
25.6
Personal tools
Support