User:Coderjoe/Sandbox2: Difference between revisions

From Rosetta Code
Content added Content deleted
No edit summary
No edit summary
 
(4 intermediate revisions by the same user not shown)
Line 1: Line 1:
<lang parigp>compose(f,g)={
=={{header|Nemerle}}==
x -> f(g(x))
{{trans|Python}}
};
<lang Nemerle>using System;
using System.Console;
using System.Math;
using Nemerle.Collections.NCollectionsExtensions;


fcf()={
module FirstClassFunc
my(A,B);
{
A=[x->sin(x), x->cos(x), x->x^2];
Main() : void
B=[x->asin(x), x->acos(x), x->sqrt(x)];
{
for(i=1,#A,
def cube = fun (x) {x * x * x};
print(compose(A[i],B[i])(.5))
def croot = fun (x) {Pow(x, 1.0/3.0)};
)
def compose = fun(f, g) {fun (x) {f(g(x))}};
};</lang>
def funcs = [Sin, Cos, cube];
Usage note: In Pari/GP 2.4.3 the vectors can be written as
def ifuncs = [Asin, Acos, croot];
<lang parigp> A=[sin, cos, x->x^2];
WriteLine($[compose(f, g)(0.5) | (f, g) in ZipLazy(funcs, ifuncs)]);
B=[asin, acos, x->sqrt(x)];</lang>
}
}</lang>

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

=={{header|OCaml}}==
<lang ocaml># let cube x = x ** 3. ;;
val cube : float -> float = <fun>

# let croot x = x ** (1. /. 3.) ;;
val croot : float -> float = <fun>

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

# let funclist = [sin; cos; cube] ;;
val funclist : (float -> float) list = [<fun>; <fun>; <fun>]

# let funclisti = [asin; acos; croot] ;;
val funclisti : (float -> float) list = [<fun>; <fun>; <fun>]

# List.map2 (fun f inversef -> (compose inversef f) 0.5) funclist funclisti ;;
- : float list = [0.5; 0.499999999999999889; 0.5]</lang>

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

Latest revision as of 20:38, 16 July 2011

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