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}}==
{{trans|JavaScript}}
<lang ActionScript>function compose(f:Function, g:Function):Function {
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);}];

function test() {
for (var i:uint = 0; i < functions.length; i++) {
trace(compose(functions[i], inverse[i])(0.5));
}
}</lang>

=={{header|Ada}}==
<lang Ada>
<lang Ada>
with Ada.Text_IO;
with Ada.Text_IO;
Line 26: Line 41:


</lang>
</lang>

=={{header|Aikido}}==
{{trans|Javascript}}
<lang aikido>
import math

function compose (f, g) {
return function (x) { return f(g(x)) }
}

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

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

</lang>

=={{header|ALGOL 68}}==
{{trans|Python}}

{{works with|ALGOL 68|Standard - no extensions to language used}}

{{works with|ALGOL 68G|Any - tested with release mk15-0.8b.fc9.i386}}

{{works with|ELLA ALGOL 68|Any (with appropriate job cards) - tested with release 1.8.8d.fc9.i386 using non-standard compose}}

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

# Add a user defined function and its inverse #
PROC cube = (REAL x)REAL: x * x * x;
PROC cube root = (REAL x)REAL: x ** (1/3);

# First class functions allow run-time creation of functions from functions #
# return function compose(f,g)(x) == f(g(x)) #
PROC non standard compose = (F f1, f2)F: (REAL x)REAL: f1(f2(x)); # eg ELLA ALGOL 68RS #
PROC compose = (F f, g)F: ((F f2, g2, REAL x)REAL: f2(g2(x)))(f, g, );

# Or the classic "o" functional operator #
PRIO O = 5;
OP (F,F)F O = compose;

# first class functions should be able to be members of collection types #
[]F func list = (sin, cos, cube);
[]F arc func list = (arc sin, arc cos, cube root);

# Apply functions from lists as easily as integers #
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>

=={{header|AutoHotkey}}==
AutoHotkey core does not support new function definitions at run time.<br>
However, functions can be called by name, so mapping functions is possible:
<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

compose(f, g){
Return map(0, 0, f, g)
}

map(ab = 0, x = 0 , a = 0, b = 0)
{
Static
If (a And b)
Return a . "`n" . b
If ab
{
StringSplit, ab, ab, `n
Return %ab1%(%ab2%(x))
}
}

cube(x){
Return x ** 3
}

cuberoot(x){
Return x ** (1 / 3)
}</lang>

=={{header|C}}==
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.

Here goes.

<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)
{
return v*v*v;
}
double functionB(double v)
{
return exp(log(v)/3);
}
/* 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>
===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>

typedef double (*f_dbl)(double);
#define TAGF (f_dbl)0xdeadbeef
#define TAGG (f_dbl)0xbaddecaf

double dummy(double x)
{
f_dbl f = TAGF;
f_dbl g = TAGG;
return f(g(x));
}

f_dbl composite(f_dbl f, f_dbl g)
{
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;
}

double cube(double x)
{
return x * x * x;
}

/* uncomment next line if your math.h doesn't have cbrt() */
/* double cbrt(double x) { return pow(x, 1/3.); } */

int main()
{
int i;
double x;

f_dbl A[3] = { cube, exp, sin };
f_dbl B[3] = { cbrt, log, asin}; /* not sure about availablity of cbrt() */
f_dbl C[3];

for (i = 0; i < 3; i++)
C[i] = composite(A[i], B[i]);

for (i = 0; i < 3; i++) {
for (x = .2; x <= 1; x += .2)
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

C1(0.2) = 0.2
C1(0.4) = 0.4
C1(0.6) = 0.6
C1(0.8) = 0.8
C1(1) = 1

C2(0.2) = 0.2
C2(0.4) = 0.4
C2(0.6) = 0.6
C2(0.8) = 0.8
C2(1) = 1</lang>

=={{header|C sharp|C#}}==
{{works with|C sharp|4.0}}

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

class Program
{
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);

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

foreach (var compose in composed)
Console.WriteLine(compose(0.5));
}
}
</lang>

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

<lang cpp>
#include <tr1/functional>
#include <vector>
#include <iostream>
#include <cmath>

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

vector<double(*)(double)> A = {sin, cos, tan, [](double x) { return x*x*x; } };
vector<double(*)(double)> B = {asin, acos, atan, [](double x) { return exp(log(x)/3); } };

template <typename A, typename B, typename... Params>
function<A(Params...)> compose(A(*f)(B), B(*g)(Params...)){
return [=](Params... args){ return f(g(args...)); };
}

#define PRINT(x) cout << #x ": " << (x) << endl;
int main() {
double num = 1 / 3.14159;
PRINT(num);
PRINT(compose(B[0], A[0])(num));
PRINT(compose(B[1], A[1])(num));
PRINT(compose(B[2], A[2])(num));
PRINT(compose(B[3], A[3])(num));

auto identity = compose(log10, pow);
PRINT(identity(10, num));
}
</lang>

=={{header|Clojure}}==
<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>

=={{header|CoffeeScript}}==
{{trans|JavaScript}}
<lang coffeescript>compose = (f, g) ->
(x) ->
f g x

fn = [Math.sin, Math.cos, (x) -> Math.pow(x, 3) ]
inv = [Math.asin, Math.acos, (x) -> Math.pow(x, 1/3) ]

do ->
for i in [0..2]
f = compose inv[i], fn[i]
console.log f 0.5 # 0.5</lang>

=={{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
for function in (list #'sin #'cos #'cube )
for inverse in (list #'asin #'acos #'cube-root)
for composed = (compose inverse function)
do (format t "~&(~A ∘ ~A)(~A) = ~A~%"
inverse
function
value
(funcall composed value)))</lang>

Output:

<lang lisp>(#<FUNCTION ASIN> ∘ #<FUNCTION SIN>)(0.5) = 0.5
(#<FUNCTION ACOS> ∘ #<FUNCTION COS>)(0.5) = 0.5
(#<FUNCTION CUBE-ROOT> ∘ #<FUNCTION CUBE>)(0.5) = 0.5</lang>

=={{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 working both in D 1.0 and 2.0:
<lang D>T delegate(S) compose(T, U, S)(T delegate(U) f, U delegate(S) g) {
struct Wrapper {
typeof(f) fcp;
typeof(g) gcp;
T foobar(S s) { return fcp(gcp(s)); }
}

Wrapper* hold = new Wrapper;
hold.fcp = f;
hold.gcp = g;
return &hold.foobar;
}</lang>

Example:

<lang D>import std.stdio, std.math, std.range;

T delegate(S) compose(T, U, S)(T delegate(U) f, U delegate(S) g) {
return (S s){ return f(g(s)); };
}

void main() {
// 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); };

auto fun = [sin, cos, cube];
auto inv = [asin, acos, cbrt];

foreach (f2; zip(fun, inv))
writefln("%6.3f", compose(f2[0], f2[1])(0.5));
}</lang>
Using the compose() of the std lib, D v2:
<lang d>import std.stdio, std.math, std.typetuple, std.functional;

void main() {
// wrappers needed as not all built-in 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); };

alias TypeTuple!(sin, cos, cube) dir;
alias TypeTuple!(asin, acos, cbrt) inv;

foreach (i, f; dir)
writefln("%6.3f", compose!(f, inv[i])(0.5));
}</lang>

=={{header|E}}==

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".

The relevant mathematical operations are provided as methods on floats, so the first thing we must do is define them as functions.

<lang e>def sin(x) { return x.sin() }
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) }

def forward := [sin, cos, cube]
def reverse := [asin, acos, curt]</lang>

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.

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>

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

x = 0.5, f = <sin>, g = <asin>, compose(<sin>, <asin>)(0.5) = 0.5
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>

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.]
=={{header|Factor}}==
<lang factor>USING: assocs combinators kernel math.functions prettyprint
sequences ;
IN: rosettacode.first-class-functions

CONSTANT: A { [ sin ] [ cos ] [ 3 ^ ] }
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 ;
;

: cube fdup fdup f* f* ;
: cuberoot 1e 3e f/ f** ;

: table create does> swap cells + @ ;

table fn ' fsin , ' fcos , ' cube ,
table inverse ' fasin , ' facos , ' cuberoot ,

: main
3 0 do
i fn i inverse compose ( xt )
0.5e execute f.
loop ;

main \ 0.5 0.5 0.5</lang>

=={{header|F_Sharp|F#}}==
<lang fsharp>open System

let cube x = x ** 3.0
let croot x = x ** (1.0/3.0)

let funclist = [Math.Sin; Math.Cos; cube]
let funclisti = [Math.Asin; Math.Acos; croot]
let composed = List.map2 (<<) funclist funclisti

let main() = for f in composed do printfn "%f" (f 0.5)

main()</lang>

Output:
<pre>0.500000
0.500000
0.500000</pre>

=={{header|Fantom}}==

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 fantom>
class FirstClassFns
{
static |Obj -> Obj| compose (|Obj -> Obj| fn1, |Obj -> Obj| fn2)
{
return |Obj x -> Obj| { fn2 (fn1 (x)) }
}

public static Void main ()
{
cube := |Float a -> Float| { a * a * a }
cbrt := |Float a -> Float| { a.pow(1/3f) }

|Float->Float|[] fns := [Float#sin.func, Float#cos.func, cube]
|Float->Float|[] inv := [Float#asin.func, Float#acos.func, cbrt]
|Float->Float|[] composed := fns.map |fn, i| { compose(fn, inv[i]) }

composed.each |fn| { echo (fn(0.5f)) }
}
}
</lang>

Output:
<pre>
0.5
0.4999999999999999
0.5
</pre>

=={{header|GAP}}==
<lang gap># Function composition
Composition := function(f, g)
local h;
h := function(x)
return f(g(x));
end;
return h;
end;

# Apply each function in list u, to argument x
ApplyList := function(u, x)
local i, n, v;
n := Size(u);
v := [ ];
for i in [1 .. n] do
v[i] := u[i](x);
od;
return v;
end;

# 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.
# 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 each couple
z := ListN(a, b, Composition);

# Now a test
ApplyList(z, 3);
[ 3, 3, 3 ]</lang>

=={{header|Go}}==
<lang go>package main

import "math"
import "fmt"

// user-defined function, per task. Other math functions used are built-in.
func cube(x float64) float64 { return math.Pow(x, 3) }

// ffType and compose function taken from Function composition task
type ffType func(float64) float64

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

func main() {
// collection A
funclist := []ffType{math.Sin, math.Cos, cube}
// collection B
funclisti := []ffType{math.Asin, math.Acos, math.Cbrt}
for i := 0; i < 3; i++ {
// apply composition and show result
fmt.Println(compose(funclisti[i], funclist[i])(.5))
}
}</lang>
Output:
<pre>
0.49999999999999994
0.5
0.5
</pre>

Revision as of 20:35, 16 July 2011

ActionScript

Translation of: JavaScript

<lang ActionScript>function compose(f:Function, g:Function):Function { 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);}];

function test() { for (var i:uint = 0; i < functions.length; i++) { trace(compose(functions[i], inverse[i])(0.5)); } }</lang>

Ada

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

</lang>

Aikido

Translation of: Javascript

<lang aikido> import math

function compose (f, g) {

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

}

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

for (var i=0; i<3; i++) {

   var f = compose(inv[i], fn[i])
   println(f(0.5))    // 0.5

}

</lang>

ALGOL 68

Translation of: Python
Works with: ALGOL 68 version Standard - no extensions to language used
Works with: ALGOL 68G version Any - tested with release mk15-0.8b.fc9.i386
Works with: ELLA ALGOL 68 version Any (with appropriate job cards) - tested with release 1.8.8d.fc9.i386 using non-standard compose

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 - if run out of scope - rejects during runtime. <lang algol68>MODE F = PROC (REAL)REAL; OP ** = (REAL x, power)REAL: exp(ln(x)*power);

  1. Add a user defined function and its inverse #

PROC cube = (REAL x)REAL: x * x * x; PROC cube root = (REAL x)REAL: x ** (1/3);

  1. First class functions allow run-time creation of functions from functions #
  2. return function compose(f,g)(x) == f(g(x)) #

PROC non standard compose = (F f1, f2)F: (REAL x)REAL: f1(f2(x)); # eg ELLA ALGOL 68RS # PROC compose = (F f, g)F: ((F f2, g2, REAL x)REAL: f2(g2(x)))(f, g, );

  1. Or the classic "o" functional operator #

PRIO O = 5; OP (F,F)F O = compose;

  1. first class functions should be able to be members of collection types #

[]F func list = (sin, cos, cube); []F arc func list = (arc sin, arc cos, cube root);

  1. Apply functions from lists as easily as integers #

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:

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

AutoHotkey

AutoHotkey core does not support new function definitions at run time.
However, functions can be called by name, so mapping functions is possible: <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

compose(f, g){

 Return map(0, 0, f, g)

}

map(ab = 0, x = 0 , a = 0, b = 0) {

 Static
 If (a And b)
   Return a . "`n" . b
 If ab
 {
   StringSplit, ab, ab, `n
   Return %ab1%(%ab2%(x))
 }

}

cube(x){

 Return x ** 3

}

cuberoot(x){

 Return x ** (1 / 3) 

}</lang>

C

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.

Here goes.

<lang c>#include <stdlib.h>

  1. include <stdio.h>
  2. 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) {

  return v*v*v;

} double functionB(double v) {

  return exp(log(v)/3);

}

/* 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>

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>

  1. include <stdlib.h>
  2. include <string.h>
  3. include <math.h>

typedef double (*f_dbl)(double);

  1. define TAGF (f_dbl)0xdeadbeef
  2. define TAGG (f_dbl)0xbaddecaf

double dummy(double x) { f_dbl f = TAGF; f_dbl g = TAGG; return f(g(x)); }

f_dbl composite(f_dbl f, f_dbl g) { 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; }

double cube(double x) { return x * x * x; }

/* uncomment next line if your math.h doesn't have cbrt() */ /* double cbrt(double x) { return pow(x, 1/3.); } */

int main() { int i; double x;

f_dbl A[3] = { cube, exp, sin }; f_dbl B[3] = { cbrt, log, asin}; /* not sure about availablity of cbrt() */ f_dbl C[3];

for (i = 0; i < 3; i++) C[i] = composite(A[i], B[i]);

for (i = 0; i < 3; i++) { for (x = .2; x <= 1; x += .2) 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

C1(0.2) = 0.2 C1(0.4) = 0.4 C1(0.6) = 0.6 C1(0.8) = 0.8 C1(1) = 1

C2(0.2) = 0.2 C2(0.4) = 0.4 C2(0.6) = 0.6 C2(0.8) = 0.8 C2(1) = 1</lang>

C#

Works with: C sharp version 4.0

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

class Program {

   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);
       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;
                      });
       foreach (var compose in composed)
           Console.WriteLine(compose(0.5));
   }

} </lang>

C++

This uses many C++0x niceties so make sure you put your compiler in the correct mode.

<lang cpp>

  1. include <tr1/functional>
  2. include <vector>
  3. include <iostream>
  4. include <cmath>

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

vector<double(*)(double)> A = {sin, cos, tan, [](double x) { return x*x*x; } }; vector<double(*)(double)> B = {asin, acos, atan, [](double x) { return exp(log(x)/3); } };

template <typename A, typename B, typename... Params> function<A(Params...)> compose(A(*f)(B), B(*g)(Params...)){

   return [=](Params... args){ return f(g(args...)); };

}

  1. define PRINT(x) cout << #x ": " << (x) << endl;

int main() {

   double num = 1 / 3.14159;
   
   PRINT(num);
   PRINT(compose(B[0], A[0])(num));
   PRINT(compose(B[1], A[1])(num));
   PRINT(compose(B[2], A[2])(num));
   PRINT(compose(B[3], A[3])(num));
   auto identity = compose(log10, pow);
   PRINT(identity(10, num));

} </lang>

Clojure

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

(0.5 0.4999999999999999 0.5000000000000001)

CoffeeScript

Translation of: JavaScript

<lang coffeescript>compose = (f, g) ->

   (x) -> 
       f g x

fn = [Math.sin, Math.cos, (x) -> Math.pow(x, 3) ] inv = [Math.asin, Math.acos, (x) -> Math.pow(x, 1/3) ]

do -> for i in [0..2]

       f = compose inv[i], fn[i]
       console.log f 0.5    # 0.5</lang>

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

     for function in (list #'sin  #'cos  #'cube     )
     for inverse  in (list #'asin #'acos #'cube-root)
     for composed = (compose inverse function)
     do (format t "~&(~A ∘ ~A)(~A) = ~A~%"
                inverse
                function
                value 
                (funcall composed value)))</lang>

Output:

<lang lisp>(#<FUNCTION ASIN> ∘ #<FUNCTION SIN>)(0.5) = 0.5 (#<FUNCTION ACOS> ∘ #<FUNCTION COS>)(0.5) = 0.5 (#<FUNCTION CUBE-ROOT> ∘ #<FUNCTION CUBE>)(0.5) = 0.5</lang>

D

D 2.0 version of compose function (template). <lang D>import std.stdio; import std.math;

T delegate(S) compose(T, U, S)(T delegate(U) f, U delegate(S) g) {

   return (S s) { return f(g(s)); };

}</lang>

Compose working both in D 1.0 and 2.0: <lang D>T delegate(S) compose(T, U, S)(T delegate(U) f, U delegate(S) g) {

   struct Wrapper {
       typeof(f) fcp;
       typeof(g) gcp;
       T foobar(S s) { return fcp(gcp(s)); }
   }
   Wrapper* hold = new Wrapper;
   hold.fcp = f;
   hold.gcp = g;
   return &hold.foobar;

}</lang>

Example:

<lang D>import std.stdio, std.math, std.range;

T delegate(S) compose(T, U, S)(T delegate(U) f, U delegate(S) g) {

   return (S s){ return f(g(s)); };

}

void main() {

   // 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); };
   auto fun = [sin,  cos,  cube];
   auto inv = [asin, acos, cbrt];
   foreach (f2; zip(fun, inv))
       writefln("%6.3f", compose(f2[0], f2[1])(0.5));

}</lang> Using the compose() of the std lib, D v2: <lang d>import std.stdio, std.math, std.typetuple, std.functional;

void main() {

   // wrappers needed as not all built-in 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); };
   alias TypeTuple!(sin,  cos,  cube) dir;
   alias TypeTuple!(asin, acos, cbrt) inv;
   foreach (i, f; dir)
       writefln("%6.3f", compose!(f, inv[i])(0.5));

}</lang>

E

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".

The relevant mathematical operations are provided as methods on floats, so the first thing we must do is define them as functions.

<lang e>def sin(x) { return x.sin() } 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) }

def forward := [sin, cos, cube] def reverse := [asin, acos, curt]</lang>

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.

Defining composition. fn params { expr } is shorthand for an anonymous function returning a value. <lang e>def compose(f, g) {

   return fn x { f(g(x)) }

}</lang>

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

x = 0.5, f = <sin>, g = <asin>, compose(<sin>, <asin>)(0.5) = 0.5 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>

Note: def g := reverse[i] is needed here because E as yet has no defined protocol for iterating over collections in parallel. Page for this issue.

Factor

<lang factor>USING: assocs combinators kernel math.functions prettyprint sequences ; IN: rosettacode.first-class-functions

CONSTANT: A { [ sin ] [ cos ] [ 3 ^ ] } 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>

Forth

<lang forth>: compose ( xt1 xt2 -- xt3 )

 >r >r :noname
    r> compile,
    r> compile,
    postpone ;
cube fdup fdup f* f* ;
cuberoot 1e 3e f/ f** ;
table create does> swap cells + @ ;

table fn ' fsin , ' fcos , ' cube , table inverse ' fasin , ' facos , ' cuberoot ,

main
 3 0 do
   i fn i inverse compose  ( xt )
   0.5e execute f.
 loop ;

main \ 0.5 0.5 0.5</lang>

F#

<lang fsharp>open System

let cube x = x ** 3.0 let croot x = x ** (1.0/3.0)

let funclist = [Math.Sin; Math.Cos; cube] let funclisti = [Math.Asin; Math.Acos; croot] let composed = List.map2 (<<) funclist funclisti

let main() = for f in composed do printfn "%f" (f 0.5)

main()</lang>

Output:

0.500000
0.500000
0.500000

Fantom

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 fantom> class FirstClassFns {

 static |Obj -> Obj| compose (|Obj -> Obj| fn1, |Obj -> Obj| fn2)
 {
   return |Obj x -> Obj| { fn2 (fn1 (x)) }
 }
 public static Void main () 
 {
   cube := |Float a -> Float| { a * a * a }
   cbrt := |Float a -> Float| { a.pow(1/3f) }
   |Float->Float|[] fns := [Float#sin.func, Float#cos.func, cube]
   |Float->Float|[] inv := [Float#asin.func, Float#acos.func, cbrt]
   |Float->Float|[] composed := fns.map |fn, i| { compose(fn, inv[i]) }
   composed.each |fn| { echo (fn(0.5f)) }
 }

} </lang>

Output:

0.5
0.4999999999999999
0.5

GAP

<lang gap># Function composition Composition := function(f, g)

 local h;
 h := function(x)
   return f(g(x));
 end;
 return h;

end;

  1. Apply each function in list u, to argument x

ApplyList := function(u, x)

 local i, n, v;
 n := Size(u);
 v := [ ];
 for i in [1 .. n] do
   v[i] := u[i](x);
 od;
 return v;

end;

  1. 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.
  2. For example,
  3. gap> Sqrt(7);
  4. E(28)^3-E(28)^11-E(28)^15+E(28)^19-E(28)^23+E(28)^27
  5. where E(n) is a primitive n-th root of unity

a := [ i -> i + 1, Inverse, Sqrt ];

  1. [ function( i ) ... end, <Operation "InverseImmutable">, <Operation "Sqrt"> ]

b := [ i -> i - 1, Inverse, x -> x*x ];

  1. [ function( i ) ... end, <Operation "InverseImmutable">, function( x ) ... end ]
  1. Compose each couple

z := ListN(a, b, Composition);

  1. Now a test

ApplyList(z, 3); [ 3, 3, 3 ]</lang>

Go

<lang go>package main

import "math" import "fmt"

// user-defined function, per task. Other math functions used are built-in. func cube(x float64) float64 { return math.Pow(x, 3) }

// ffType and compose function taken from Function composition task type ffType func(float64) float64

func compose(f, g ffType) ffType {

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

}

func main() {

   // collection A
   funclist := []ffType{math.Sin, math.Cos, cube}
   // collection B
   funclisti := []ffType{math.Asin, math.Acos, math.Cbrt}
   for i := 0; i < 3; i++ {
       // apply composition and show result
       fmt.Println(compose(funclisti[i], funclist[i])(.5))
   }

}</lang> Output:

0.49999999999999994
0.5
0.5