User:Coderjoe/Sandbox2: Difference between revisions

From Rosetta Code
Content added Content deleted
No edit summary
No edit summary
Line 1: Line 1:
=={{header|ActionScript}}==
=={{header|Groovy}}==
Solution:
{{trans|JavaScript}}
<lang ActionScript>function compose(f:Function, g:Function):Function {
<lang groovy>def compose = { f, g -> { x -> f(g(x)) } }</lang>
return function(x:Number) {return f(g(x));};
}
var functions:Array = [Math.cos, Math.tan, function(x:Number){return x*x;}];
var inverse:Array = [Math.acos, Math.atan, function(x:Number){return Math.sqrt(x);}];


Test program:
function test() {
<lang groovy>def cube = { it * it * it }
for (var i:uint = 0; i < functions.length; i++) {
def cubeRoot = { it ** (1/3) }
trace(compose(functions[i], inverse[i])(0.5));
}
}</lang>


funcList = [ Math.&sin, Math.&cos, cube ]
=={{header|Ada}}==
inverseList = [ Math.&asin, Math.&acos, cubeRoot ]
<lang Ada>
with Ada.Text_IO;
with Ada.Numerics.Generic_Elementary_Functions;
procedure Program is
generic
type Number_Type is private;
with function F(X : Number_Type) return Number_Type;
with function G(X : Number_Type) return Number_Type;
function Compose(X : Number_Type) return Number_Type;
function Compose(X : Number_Type) return Number_Type is begin return F(G(X)); end;
type Function_Type is access function(X : Float) return Float;
function sqr(X : Float) return Float is begin return X * X; end;
package Math is new Ada.Numerics.Generic_Elementary_Functions(Float);
type Function_List is array(Natural range <>) of Function_Type;
functions : Function_List := (Math.sin'Access, Math.cos'Access, Program.sqr'Access);
inverts : Function_List of Function_Type := (Math.arcsin'Access, Math.arccos'Access, Math.sqrt'Access);
begin
for i in functions'Range loop
declare
function C is new Compose(Float, functions(i).all, inverts(i).all);
begin
Ada.Text_IO.Put_Line(Float'Image(C(0.5)));
end;
end loop;
end Program;


println [funcList, inverseList].transpose().collect { compose(it[0],it[1]) }.collect{ it(0.5) }
</lang>
println [inverseList, funcList].transpose().collect { compose(it[0],it[1]) }.collect{ it(0.5) }</lang>


Output:
=={{header|Aikido}}==
<pre>[0.5, 0.4999999999999999, 0.5000000000346574]
{{trans|Javascript}}
[0.5, 0.4999999999999999, 0.5000000000346574]</pre>
<lang aikido>
import math


=={{header|Haskell}}==
function compose (f, g) {
<lang haskell>Prelude> let cube x = x ^ 3
return function (x) { return f(g(x)) }
Prelude> let croot x = x ** (1/3)
}
Prelude> let compose f g = \x -> f (g x) -- this is already implemented in Haskell as the "." operator
Prelude> -- we could have written "let compose f g x = f (g x)" but we show this for clarity
Prelude> let funclist = [sin, cos, cube]
Prelude> let funclisti = [asin, acos, croot]
Prelude> zipWith (\f inversef -> (compose inversef f) 0.5) funclist funclisti
[0.5,0.4999999999999999,0.5]</lang>


=={{header|Icon}} and {{header|Unicon}}==
var fn = [Math.sin, Math.cos, function(x) { return x*x*x }]
The Unicon solution can be modified to work in Icon. See [[Function_composition#Icon_and_Unicon]].
var inv = [Math.asin, Math.acos, function(x) { return Math.pow(x, 1.0/3) }]
<lang Unicon>link compose
procedure main(arglist)


fun := [sin,cos,cube]
for (var i=0; i<3; i++) {
var f = compose(inv[i], fn[i])
inv := [asin,acos,cuberoot]
println(f(0.5)) // 0.5
x := 0.5
every i := 1 to *inv do
}
write("f(",x,") := ", compose(inv[i],fun[i])(x))
end


procedure cube(x)
</lang>
return x*x*x
end


procedure cuberoot(x)
=={{header|ALGOL 68}}==
return x ^ (1./3)
{{trans|Python}}
end</lang>
Please refer to See [[Function_composition#Icon_and_Unicon]] for 'compose'.


Sample Output:
{{works with|ALGOL 68|Standard - no extensions to language used}}
<pre>f(0.5) := 0.5
f(0.5) := 0.4999999999999999
f(0.5) := 0.5</pre>


=={{header|J}}==
{{works with|ALGOL 68G|Any - tested with release mk15-0.8b.fc9.i386}}
J has some subtleties which are not addressed in this specification (J functions have grammatical character and their [[wp:Gerund|gerundial form]] may be placed in data structures where the spec sort of implies that there be no such distinction).


However, here are the basics which were requested:
{{works with|ELLA ALGOL 68|Any (with appropriate job cards) - tested with release 1.8.8d.fc9.i386 using non-standard compose}}
<lang j> sin=: 1&o.
cos=: 2&o.
cube=: ^&3
square=: *:
unqo=: `:6
unqcol=: `:0
quot=: 1 :'{.u`'''''
A=: sin`cos`cube`square
B=: monad def'y unqo inv quot'"0 A
BA=. A dyad def'x unqo@(y unqo) quot'"0 B</lang>


<lang> A unqcol 0.5
Note: Returning <code>PROC (REAL x)REAL: f1(f2(x))</code> from a function apparently
0.479426 0.877583 0.125 0.25
violates standard '''ALGOL 68''''s scoping rules. [[ALGOL 68G]] warns about this during
BA unqcol 0.5
parsing, and then - if run out of scope - rejects during runtime.
0.5 0.5 0.5 0.5</lang>
<lang algol68>MODE F = PROC (REAL)REAL;
OP ** = (REAL x, power)REAL: exp(ln(x)*power);


=={{header|Java}}==
# Add a user defined function and its inverse #
Java doesn't technically have first-class functions. Java can simulate first-class functions to a certain extent, with anonymous classes and generic function interface.
PROC cube = (REAL x)REAL: x * x * x;
PROC cube root = (REAL x)REAL: x ** (1/3);


<lang java>
# First class functions allow run-time creation of functions from functions #
public static Function<Double, Double> compose(
# return function compose(f,g)(x) == f(g(x)) #
final Function<Double, Double> f, final Function<Double, Double> g) {
PROC non standard compose = (F f1, f2)F: (REAL x)REAL: f1(f2(x)); # eg ELLA ALGOL 68RS #
return new Function<Double, Double>() {
PROC compose = (F f, g)F: ((F f2, g2, REAL x)REAL: f2(g2(x)))(f, g, );
@Override public Double apply(Double x) {
return f.apply(g.apply(x));
}
};
}


@SuppressWarnings("unchecked") public static void main(String[] args) {
# Or the classic "o" functional operator #
ArrayList<Function<Double, Double>> functions = Lists.newArrayList(
PRIO O = 5;
new Function<Double, Double>() {
OP (F,F)F O = compose;
@Override public Double apply(Double x) {
return Math.cos(x);
}
}, new Function<Double, Double>() {
@Override public Double apply(Double x) {
return Math.tan(x);
}
}, new Function<Double, Double>() {
@Override public Double apply(Double x) {
return x * x;
}
});
ArrayList<Function<Double, Double>> inverse = Lists.newArrayList(
new Function<Double, Double>() {
@Override public Double apply(Double x) {
return Math.acos(x);
}
}, new Function<Double, Double>() {
@Override public Double apply(Double x) {
return Math.atan(x);
}
}, new Function<Double, Double>() {
@Override public Double apply(Double x) {
return Math.sqrt(x);
}
});
for (int i = 0; i < functions.size(); i++) {
System.out.println(compose(functions.get(i), inverse.get(i)).apply(0.5));
}
}
</lang>
=={{header|JavaScript}}==
assuming the print function is provided by the environment, like a stand-alone shell. In browsers, use alert(), document.write() or similar


<lang javascript>var compose = function (f, g) {
# first class functions should be able to be members of collection types #
return function (x) {
[]F func list = (sin, cos, cube);
[]F arc func list = (arc sin, arc cos, cube root);
return f(g(x));
};
};


var fn = [Math.sin, Math.cos, function (x) { return Math.pow(x, 3); }];
# Apply functions from lists as easily as integers #
var inv = [Math.asin, Math.acos, function (x) { return Math.pow(x, 1/3); }];
FOR index TO UPB func list DO
STRUCT(F f, inverse f) this := (func list[index], arc func list[index]);
print(((inverse f OF this O f OF this)(.5), new line))
OD</lang>
Output:
<pre>+.500000000000000e +0
+.500000000000000e +0
+.500000000000000e +0</pre>


(function () {
=={{header|AutoHotkey}}==
for (var i = 0; i < 3; i++) {
AutoHotkey core does not support new function definitions at run time.<br>
var f = compose(inv[i], fn[i]);
However, functions can be called by name, so mapping functions is possible:
print(f(0.5)); // 0.5
<lang AutoHotkey>forward := "sin,cube,cos"
}
inverse := "Asin,cuberoot,Acos"
})();
StringSplit, forward, forward, `, ; store array length in forward0
StringSplit, inverse, inverse, `, ; array contents are in inverse1, inverse2...
Loop, % forward0
MsgBox % map(compose(forward%A_Index%, inverse%A_Index%), 0.500)
Return


</lang>
compose(f, g){
Return map(0, 0, f, g)
}


=={{header|Lua}}==
map(ab = 0, x = 0 , a = 0, b = 0)
<lang lua> function compose(f,g) return function(...) return f(g(...)) end end
{
Static
If (a And b)
Return a . "`n" . b
If ab
{
StringSplit, ab, ab, `n
Return %ab1%(%ab2%(x))
}
}


fn = {math.sin, math.cos, function(x) return x^3 end}
cube(x){
inv = {math.asin, math.acos, function(x) return x^(1/3) end}
Return x ** 3
}


for i, v in ipairs(fn)
cuberoot(x){
Return x ** (1 / 3)
local f = compose(v, inv[i])
print(f(0.5)) --> 0.5
}</lang>
end</lang>


=={{header|C}}==
=={{header|Mathematica}}==
The built-in function Composition can do composition, a custom function that does the same would be compose[f_,g_]:=f[g[#]]&. However the latter only works with 2 arguments, Composition works with any number of arguments.
Since one can't create new functions dynamically within a C program, C doesn't have first class functions. But you can pass references to functions as parameters and return values and you can have a list of function references, so I guess you can say C has second class functions.
<lang Mathematica>funcs = {Sin, Cos, #^3 &};
funcsi = {ArcSin, ArcCos, #^(1/3) &};
compositefuncs = Composition @@@ Transpose[{funcs, funcsi}];
Table[i[0.666], {i, compositefuncs}]</lang>
gives back:
<lang Mathematica>{0.666, 0.666, 0.666}</lang>
Note that I implemented cube and cube-root as pure functions. This shows that Mathematica is fully able to handle functions as variables, functions can return functions, and functions can be given as an argument. 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>


=={{header|Nemerle}}==
Here goes.
{{trans|Python}}
<lang Nemerle>using System;
using System.Console;
using System.Math;
using Nemerle.Collections.NCollectionsExtensions;


module FirstClassFunc
<lang c>#include <stdlib.h>
#include <stdio.h>
#include <math.h>
/* declare a typedef for a function pointer */
typedef double (*Class2Func)(double);
/*A couple of functions with the above prototype */
double functionA( double v)
{
{
Main() : void
return v*v*v;
{
}
def cube = fun (x) {x * x * x};
double functionB(double v)
def croot = fun (x) {Pow(x, 1.0/3.0)};
{
def compose = fun(f, g) {fun (x) {f(g(x))}};
return exp(log(v)/3);
def funcs = [Sin, Cos, cube];
}
def ifuncs = [Asin, Acos, croot];
WriteLine($[compose(f, g)(0.5) | (f, g) in ZipLazy(funcs, ifuncs)]);
/* A function taking a function as an argument */
}
double Function1( Class2Func f2, double val )
{
return f2(val);
}
/*A function returning a function */
Class2Func WhichFunc( int idx)
{
return (idx < 4) ? &functionA : &functionB;
}
/* A list of functions */
Class2Func funcListA[] = {&functionA, &sin, &cos, &tan };
Class2Func funcListB[] = {&functionB, &asin, &acos, &atan };
/* Composing Functions */
double InvokeComposed( Class2Func f1, Class2Func f2, double val )
{
return f1(f2(val));
}
typedef struct sComposition {
Class2Func f1;
Class2Func f2;
} *Composition;
Composition Compose( Class2Func f1, Class2Func f2)
{
Composition comp = malloc(sizeof(struct sComposition));
comp->f1 = f1;
comp->f2 = f2;
return comp;
}
double CallComposed( Composition comp, double val )
{
return comp->f1( comp->f2(val) );
}
/** * * * * * * * * * * * * * * * * * * * * * * * * * * */
int main(int argc, char *argv[])
{
int ix;
Composition c;
printf("Function1(functionA, 3.0) = %f\n", Function1(WhichFunc(0), 3.0));
for (ix=0; ix<4; ix++) {
c = Compose(funcListA[ix], funcListB[ix]);
printf("Compostion %d(0.9) = %f\n", ix, CallComposed(c, 0.9));
}
return 0;
}</lang>
}</lang>
===Non-portable function body duplication===
Following code generates true functions at run time. Extremely unportable, and should be considered harmful in general, but it's one (again, harmful) way for the truly desperate (or perhaps for people supporting only one platform -- and note that some other languages only work on one platform).
<lang C>#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>


=={{header|newLISP}}==
typedef double (*f_dbl)(double);
<lang newLISP>> (define (compose f g) (expand (lambda (x) (f (g x))) 'f 'g))
#define TAGF (f_dbl)0xdeadbeef
(lambda (f g) (expand (lambda (x) (f (g x))) 'f 'g))
#define TAGG (f_dbl)0xbaddecaf
> (define (cube x) (pow x 3))
(lambda (x) (pow x 3))
> (define (cube-root x) (pow x (div 1 3)))
(lambda (x) (pow x (div 1 3)))
> (define functions '(sin cos cube))
(sin cos cube)
> (define inverses '(asin acos cube-root))
(asin acos cube-root)
> (map (fn (f g) ((compose f g) 0.5)) functions inverses)
(0.5 0.5 0.5)
</lang>


=={{header|OCaml}}==
double dummy(double x)
<lang ocaml># let cube x = x ** 3. ;;
{
val cube : float -> float = <fun>
f_dbl f = TAGF;
f_dbl g = TAGG;
return f(g(x));
}


# let croot x = x ** (1. /. 3.) ;;
f_dbl composite(f_dbl f, f_dbl g)
val croot : float -> float = <fun>
{
size_t len = (void*)composite - (void*)dummy;
f_dbl ret = malloc(len);
char *ptr;
memcpy(ret, dummy, len);
for (ptr = (char*)ret; ptr < (char*)ret + len - sizeof(f_dbl); ptr++) {
if (*(f_dbl*)ptr == TAGF) *(f_dbl*)ptr = f;
else if (*(f_dbl*)ptr == TAGG) *(f_dbl*)ptr = g;
}
return ret;
}


# let compose f g = fun x -> f (g x) ;; (* we could have written "let compose f g x = f (g x)" but we show this for clarity *)
double cube(double x)
val compose : ('a -> 'b) -> ('c -> 'a) -> 'c -> 'b = <fun>
{
return x * x * x;
}


# let funclist = [sin; cos; cube] ;;
/* uncomment next line if your math.h doesn't have cbrt() */
val funclist : (float -> float) list = [<fun>; <fun>; <fun>]
/* double cbrt(double x) { return pow(x, 1/3.); } */


# let funclisti = [asin; acos; croot] ;;
int main()
val funclisti : (float -> float) list = [<fun>; <fun>; <fun>]
{
int i;
double x;


# List.map2 (fun f inversef -> (compose inversef f) 0.5) funclist funclisti ;;
f_dbl A[3] = { cube, exp, sin };
- : float list = [0.5; 0.499999999999999889; 0.5]</lang>
f_dbl B[3] = { cbrt, log, asin}; /* not sure about availablity of cbrt() */
f_dbl C[3];


=={{header|Octave}}==
for (i = 0; i < 3; i++)
<lang octave>function r = cube(x)
C[i] = composite(A[i], B[i]);
r = x.^3;
endfunction


function r = croot(x)
for (i = 0; i < 3; i++) {
for (x = .2; x <= 1; x += .2)
r = x.^(1/3);
endfunction
printf("C%d(%g) = %g\n", i, x, C[i](x));
printf("\n");
}
return 0;
}</lang>(Boring) output<lang>C0(0.2) = 0.2
C0(0.4) = 0.4
C0(0.6) = 0.6
C0(0.8) = 0.8
C0(1) = 1


compose = @(f,g) @(x) f(g(x));
C1(0.2) = 0.2
C1(0.4) = 0.4
C1(0.6) = 0.6
C1(0.8) = 0.8
C1(1) = 1


f1 = {@sin, @cos, @cube};
C2(0.2) = 0.2
f2 = {@asin, @acos, @croot};
C2(0.4) = 0.4
C2(0.6) = 0.6
C2(0.8) = 0.8
C2(1) = 1</lang>


for i = 1:3
=={{header|C sharp|C#}}==
disp(compose(f1{i}, f2{i})(.5))
{{works with|C sharp|4.0}}
endfor</lang>


<lang csharp>using System;
using System.Linq;


=={{header|Oz}}==
class Program
To be executed in the REPL.
{
static void Main(string[] args)
{
Func<double, double> cube = x => Math.Pow(x, 3);
Func<double, double> croot = x => Math.Pow(x, (double) 1/3);


<lang oz>declare
var funclist = new[] {Math.Sin, Math.Cos, cube};
var funclisti = new[] {Math.Asin, Math.Acos, croot};
var composed = funclist.Zip(funclisti, (f, s) =>
{
Func<double, double> compose = x => f(s(x));
return compose;
});


fun {Compose F G}
foreach (var compose in composed)
fun {$ X}
Console.WriteLine(compose(0.5));
}
{F {G X}}
end
}
end
</lang>


fun {Cube X} X*X*X end
=={{header|C++}}==
This uses many C++0x niceties so make sure you put your compiler in the correct mode.


fun {CubeRoot X} {Number.pow X 1.0/3.0} end
<lang cpp>
#include <tr1/functional>
#include <vector>
#include <iostream>
#include <cmath>


in
using std::vector;
using std::cout;
using std::endl;
using std::tr1::function;


for
vector<double(*)(double)> A = {sin, cos, tan, [](double x) { return x*x*x; } };
F in [Float.sin Float.cos Cube]
vector<double(*)(double)> B = {asin, acos, atan, [](double x) { return exp(log(x)/3); } };
I in [Float.asin Float.acos CubeRoot]
do
{Show {{Compose I F} 0.5}}
end
</lang>


=={{header|PARI/GP}}==
template <typename A, typename B, typename... Params>
{{works with|PARI/GP|2.4.2 and above}}
function<A(Params...)> compose(A(*f)(B), B(*g)(Params...)){
<lang parigp>compose(f,g)={
return [=](Params... args){ return f(g(args...)); };
x -> f(g(x))
}
};


fcf()={
#define PRINT(x) cout << #x ": " << (x) << endl;
my(A,B);
int main() {
A=[x->sin(x), x->cos(x), x->x^2];
double num = 1 / 3.14159;
B=[x->asin(x), x->acos(x), x->sqrt(x)];
for(i=1,#A,
PRINT(num);
PRINT(compose(B[0], A[0])(num));
print(compose(A[i],B[i])(.5))
)
PRINT(compose(B[1], A[1])(num));
};</lang>
PRINT(compose(B[2], A[2])(num));
Usage note: In Pari/GP 2.4.3 the vectors can be written as
PRINT(compose(B[3], A[3])(num));
<lang parigp> A=[sin, cos, x->x^2];
B=[asin, acos, x->sqrt(x)];</lang>


=={{header|Perl}}==
auto identity = compose(log10, pow);
<lang perl>use Math::Complex ':trig';
PRINT(identity(10, num));

sub compose {
my ($f, $g) = @_;
sub {
$f -> ($g -> (@_));
};
}
}
</lang>


my $cube = sub { $_[0] ** (3) };
=={{header|Clojure}}==
my $croot = sub { $_[0] ** (1/3) };
<lang clojure>
(use 'clojure.contrib.math)
(let [fns [#(Math/sin %) #(Math/cos %) (fn [x] (* x x x))]
inv [#(Math/asin %) #(Math/acos %) #(expt % 1/3)]]
(map #(% 0.5) (map #(comp %1 %2) fns inv)))
</lang>
Output:
<pre>(0.5 0.4999999999999999 0.5000000000000001)</pre>


my @flist1 = ( \&Math::Complex::sin, \&Math::Complex::cos, $cube );
=={{header|CoffeeScript}}==
my @flist2 = ( \&asin, \&acos, $croot );
{{trans|JavaScript}}
<lang coffeescript>compose = (f, g) ->
(x) ->
f g x


print join "\n", map {
fn = [Math.sin, Math.cos, (x) -> Math.pow(x, 3) ]
compose($flist1[$_], $flist2[$_]) -> (0.5)
inv = [Math.asin, Math.acos, (x) -> Math.pow(x, 1/3) ]
} 0..2;</lang>


=={{header|Perl 6}}==
do ->
{{works with|Rakudo|2011.06}}
for i in [0..2]
f = compose inv[i], fn[i]
console.log f 0.5 # 0.5</lang>


<lang perl6>sub compose (&g, &f) { return { g f $^x } }
=={{header|Common Lisp}}==
<lang lisp>(defun compose (f g) (lambda (x) (funcall f (funcall g x))))
(defun cube (x) (expt x 3))
(defun cube-root (x) (expt x (/ 3)))


(loop with value = 0.5
my $x = *.sin;
my $xi = *.asin;
for function in (list #'sin #'cos #'cube )
my $y = *.cos;
for inverse in (list #'asin #'acos #'cube-root)
my $yi = *.acos;
for composed = (compose inverse function)
my $z = * ** 3;
do (format t "~&(~A ∘ ~A)(~A) = ~A~%"
my $zi = * ** (1/3);
inverse
function
my @functions = $x, $y, $z;
value
my @inverses = $xi, $yi, $zi;
(funcall composed value)))</lang>
for @functions Z @inverses { say compose($^g, $^f)(.5) }</lang>
Output:
<pre>0.5
0.5
0.5</pre>


=={{header|PicoLisp}}==
<lang PicoLisp>(load "@lib/math.l")

(de compose (F G)
(curry (F G) (X)
(F (G X)) ) )

(de cube (X)
(pow X 3.0) )

(de cubeRoot (X)
(pow X 0.3333333) )

(mapc
'((Fun Inv)
(prinl (format ((compose Inv Fun) 0.5) *Scl)) )
'(sin cos cube)
'(asin acos cubeRoot) )</lang>
Output:
Output:
<pre>0.500001
0.499999
0.500000</pre>


=={{header|Prolog}}==
<lang lisp>(#<FUNCTION ASIN> ∘ #<FUNCTION SIN>)(0.5) = 0.5
Works with SWI-Prolog and module lambda, written by <b>Ulrich Neumerkel</b> found here: http://www.complang.tuwien.ac.at/ulrich/Prolog-inedit/lambda.pl
(#<FUNCTION ACOS> ∘ #<FUNCTION COS>)(0.5) = 0.5
(#<FUNCTION CUBE-ROOT> ∘ #<FUNCTION CUBE>)(0.5) = 0.5</lang>


<lang Prolog>:- use_module(library(lambda)).
=={{header|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(F,G, FG) :-
Compose working both in D 1.0 and 2.0:
FG = \X^Z^(call(G,X,Y), call(F,Y,Z)).
<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)); }
}


cube(X, Y) :-
Wrapper* hold = new Wrapper;
hold.fcp = f;
Y is X ** 3.
hold.gcp = g;
return &hold.foobar;
}</lang>


cube_root(X, Y) :-
Example:
Y is X ** (1/3).


first_class :-
<lang D>import std.stdio, std.math, std.range;
L = [sin, cos, cube],
IL = [asin, acos, cube_root],


% we create the composed functions
T delegate(S) compose(T, U, S)(T delegate(U) f, U delegate(S) g) {
maplist(compose, L, IL, Lst),
return (S s){ return f(g(s)); };
}


% we call the functions
void main() {
maplist(call, Lst, [0.5,0.5,0.5], R),
// warper need as not all built-in real functions
// have same signature, eg pure/nothrow
auto sin = (real x){ return std.math.sin(x); };
auto asin = (real x){ return std.math.asin(x); };
auto cos = (real x){ return std.math.cos(x); };
auto acos = (real x){ return std.math.acos(x); };
auto cube = (real x){ return x ^^ 3; };
auto cbrt = (real x){ return std.math.cbrt(x); };


% we display the results
auto fun = [sin, cos, cube];
maplist(writeln, R).
auto inv = [asin, acos, cbrt];
</lang>
Output :
<pre> ?- first_class.
0.5
0.4999999999999999
0.5000000000000001
true.
</pre>


=={{header|Python}}==
foreach (f2; zip(fun, inv))

writefln("%6.3f", compose(f2[0], f2[1])(0.5));
<lang python>>>> # Some built in functions and their inverses
}</lang>
>>> from math import sin, cos, acos, asin
Using the compose() of the std lib, D v2:
>>> # Add a user defined function and its inverse
<lang d>import std.stdio, std.math, std.typetuple, std.functional;
>>> cube = lambda x: x * x * x
>>> croot = lambda x: x ** (1/3.0)
>>> # First class functions allow run-time creation of functions from functions
>>> # return function compose(f,g)(x) == f(g(x))
>>> compose = lambda f1, f2: ( lambda x: f1(f2(x)) )
>>> # first class functions should be able to be members of collection types
>>> funclist = [sin, cos, cube]
>>> funclisti = [asin, acos, croot]
>>> # Apply functions from lists as easily as integers
>>> [compose(inversef, f)(.5) for f, inversef in zip(funclist, funclisti)]
[0.5, 0.4999999999999999, 0.5]
>>></lang>


=={{header|R}}==
void main() {
<lang R>cube <- function(x) x^3
// wrappers needed as not all built-in functions
croot <- function(x) x^(1/3)
// have same signature, eg pure/nothrow
compose <- function(f, g) function(x){f(g(x))}
auto sin = (real x){ return std.math.sin(x); };
auto asin = (real x){ return std.math.asin(x); };
auto cos = (real x){ return std.math.cos(x); };
auto acos = (real x){ return std.math.acos(x); };
auto cube = (real x){ return x ^^ 3; };
auto cbrt = (real x){ return std.math.cbrt(x); };


alias TypeTuple!(sin, cos, cube) dir;
f1 <- c(sin, cos, cube)
alias TypeTuple!(asin, acos, cbrt) inv;
f2 <- c(asin, acos, croot)


for(i in 1:3) {
foreach (i, f; dir)
writefln("%6.3f", compose!(f, inv[i])(0.5));
print(compose(f1[[i]], f2[[i]])(.5))
}</lang>
}</lang>


Alternatively:
=={{header|E}}==


<lang R>
First, a brief summary of the relevant semantics: In E, every value, including built-in and user-defined functions, "is an object" — it has methods which respond to messages. Methods are distinguished by the given name (''verb'') and the number of parameters (''arity''). By convention and syntactic sugar, a ''function'' is an object which has a method whose verb is "run".
sapply(mapply(compose,f1,f2),do.call,list(.5))
</lang>


=={{header|REBOL}}==
The relevant mathematical operations are provided as methods on floats, so the first thing we must do is define them as functions.
<lang REBOL>REBOL [
Title: "First Class Functions"
Author: oofoe
Date: 2009-12-05
URL: http://rosettacode.org/wiki/First-class_functions
]


; Functions "foo" and "bar" are used to prove that composition
<lang e>def sin(x) { return x.sin() }
; actually took place by attaching their signatures to the result.
def cos(x) { return x.cos() }
def asin(x) { return x.asin() }
def acos(x) { return x.acos() }
def cube(x) { return x ** 3 }
def curt(x) { return x ** (1/3) }


foo: func [x][reform ["foo:" x]]
def forward := [sin, cos, cube]
bar: func [x][reform ["bar:" x]]
def reverse := [asin, acos, curt]</lang>


cube: func [x][x * x * x]
There are no built-in functions in this list, since the original author couldn't easily think of any which had one parameter and were inverses of each other, but composition would work just the same with them.
croot: func [x][power x 1 / 3]


; "compose" means something else in REBOL, so I "fashion" an alternative.
Defining composition. <code>fn ''params'' { ''expr'' }</code> is shorthand for an anonymous function returning a value.
<lang e>def compose(f, g) {
return fn x { f(g(x)) }
}</lang>


fashion: func [f1 f2][
<lang e>? def x := 0.5 \
do compose/deep [func [x][(:f1) (:f2) x]]]
> for i => f in forward {
> def g := reverse[i]
> println(`x = $x, f = $f, g = $g, compose($f, $g)($x) = ${compose(f, g)(x)}`)
> }


A: [foo sine cosine cube]
x = 0.5, f = <sin>, g = <asin>, compose(<sin>, <asin>)(0.5) = 0.5
B: [bar arcsine arccosine croot]
x = 0.5, f = <cos>, g = <acos>, compose(<cos>, <acos>)(0.5) = 0.4999999999999999
x = 0.5, f = <cube>, g = <curt>, compose(<cube>, <curt>)(0.5) = 0.5000000000000001</lang>


while [not tail? A][
Note: <code>def g := reverse[i]</code> is needed here because E as yet has no defined protocol for iterating over collections in parallel. [http://wiki.erights.org/wiki/Parallel_iteration Page for this issue.]
fn: fashion get A/1 get B/1
=={{header|Factor}}==
source fn ; Prove that functions actually got composed.
<lang factor>USING: assocs combinators kernel math.functions prettyprint
print [fn 0.5 crlf]
sequences ;
IN: rosettacode.first-class-functions


CONSTANT: A { [ sin ] [ cos ] [ 3 ^ ] }
A: next A B: next B ; Advance to next pair.
]</lang>
CONSTANT: B { [ asin ] [ acos ] [ 1/3 ^ ] }
: compose-all ( seq1 seq2 -- seq ) [ compose ] 2map ;
: test1 ( -- )
0.5 A B compose-all
[ call( x -- y ) ] with map . ;</lang>
=={{header|Forth}}==
<lang forth>: compose ( xt1 xt2 -- xt3 )
>r >r :noname
r> compile,
r> compile,
postpone ;
;


=={{header|Ruby}}==
: cube fdup fdup f* f* ;
<lang ruby>irb(main):001:0> cube = proc {|x| x ** 3}
: cuberoot 1e 3e f/ f** ;
=> #<Proc:0xb7cac4b8@(irb):1>
irb(main):002:0> croot = proc {|x| x ** (1/3.0)}
=> #<Proc:0xb7ca40d8@(irb):2>
irb(main):003:0> compose = proc {|f,g| proc {|x| f[g[x]]}}
=> #<Proc:0xb7c9996c@(irb):3>
irb(main):004:0> funclist = [Math.method(:sin).to_proc, Math.method(:cos).to_proc, cube]
=> [#<Proc:0xb7c84be8@(irb):4>, #<Proc:0xb7c84bac@(irb):4>, #<Proc:0xb7cac4b8@(irb):1>]
irb(main):005:0> funclisti = [Math.method(:asin).to_proc, Math.method(:acos).to_proc, croot]
=> [#<Proc:0xb7c7a88c@(irb):5>, #<Proc:0xb7c7a850@(irb):5>, #<Proc:0xb7ca40d8@(irb):2>]
irb(main):006:0> funclist.zip(funclisti).map {|f,inversef| compose[inversef, f][0.5] }
=> [0.5, 0.5, 0.5]</lang>


=={{header|Scala}}==
: table create does> swap cells + @ ;
<lang scala>def cube = (x:Double) => x*x*x
def cuberoot = (x:Double) => Math.pow(x,1.0/3)


def compose[A,B,C](f:B=>C,g:A=>B) = (x:A)=>f(g(x))
table fn ' fsin , ' fcos , ' cube ,
table inverse ' fasin , ' facos , ' cuberoot ,


def fun = List(Math.sin _, Math.cos _, cube)
: main
def inv = List(Math.asin _, Math.acos _, cuberoot)
3 0 do
i fn i inverse compose ( xt )
0.5e execute f.
loop ;


def comp = fun zip inv map Function.tupled(_ compose _)
main \ 0.5 0.5 0.5</lang>


comp.foreach(f=>println(f(0.5)))</lang>
=={{header|F_Sharp|F#}}==
<lang fsharp>open System


Here's how you could add a composition operator to make that syntax prettier:
let cube x = x ** 3.0
let croot x = x ** (1.0/3.0)


<lang scala>class SweetFunction[B,C](f:B=>C) {
let funclist = [Math.Sin; Math.Cos; cube]
def o[A](g:A=>B) = (x:A)=>f(g(x))
let funclisti = [Math.Asin; Math.Acos; croot]
}
let composed = List.map2 (<<) funclist funclisti
implicit def sugarOnTop[A,B](f:A=>B) = new SweetFunction(f)


//and now you can do things like this
let main() = for f in composed do printfn "%f" (f 0.5)
println((cube o cube o cuberoot)(0.5))</lang>


=={{header|Scheme}}==
main()</lang>
<lang scheme>(define (compose f g) (lambda (x) (f (g x))))
(define (cube x) (expt x 3))
(define (cube-root x) (expt x (/ 1 3)))


(define function (list sin cos cube))
(define inverse (list asin acos cube-root))

(define x 0.5)
(define (go f g)
(if (not (or (null? f)
(null? g)))
(begin (display ((compose (car f) (car g)) x))
(newline)
(go (cdr f) (cdr g)))))

(go function inverse)</lang>
Output:
Output:
0.5
<pre>0.500000
0.500000
0.5
0.5
0.500000</pre>


=={{header|Fantom}}==
=={{header|Slate}}==


Compose is already defined in slate as (note the examples in the comment):
Methods defined for classes can be pulled out into functions, e.g. "Float#sin.func" pulls the sine method for floats out into a function accepting a single argument. This function is then a first-class value.


<lang slate>m@(Method traits) ** n@(Method traits)
<lang fantom>
"Answers a new Method whose effect is that of calling the first method
class FirstClassFns
on the results of the second method applied to whatever arguments are passed.
{
This composition is associative, i.e. (a ** b) ** c = a ** (b ** c).
static |Obj -> Obj| compose (|Obj -> Obj| fn1, |Obj -> Obj| fn2)
When the second method, n, does not take a *rest option or the first takes
{
more than one input, then the output is chunked into groups for its
return |Obj x -> Obj| { fn2 (fn1 (x)) }
consumption. E.g.:
}
#; `er ** #; `er applyTo: {'a'. 'b'. 'c'. 'd'} => 'abcd'
#; `er ** #name `er applyTo: {#a. #/}. => 'a/'"
[
n acceptsAdditionalArguments \/ [m arity = 1]
ifTrue:
[[| *args | m applyTo: {n applyTo: args}]]
ifFalse:
[[| *args |
m applyTo:
([| :stream |
args do: [| *each | stream nextPut: (n applyTo: each)]
inGroupsOf: n arity] writingAs: {})]]
].


#**`er asMethod: #compose: on: {Method traits. Method traits}.</lang>
public static Void main ()
used as:
{
<lang slate>n@(Number traits) cubed [n raisedTo: 3].
cube := |Float a -> Float| { a * a * a }
n@(Number traits) cubeRoot [n raisedTo: 1 / 3].
cbrt := |Float a -> Float| { a.pow(1/3f) }
define: #forward -> {#cos `er. #sin `er. #cube `er}.
define: #reverse -> {#arcCos `er. #arcSin `er. #cubeRoot `er}.


define: #composedMethods -> (forward with: reverse collect: #compose: `er).
|Float->Float|[] fns := [Float#sin.func, Float#cos.func, cube]
composedMethods do: [| :m | inform: (m applyWith: 0.5)].</lang>
|Float->Float|[] inv := [Float#asin.func, Float#acos.func, cbrt]
|Float->Float|[] composed := fns.map |fn, i| { compose(fn, inv[i]) }


=={{header|Smalltalk}}==
composed.each |fn| { echo (fn(0.5f)) }
{{works with|GNU Smalltalk}}
}
<lang smalltalk>|forward reverse composer compounds|
}
"commodities"
</lang>
Number extend [
cube [ ^self raisedTo: 3 ]
].
Number extend [
cubeRoot [ ^self raisedTo: (1 / 3) ]
].

forward := #( #cos #sin #cube ).
reverse := #( #arcCos #arcSin #cubeRoot ).

composer := [ :f :g | [ :x | f value: (g value: x) ] ].

"let us create composed funcs"
compounds := OrderedCollection new.

1 to: 3 do: [ :i |
compounds add: ([ :j | composer value: [ :x | x perform: (forward at: j) ]
value: [ :x | x perform: (reverse at: j) ] ] value: i)
].

compounds do: [ :r | (r value: 0.5) displayNl ].</lang>


Output:
Output:

<pre>
<pre>0.4999999999999999
0.5
0.5
0.5000000000000001</pre>
0.4999999999999999
0.5
</pre>


=={{header|GAP}}==
=={{header|Standard ML}}==
<lang sml>- fun cube x = Math.pow(x, 3.0);
<lang gap># Function composition
val cube = fn : real -> real
Composition := function(f, g)
- fun croot x = Math.pow(x, 1.0 / 3.0);
local h;
val croot = fn : real -> real
h := function(x)
- fun compose (f, g) = fn x => f (g x); (* this is already implemented in Standard ML as the "o" operator
return f(g(x));
= we could have written "fun compose (f, g) x = f (g x)" but we show this for clarity *)
end;
val compose = fn : ('a -> 'b) * ('c -> 'a) -> 'c -> 'b
return h;
- val funclist = [Math.sin, Math.cos, cube];
end;
val funclist = [fn,fn,fn] : (real -> real) list
- val funclisti = [Math.asin, Math.acos, croot];
val funclisti = [fn,fn,fn] : (real -> real) list
- ListPair.map (fn (f, inversef) => (compose (inversef, f)) 0.5) (funclist, funclisti);
val it = [0.5,0.5,0.500000000001] : real list</lang>


=={{header|Tcl}}==
# Apply each function in list u, to argument x
The following is a transcript of an interactive session:<br>
ApplyList := function(u, x)
{{works with|tclsh|8.5}}
local i, n, v;
<lang Tcl>% namespace path tcl::mathfunc ;# to import functions like abs() etc.
n := Size(u);
% proc cube x {expr {$x**3}}
v := [ ];
% proc croot x {expr {$x**(1/3.)}}
for i in [1 .. n] do
% proc compose {f g} {list apply {{f g x} {{*}$f [{*}$g $x]}} $f $g}
v[i] := u[i](x);
od;
return v;
end;


% compose abs cube ;# returns a partial command, without argument
# Inverse and Sqrt are in the built-in library. Note that GAP doesn't have real numbers nor floating point numbers. Therefore, Sqrt yields values in cyclotomic fields.
apply {{f g x} {{*}$f [{*}$g $x]}} abs cube
# For example,
# gap> Sqrt(7);
# E(28)^3-E(28)^11-E(28)^15+E(28)^19-E(28)^23+E(28)^27
# where E(n) is a primitive n-th root of unity
a := [ i -> i + 1, Inverse, Sqrt ];
# [ function( i ) ... end, <Operation "InverseImmutable">, <Operation "Sqrt"> ]
b := [ i -> i - 1, Inverse, x -> x*x ];
# [ function( i ) ... end, <Operation "InverseImmutable">, function( x ) ... end ]


% {*}[compose abs cube] -3 ;# applies the partial command to argument -3
# Compose each couple
27
z := ListN(a, b, Composition);


% set forward [compose [compose sin cos] cube] ;# omitting to print result
# Now a test
% set backward [compose croot [compose acos asin]]
ApplyList(z, 3);
% {*}$forward 0.5
[ 3, 3, 3 ]</lang>
0.8372297964617733
% {*}$backward [{*}$forward 0.5]
0.5000000000000017</lang>
Obviously, the ([[C]]) library implementation of some of the trigonometric functions (on which Tcl depends for its implementation) on the platform used for testing is losing a little bit of accuracy somewhere.


=={{header|Go}}==
=={{header|TI-89 BASIC}}==
<lang go>package main


See the comments at [[Function as an Argument#TI-89 BASIC]] for more information on first-class functions or the lack thereof in TI-89 BASIC. In particular, it is not possible to do proper function composition, because functions cannot be passed as values nor be closures.
import "math"
import "fmt"


Therefore, this example does everything but the composition.
// user-defined function, per task. Other math functions used are built-in.
func cube(x float64) float64 { return math.Pow(x, 3) }


(Note: The names of the inverse functions may not display as intended unless you have the “TI Uni” font.)
// ffType and compose function taken from Function composition task
type ffType func(float64) float64


<lang ti89b>Prgm
func compose(f, g ffType) ffType {
Local funs,invs,composed,x,i
return func(x float64) float64 {

return f(g(x))
Define rc_cube(x) = x^3 © Cannot be local variables
}
Define rc_curt(x) = x^(1/3)
}


Define funs = {"sin","cos","rc_cube"}
func main() {
Define invs = {"sin","cos","rc_curt"}
// collection A

funclist := []ffType{math.Sin, math.Cos, cube}
Define x = 0.5
// collection B
Disp "x = " & string(x)
funclisti := []ffType{math.Asin, math.Acos, math.Cbrt}
For i,1,3
for i := 0; i < 3; i++ {
Disp "f=" & invs[i] & " g=" & funs[i] & " f(g(x))=" & string(#(invs[i])(#(funs[i])(x)))
// apply composition and show result
EndFor
fmt.Println(compose(funclisti[i], funclist[i])(.5))

}
DelVar rc_cube,rc_curt © Clean up our globals
}</lang>
EndPrgm</lang>
Output:

<pre>
=={{header|Ursala}}==
0.49999999999999994
The algorithm is to zip two lists of functions into a list of pairs of functions, make
0.5
that a list of functions by composing each pair, "<code>gang</code>" the list of
0.5
functions into a single function returning a list, and apply it to the
</pre>
argument 0.5.
<lang Ursala>#import std
#import flo

functions = <sin,cos,times^/~& sqr>
inverses = <asin,acos,math..cbrt>

#cast %eL

main = (gang (+)*p\functions inverses) 0.5</lang>
In more detail,
* <code>(+)*p\functions inverses</code> evaluates to <code>(+)*p(inverses,functions)</code> by definition of the reverse binary to unary combinator (<code>\</code>)
* This expression evaluates to <code>(+)*p(<asin,acos,math..cbrt>,<sin,cos,times^/~& sqr>)</code> by substitution.
* The zipping is indicated by the <code>p</code> suffix on the map operator, (<code>*</code>) so that <code>(+)*p</code> evaluates to <code>(+)* <(asin,sin),(acos,cos),(cbrt,times^/~& sqr)></code>.
* The composition (<code>(+)</code>) operator is then mapped over the resulting list of pairs of functions, to obtain the list of functions <code><asin+sin,acos+cos,cbrt+ times^/~& sqr></code>.
* <code>gang<aisn+sin,acos+cos,cbrt+ times^/~& sqr></code> expresses a function returning a list in terms of a list of functions.

output:
<pre><5.000000e-01,5.000000e-01,5.000000e-01></pre>

Revision as of 20:35, 16 July 2011

Groovy

Solution: <lang groovy>def compose = { f, g -> { x -> f(g(x)) } }</lang>

Test program: <lang groovy>def cube = { it * it * it } def cubeRoot = { it ** (1/3) }

funcList = [ Math.&sin, Math.&cos, cube ] inverseList = [ Math.&asin, Math.&acos, cubeRoot ]

println [funcList, inverseList].transpose().collect { compose(it[0],it[1]) }.collect{ it(0.5) } println [inverseList, funcList].transpose().collect { compose(it[0],it[1]) }.collect{ it(0.5) }</lang>

Output:

[0.5, 0.4999999999999999, 0.5000000000346574]
[0.5, 0.4999999999999999, 0.5000000000346574]

Haskell

<lang haskell>Prelude> let cube x = x ^ 3 Prelude> let croot x = x ** (1/3) Prelude> let compose f g = \x -> f (g x) -- this is already implemented in Haskell as the "." operator Prelude> -- we could have written "let compose f g x = f (g x)" but we show this for clarity Prelude> let funclist = [sin, cos, cube] Prelude> let funclisti = [asin, acos, croot] Prelude> zipWith (\f inversef -> (compose inversef f) 0.5) funclist funclisti [0.5,0.4999999999999999,0.5]</lang>

Icon and Unicon

The Unicon solution can be modified to work in Icon. See Function_composition#Icon_and_Unicon. <lang Unicon>link compose procedure main(arglist)

   fun := [sin,cos,cube]
   inv := [asin,acos,cuberoot]
   x := 0.5
   every i := 1 to *inv do 
      write("f(",x,") := ", compose(inv[i],fun[i])(x))

end

procedure cube(x) return x*x*x end

procedure cuberoot(x) return x ^ (1./3) end</lang> Please refer to See Function_composition#Icon_and_Unicon for 'compose'.

Sample Output:

f(0.5) := 0.5
f(0.5) := 0.4999999999999999
f(0.5) := 0.5

J

J has some subtleties which are not addressed in this specification (J functions have grammatical character and their gerundial form may be placed in data structures where the spec sort of implies that there be no such distinction).

However, here are the basics which were requested: <lang j> sin=: 1&o.

  cos=:  2&o.
 cube=: ^&3

square=: *:

 unqo=: `:6
 unqcol=: `:0
 quot=: 1 :'{.u`
 A=: sin`cos`cube`square
 B=: monad def'y unqo inv quot'"0 A
 BA=. A dyad def'x unqo@(y unqo) quot'"0 B</lang>

<lang> A unqcol 0.5 0.479426 0.877583 0.125 0.25

  BA unqcol 0.5

0.5 0.5 0.5 0.5</lang>

Java

Java doesn't technically have first-class functions. Java can simulate first-class functions to a certain extent, with anonymous classes and generic function interface.

<lang java> public static Function<Double, Double> compose( final Function<Double, Double> f, final Function<Double, Double> g) { return new Function<Double, Double>() { @Override public Double apply(Double x) { return f.apply(g.apply(x)); } }; }

@SuppressWarnings("unchecked") public static void main(String[] args) { ArrayList<Function<Double, Double>> functions = Lists.newArrayList( new Function<Double, Double>() { @Override public Double apply(Double x) { return Math.cos(x); } }, new Function<Double, Double>() { @Override public Double apply(Double x) { return Math.tan(x); } }, new Function<Double, Double>() { @Override public Double apply(Double x) { return x * x; } }); ArrayList<Function<Double, Double>> inverse = Lists.newArrayList( new Function<Double, Double>() { @Override public Double apply(Double x) { return Math.acos(x); } }, new Function<Double, Double>() { @Override public Double apply(Double x) { return Math.atan(x); } }, new Function<Double, Double>() { @Override public Double apply(Double x) { return Math.sqrt(x); } }); for (int i = 0; i < functions.size(); i++) { System.out.println(compose(functions.get(i), inverse.get(i)).apply(0.5)); } } </lang>

JavaScript

assuming the print function is provided by the environment, like a stand-alone shell. In browsers, use alert(), document.write() or similar

<lang javascript>var compose = function (f, g) {

   return function (x) { 
       return f(g(x)); 
   }; 

};

var fn = [Math.sin, Math.cos, function (x) { return Math.pow(x, 3); }]; var inv = [Math.asin, Math.acos, function (x) { return Math.pow(x, 1/3); }];

(function () {

   for (var i = 0; i < 3; i++) {
       var f = compose(inv[i], fn[i]);
       print(f(0.5));    // 0.5
   }

})();

</lang>

Lua

<lang lua> function compose(f,g) return function(...) return f(g(...)) end end

fn = {math.sin, math.cos, function(x) return x^3 end} inv = {math.asin, math.acos, function(x) return x^(1/3) end}

for i, v in ipairs(fn)

 local f = compose(v, inv[i])
 print(f(0.5))     --> 0.5

end</lang>

Mathematica

The built-in function Composition can do composition, a custom function that does the same would be compose[f_,g_]:=f[g[#]]&. However the latter only works with 2 arguments, Composition works with any number of arguments. <lang Mathematica>funcs = {Sin, Cos, #^3 &}; funcsi = {ArcSin, ArcCos, #^(1/3) &}; compositefuncs = Composition @@@ Transpose[{funcs, funcsi}]; Table[i[0.666], {i, compositefuncs}]</lang> gives back: <lang Mathematica>{0.666, 0.666, 0.666}</lang> Note that I implemented cube and cube-root as pure functions. This shows that Mathematica is fully able to handle functions as variables, functions can return functions, and functions can be given as an argument. 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>

Nemerle

Translation of: Python

<lang Nemerle>using System; using System.Console; using System.Math; using Nemerle.Collections.NCollectionsExtensions;

module FirstClassFunc {

   Main() : void
   {
       def cube = fun (x) {x * x * x};
       def croot = fun (x) {Pow(x, 1.0/3.0)};
       def compose = fun(f, g) {fun (x) {f(g(x))}};
       def funcs = [Sin, Cos, cube];
       def ifuncs = [Asin, Acos, croot];
       WriteLine($[compose(f, g)(0.5) | (f, g) in ZipLazy(funcs, ifuncs)]);
   }

}</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)) > (define (cube x) (pow x 3)) (lambda (x) (pow x 3)) > (define (cube-root x) (pow x (div 1 3))) (lambda (x) (pow x (div 1 3))) > (define functions '(sin cos cube)) (sin cos cube) > (define inverses '(asin acos cube-root)) (asin acos cube-root) > (map (fn (f g) ((compose f g) 0.5)) functions inverses) (0.5 0.5 0.5) </lang>

OCaml

<lang ocaml># let cube x = x ** 3. ;; val cube : float -> float = <fun>

  1. let croot x = x ** (1. /. 3.) ;;

val croot : float -> float = <fun>

  1. let compose f g = fun x -> f (g x) ;; (* we could have written "let compose f g x = f (g x)" but we show this for clarity *)

val compose : ('a -> 'b) -> ('c -> 'a) -> 'c -> 'b = <fun>

  1. let funclist = [sin; cos; cube] ;;

val funclist : (float -> float) list = [<fun>; <fun>; <fun>]

  1. let funclisti = [asin; acos; croot] ;;

val funclisti : (float -> float) list = [<fun>; <fun>; <fun>]

  1. List.map2 (fun f inversef -> (compose inversef f) 0.5) funclist funclisti ;;

- : float list = [0.5; 0.499999999999999889; 0.5]</lang>

Octave

<lang octave>function r = cube(x)

 r = x.^3;

endfunction

function r = croot(x)

 r = x.^(1/3);

endfunction

compose = @(f,g) @(x) f(g(x));

f1 = {@sin, @cos, @cube}; f2 = {@asin, @acos, @croot};

for i = 1:3

 disp(compose(f1{i}, f2{i})(.5))

endfor</lang>


Oz

To be executed in the REPL.

<lang oz>declare

 fun {Compose F G}
    fun {$ X}
       {F {G X}}
    end
 end
 fun {Cube X} X*X*X end
 fun {CubeRoot X} {Number.pow X 1.0/3.0} end

in

 for
    F in [Float.sin  Float.cos  Cube]
    I in [Float.asin Float.acos CubeRoot]
 do
    {Show {{Compose I F} 0.5}}
 end

</lang>

PARI/GP

Works with: PARI/GP version 2.4.2 and above

<lang parigp>compose(f,g)={

 x -> f(g(x))

};

fcf()={

 my(A,B);
 A=[x->sin(x), x->cos(x), x->x^2];
 B=[x->asin(x), x->acos(x), x->sqrt(x)];
 for(i=1,#A,
   print(compose(A[i],B[i])(.5))
 )

};</lang> Usage note: In Pari/GP 2.4.3 the vectors can be written as <lang parigp> A=[sin, cos, x->x^2];

 B=[asin, acos, x->sqrt(x)];</lang>

Perl

<lang perl>use Math::Complex ':trig';

sub compose {

   my ($f, $g) = @_;
   
   sub {
       $f -> ($g -> (@_));
   };

}

my $cube = sub { $_[0] ** (3) }; my $croot = sub { $_[0] ** (1/3) };

my @flist1 = ( \&Math::Complex::sin, \&Math::Complex::cos, $cube ); my @flist2 = ( \&asin, \&acos, $croot );

print join "\n", map {

   compose($flist1[$_], $flist2[$_]) -> (0.5)   

} 0..2;</lang>

Perl 6

Works with: Rakudo version 2011.06

<lang perl6>sub compose (&g, &f) { return { g f $^x } }

my $x = *.sin; my $xi = *.asin; my $y = *.cos; my $yi = *.acos; my $z = * ** 3; my $zi = * ** (1/3);

my @functions = $x, $y, $z; my @inverses = $xi, $yi, $zi;

for @functions Z @inverses { say compose($^g, $^f)(.5) }</lang> Output:

0.5
0.5
0.5

PicoLisp

<lang PicoLisp>(load "@lib/math.l")

(de compose (F G)

  (curry (F G) (X)
     (F (G X)) ) )

(de cube (X)

  (pow X 3.0) )

(de cubeRoot (X)

  (pow X 0.3333333) )

(mapc

  '((Fun Inv)
     (prinl (format ((compose Inv Fun) 0.5) *Scl)) )
  '(sin  cos  cube)
  '(asin acos cubeRoot) )</lang>

Output:

0.500001
0.499999
0.500000

Prolog

Works with SWI-Prolog and module lambda, written by Ulrich Neumerkel found here: http://www.complang.tuwien.ac.at/ulrich/Prolog-inedit/lambda.pl

<lang Prolog>:- use_module(library(lambda)).


compose(F,G, FG) :- FG = \X^Z^(call(G,X,Y), call(F,Y,Z)).

cube(X, Y) :- Y is X ** 3.

cube_root(X, Y) :- Y is X ** (1/3).

first_class :- L = [sin, cos, cube], IL = [asin, acos, cube_root],

% we create the composed functions maplist(compose, L, IL, Lst),

% we call the functions maplist(call, Lst, [0.5,0.5,0.5], R),

% we display the results maplist(writeln, R). </lang> Output :

 ?- first_class.
0.5
0.4999999999999999
0.5000000000000001
true.

Python

<lang python>>>> # Some built in functions and their inverses >>> from math import sin, cos, acos, asin >>> # Add a user defined function and its inverse >>> cube = lambda x: x * x * x >>> croot = lambda x: x ** (1/3.0) >>> # First class functions allow run-time creation of functions from functions >>> # return function compose(f,g)(x) == f(g(x)) >>> compose = lambda f1, f2: ( lambda x: f1(f2(x)) ) >>> # first class functions should be able to be members of collection types >>> funclist = [sin, cos, cube] >>> funclisti = [asin, acos, croot] >>> # Apply functions from lists as easily as integers >>> [compose(inversef, f)(.5) for f, inversef in zip(funclist, funclisti)] [0.5, 0.4999999999999999, 0.5] >>></lang>

R

<lang R>cube <- function(x) x^3 croot <- function(x) x^(1/3) compose <- function(f, g) function(x){f(g(x))}

f1 <- c(sin, cos, cube) f2 <- c(asin, acos, croot)

for(i in 1:3) {

 print(compose(f1i, f2i)(.5))

}</lang>

Alternatively:

<lang R> sapply(mapply(compose,f1,f2),do.call,list(.5)) </lang>

REBOL

<lang REBOL>REBOL [ Title: "First Class Functions" Author: oofoe Date: 2009-12-05 URL: http://rosettacode.org/wiki/First-class_functions ]

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

cube: func [x][x * x * x] croot: func [x][power x 1 / 3]

"compose" means something else in REBOL, so I "fashion" an alternative.

fashion: func [f1 f2][ do compose/deep [func [x][(:f1) (:f2) x]]]

A: [foo sine cosine cube] B: [bar arcsine arccosine croot]

while [not tail? A][ fn: fashion get A/1 get B/1 source fn ; Prove that functions actually got composed. print [fn 0.5 crlf]

A: next A B: next B  ; Advance to next pair. ]</lang>

Ruby

<lang ruby>irb(main):001:0> cube = proc {|x| x ** 3} => #<Proc:0xb7cac4b8@(irb):1> irb(main):002:0> croot = proc {|x| x ** (1/3.0)} => #<Proc:0xb7ca40d8@(irb):2> irb(main):003:0> compose = proc {|f,g| proc {|x| f[g[x]]}} => #<Proc:0xb7c9996c@(irb):3> irb(main):004:0> funclist = [Math.method(:sin).to_proc, Math.method(:cos).to_proc, cube] => [#<Proc:0xb7c84be8@(irb):4>, #<Proc:0xb7c84bac@(irb):4>, #<Proc:0xb7cac4b8@(irb):1>] irb(main):005:0> funclisti = [Math.method(:asin).to_proc, Math.method(:acos).to_proc, croot] => [#<Proc:0xb7c7a88c@(irb):5>, #<Proc:0xb7c7a850@(irb):5>, #<Proc:0xb7ca40d8@(irb):2>] irb(main):006:0> funclist.zip(funclisti).map {|f,inversef| compose[inversef, f][0.5] } => [0.5, 0.5, 0.5]</lang>

Scala

<lang scala>def cube = (x:Double) => x*x*x def cuberoot = (x:Double) => Math.pow(x,1.0/3)

def compose[A,B,C](f:B=>C,g:A=>B) = (x:A)=>f(g(x))

def fun = List(Math.sin _, Math.cos _, cube) def inv = List(Math.asin _, Math.acos _, cuberoot)

def comp = fun zip inv map Function.tupled(_ compose _)

comp.foreach(f=>println(f(0.5)))</lang>

Here's how you could add a composition operator to make that syntax prettier:

<lang scala>class SweetFunction[B,C](f:B=>C) {

 def o[A](g:A=>B) = (x:A)=>f(g(x))

} implicit def sugarOnTop[A,B](f:A=>B) = new SweetFunction(f)

//and now you can do things like this println((cube o cube o cuberoot)(0.5))</lang>

Scheme

<lang scheme>(define (compose f g) (lambda (x) (f (g x)))) (define (cube x) (expt x 3)) (define (cube-root x) (expt x (/ 1 3)))

(define function (list sin cos cube)) (define inverse (list asin acos cube-root))

(define x 0.5) (define (go f g)

 (if (not (or (null? f)
              (null? g)))
     (begin (display ((compose (car f) (car g)) x))
            (newline)
            (go (cdr f) (cdr g)))))

(go function inverse)</lang> Output:

0.5
0.5
0.5

Slate

Compose is already defined in slate as (note the examples in the comment):

<lang slate>m@(Method traits) ** n@(Method traits) "Answers a new Method whose effect is that of calling the first method on the results of the second method applied to whatever arguments are passed. This composition is associative, i.e. (a ** b) ** c = a ** (b ** c). When the second method, n, does not take a *rest option or the first takes more than one input, then the output is chunked into groups for its consumption. E.g.:

  1. `er ** #; `er applyTo
    {'a'. 'b'. 'c'. 'd'} => 'abcd'
    `er ** #name `er applyTo
    {#a. #/}. => 'a/'"

[

 n acceptsAdditionalArguments \/ [m arity = 1]
   ifTrue:
     [[| *args | m applyTo: {n applyTo: args}]]
   ifFalse:
     [[| *args |
       m applyTo:
         ([| :stream |
            args do: [| *each | stream nextPut: (n applyTo: each)]
                 inGroupsOf: n arity] writingAs: {})]]

].

      • `er asMethod: #compose: on: {Method traits. Method traits}.</lang>

used as: <lang slate>n@(Number traits) cubed [n raisedTo: 3]. n@(Number traits) cubeRoot [n raisedTo: 1 / 3]. define: #forward -> {#cos `er. #sin `er. #cube `er}. define: #reverse -> {#arcCos `er. #arcSin `er. #cubeRoot `er}.

define: #composedMethods -> (forward with: reverse collect: #compose: `er). composedMethods do: [| :m | inform: (m applyWith: 0.5)].</lang>

Smalltalk

Works with: GNU Smalltalk

<lang smalltalk>|forward reverse composer compounds| "commodities" Number extend [

  cube [ ^self raisedTo: 3 ]

]. Number extend [

  cubeRoot [ ^self raisedTo: (1 / 3) ]

].

forward := #( #cos #sin #cube ). reverse := #( #arcCos #arcSin #cubeRoot ).

composer := [ :f :g | [ :x | f value: (g value: x) ] ].

"let us create composed funcs" compounds := OrderedCollection new.

1 to: 3 do: [ :i |

 compounds add: ([ :j | composer value: [ :x | x perform: (forward at: j) ]
                                 value: [ :x | x perform: (reverse at: j) ] ] value: i)

].

compounds do: [ :r | (r value: 0.5) displayNl ].</lang>

Output:

0.4999999999999999
0.5
0.5000000000000001

Standard ML

<lang sml>- fun cube x = Math.pow(x, 3.0); val cube = fn : real -> real - fun croot x = Math.pow(x, 1.0 / 3.0); val croot = fn : real -> real - fun compose (f, g) = fn x => f (g x); (* this is already implemented in Standard ML as the "o" operator = we could have written "fun compose (f, g) x = f (g x)" but we show this for clarity *) val compose = fn : ('a -> 'b) * ('c -> 'a) -> 'c -> 'b - val funclist = [Math.sin, Math.cos, cube]; val funclist = [fn,fn,fn] : (real -> real) list - val funclisti = [Math.asin, Math.acos, croot]; val funclisti = [fn,fn,fn] : (real -> real) list - ListPair.map (fn (f, inversef) => (compose (inversef, f)) 0.5) (funclist, funclisti); val it = [0.5,0.5,0.500000000001] : real list</lang>

Tcl

The following is a transcript of an interactive session:

Works with: tclsh version 8.5

<lang Tcl>% namespace path tcl::mathfunc ;# to import functions like abs() etc. % proc cube x {expr {$x**3}} % proc croot x {expr {$x**(1/3.)}} % proc compose {f g} {list apply {{f g x} {{*}$f [{*}$g $x]}} $f $g}

% compose abs cube  ;# returns a partial command, without argument apply {{f g x} {{*}$f [{*}$g $x]}} abs cube

% {*}[compose abs cube] -3  ;# applies the partial command to argument -3 27

% set forward [compose [compose sin cos] cube] ;# omitting to print result % set backward [compose croot [compose acos asin]] % {*}$forward 0.5 0.8372297964617733 % {*}$backward [{*}$forward 0.5] 0.5000000000000017</lang> Obviously, the (C) library implementation of some of the trigonometric functions (on which Tcl depends for its implementation) on the platform used for testing is losing a little bit of accuracy somewhere.

TI-89 BASIC

See the comments at Function as an Argument#TI-89 BASIC for more information on first-class functions or the lack thereof in TI-89 BASIC. In particular, it is not possible to do proper function composition, because functions cannot be passed as values nor be closures.

Therefore, this example does everything but the composition.

(Note: The names of the inverse functions may not display as intended unless you have the “TI Uni” font.)

<lang ti89b>Prgm

 Local funs,invs,composed,x,i
 Define rc_cube(x) = x^3     © Cannot be local variables
 Define rc_curt(x) = x^(1/3)
 Define funs = {"sin","cos","rc_cube"}
 Define invs = {"sin","cos","rc_curt"}
 Define x = 0.5
 Disp "x = " & string(x)
 For i,1,3
   Disp "f=" & invs[i] & " g=" & funs[i] & " f(g(x))=" & string(#(invs[i])(#(funs[i])(x)))
 EndFor
 DelVar rc_cube,rc_curt  © Clean up our globals

EndPrgm</lang>

Ursala

The algorithm is to zip two lists of functions into a list of pairs of functions, make that a list of functions by composing each pair, "gang" the list of functions into a single function returning a list, and apply it to the argument 0.5. <lang Ursala>#import std

  1. import flo

functions = <sin,cos,times^/~& sqr> inverses = <asin,acos,math..cbrt>

  1. cast %eL

main = (gang (+)*p\functions inverses) 0.5</lang> In more detail,

  • (+)*p\functions inverses evaluates to (+)*p(inverses,functions) by definition of the reverse binary to unary combinator (\)
  • This expression evaluates to (+)*p(<asin,acos,math..cbrt>,<sin,cos,times^/~& sqr>) by substitution.
  • The zipping is indicated by the p suffix on the map operator, (*) so that (+)*p evaluates to (+)* <(asin,sin),(acos,cos),(cbrt,times^/~& sqr)>.
  • The composition ((+)) operator is then mapped over the resulting list of pairs of functions, to obtain the list of functions <asin+sin,acos+cos,cbrt+ times^/~& sqr>.
  • gang<aisn+sin,acos+cos,cbrt+ times^/~& sqr> expresses a function returning a list in terms of a list of functions.

output:

<5.000000e-01,5.000000e-01,5.000000e-01>