Anonymous user
First-class functions: Difference between revisions
m
→{{header|Elena}}
imported>Arakov |
|||
(32 intermediate revisions by 16 users not shown) | |||
Line 23:
{{trans|JavaScript}}
<syntaxhighlight lang="actionscript">
var cube:Function = function(x) {
return Math.pow(x, 3);
Line 44:
}
test();</
Output:
<pre>
Line 56:
Even if the example below solves the task, there are some limitations to how dynamically you can create, store and use functions in Ada, so it is debatable if Ada really has first class functions.
<
Ada.Integer_Text_IO,
Ada.Text_IO,
Line 111:
end;
end loop;
end First_Class_Functions;</
It is bad style (but an explicit requirement in the task description) to put the functions and their inverses in separate arrays rather than keeping each pair in a record and then having an array of that record type.
Line 118:
{{incomplete|Aikido|Fails to demonstrate that the result of applying the composition of each function in A and its inverse in B to a value, is the original value}}
{{trans|Javascript}}
<
import math
Line 133:
}
</syntaxhighlight>
=={{header|ALGOL 68}}==
Line 147:
violates standard '''ALGOL 68''''s scoping rules. [[ALGOL 68G]] warns about this during
parsing, and then - if run out of scope - rejects during runtime.
<
OP ** = (REAL x, power)REAL: exp(ln(x)*power);
Line 171:
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</
Output:
<pre>+.500000000000000e +0
Line 180:
AppleScript does not have built-in functions like sine or cosine.
<
-- a script object with a call(x) handler.
on compose(f, g)
Line 235:
call(0.5)
end repeat
answers -- Result: {0.5, 0.5, 0.5}</
Putting math libraries aside for the moment (we can always shell out to bash functions like '''bc'''), a deeper issue is that the architectural position of functions in the AppleScript type system is simply a little too incoherent and second class to facilitate really frictionless work with first-class functions. (This is clearly not what AppleScript was originally designed for).
Line 245:
Once we have a function like mReturn, however, we can readily write higher order functions like '''map''', '''zipWith''' and '''mCompose''' below.
<
set fs to {sin_, cos_, cube_}
Line 342:
on acos:r
(do shell script "echo 'a(sqrt(1-" & r & "^2)/" & r & ")' | bc -l") as real
end acos:</
{{Out}}
<
=={{header|Arturo}}==
<syntaxhighlight lang="rebol">cube: function [x] -> x^3
croot: function [x] -> x^(1//3)
names: ["sin/asin", "cos/acos", "cube/croot"]
funclist: @[var 'sin, var 'cos, var 'cube]
invlist: @[var 'asin, var 'acos, var 'croot]
num: 0.5
loop 0..2 'f [
result: call funclist\[f] @[num]
print [names\[f] "=>" call invlist\[f] @[result]]
]</syntaxhighlight>
{{out}}
<pre>sin/asin => 0.5
cos/acos => 0.4999999999999999
cube/croot => 0.5</pre>
=={{header|AutoHotkey}}==
By '''just me'''. [http://ahkscript.org/boards/viewtopic.php?f=17&t=1363&p=16454#p16454 Forum Post]
<
; Set the floating-point precision
SetFormat, Float, 0.15
Line 378 ⟶ 400:
Result .= "`n" . Compose(FuncArray1[Index], FuncArray2[Index]).(X)
MsgBox, 0, First-Class Functions, % Result
ExitApp</
{{Output}}
Line 391 ⟶ 413:
=={{header|Axiom}}==
Using the interpreter:
<
inv := [asin$Float, acos$Float, (x:Float):Float +-> x^(1/3)]
[(f*g) 0.5 for f in fns for g in inv]</
Using the Spad compiler:
<
TestPackage(T:SetCategory) : with
_*: (List((T->T)),List((T->T))) -> (T -> List T)
Line 401 ⟶ 423:
import MappingPackage3(T,T,T)
fs * gs ==
((x:T):(List T) +-> [(f*g) x for f in fs for g in gs])</
This would be called using:
<syntaxhighlight lang
Output:
<
=={{header|BBC BASIC}}==
{{works with|BBC BASIC for Windows}}
Strictly speaking you cannot return a ''function'', but you can return a ''function pointer'' which allows the task to be implemented.
<
DEF FNsin(a) = SIN(a)
DEF FNasn(a) = ASN(a)
Line 443 ⟶ 465:
DIM p% LEN(f$) + 4
$(p%+4) = f$ : !p% = p%+4
= p%</
'''Output:'''
<pre>
Line 452 ⟶ 474:
=={{header|Bori}}==
<
double asin (double d) { return Math.asin(d); }
double cos (double d) { return Math.cos(d); }
Line 477 ⟶ 499:
}
label1.setText(s);
}</
Output on Android phone:
<
0.4999999999999999
0.5000000000000001</
=={{header|BQN}}==
BQN has full support for first class functions in the context of this wiki page. A more detailed article on BQN's implementation of functional programming is discussed [https://mlochbaum.github.io/BQN/doc/functional.html here].
<code>∘</code> (Atop) is used here to compose the two lists of functions given. Higher order functions are then used to apply the functions on a value. There is a slight change in value due to floating point inaccuracy.
BQN has provisions to invert builtin functions using <code>⁼</code> (Undo), and that can also be used for this demonstration, if we remove the block function (<code>funsB ← {𝕏⁼}¨ funsA</code>).
<syntaxhighlight lang="bqn">funsA ← ⟨⋆⟜2,-,•math.Sin,{𝕩×3}⟩
funsB ← ⟨√,-,•math.Asin,{𝕩÷3}⟩
comp ← funsA {𝕎∘𝕏}¨ funsB
•Show comp {𝕎𝕩}¨<0.5</syntaxhighlight>
<syntaxhighlight lang="bqn">⟨ 0.5000000000000001 0.5 0.5 0.5 ⟩</syntaxhighlight>
[https://mlochbaum.github.io/BQN/try.html#code=ZnVuc0Eg4oaQIOKfqOKLhuKfnDIsLSzigKJtYXRoLlNpbix78J2VqcOXM33in6kKZnVuc0Ig4oaQIOKfqOKImiwtLOKAom1hdGguQXNpbix78J2VqcO3M33in6kKCmNvbXAg4oaQIGZ1bnNBIHvwnZWO4oiY8J2Vj33CqCBmdW5zQgoK4oCiU2hvdyBjb21wIHvwnZWO8J2VqX3CqDwwLjU= Try It!]
=={{header|Bracmat}}==
Line 490 ⟶ 529:
The <code>compose</code> function uses macro substitution.
<
& (log=.e\L!arg)
& (A=x2d (=.!arg^2) log (=.!arg*pi))
Line 506 ⟶ 545:
& out$((compose$(!F.!G))$3210)
)
)</
Output:
<pre>3210
Line 518 ⟶ 557:
Here goes.
<
#include <stdio.h>
#include <math.h>
Line 589 ⟶ 628:
return 0;
}</
===Non-portable function body duplication===
Following code generates true functions at run time. Extremely unportable, and [http://en.wikipedia.org/wiki/Considered_harmful 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).
<
#include <stdlib.h>
#include <string.h>
Line 647 ⟶ 686:
}
return 0;
}</
C0(0.4) = 0.4
C0(0.6) = 0.6
Line 663 ⟶ 702:
C2(0.6) = 0.6
C2(0.8) = 0.8
C2(1) = 1</
=={{header|C sharp|C#}}==
<
class Program
Line 688 ⟶ 727:
}
}
</syntaxhighlight>
Output:
Line 698 ⟶ 737:
{{works with|C++11}}
<
#include <functional>
#include <algorithm>
Line 737 ⟶ 776:
return 0;
}
</syntaxhighlight>
=={{header|Ceylon}}==
{{works with|Ceylon 1.2.1}}
First, you need to import the numeric module in you module.ceylon file
<
import ceylon.numeric "1.2.1";
}</
And then you can use the math functions in your run.ceylon file
<
sin, exp, asin, log
Line 762 ⟶ 801:
print(compose(func, inv)(0.5));
}
}</
=={{header|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)))
</syntaxhighlight>
Output:
<pre>(0.5 0.4999999999999999 0.5000000000000001)</pre>
Line 776 ⟶ 815:
=={{header|CoffeeScript}}==
{{trans|JavaScript}}
<
cube = (x) -> Math.pow x, 3
cuberoot = (x) -> Math.pow x, 1 / 3
Line 788 ⟶ 827:
# Applying the composition to 0.5
console.log compose(inv[i], fun[i])(0.5) for i in [0..2]</
Output:
<pre>0.5
Line 795 ⟶ 834:
=={{header|Common Lisp}}==
<
(defun cube (x) (expt x 3))
(defun cube-root (x) (expt x (/ 3)))
Line 807 ⟶ 846:
func
value
(funcall composed value)))</
Output:
<
(#<FUNCTION ACOS> ∘ #<FUNCTION COS>)(0.5) = 0.5
(#<FUNCTION CUBE-ROOT> ∘ #<FUNCTION CUBE>)(0.5) = 0.5</
=={{header|D}}==
===Using Standard Compose===
<
import std.stdio, std.math, std.typetuple, std.functional;
Line 825 ⟶ 864:
foreach (immutable i, f; dir)
writefln("%6.3f", compose!(f, inv[i])(0.5));
}</
{{out}}
<pre> 0.500
Line 833 ⟶ 872:
===Defining Compose===
Here we need wrappers because the standard functions have different signatures (eg pure/nothrow). Same output.
<
import std.stdio, std.math, std.range;
Line 850 ⟶ 889:
foreach (f, g; [sin, cos, cube].zip([asin, acos, cbrt]))
writefln("%6.3f", compose(f, g)(0.5));
}</
=={{header|Dart}}==
<
cube(x) => x*x*x;
cuberoot(x) => Math.pow(x, 1/3);
Line 863 ⟶ 902:
print(compose(functions[i], inverses[i])(0.5));
}
}</
{{out}}
<pre>
Line 870 ⟶ 909:
0.5000000000000001
</pre>
=={{header|Delphi}}==
{{libheader| System.SysUtils}}
{{libheader| System.Math}}
{{Trans|C#}}
<syntaxhighlight lang="delphi">
program First_class_functions;
{$APPTYPE CONSOLE}
uses
System.SysUtils,
System.Math;
type
TFunctionTuple = record
forward, backward: TFunc<Double, Double>;
procedure Assign(forward, backward: TFunc<Double, Double>);
end;
TFunctionTuples = array of TFunctionTuple;
var
cube, croot, fsin, fcos, faSin, faCos: TFunc<Double, Double>;
FunctionTuples: TFunctionTuples;
ft: TFunctionTuple;
{ TFunctionTuple }
procedure TFunctionTuple.Assign(forward, backward: TFunc<Double, Double>);
begin
self.forward := forward;
self.backward := backward;
end;
begin
cube :=
function(x: Double): Double
begin
result := x * x * x;
end;
croot :=
function(x: Double): Double
begin
result := Power(x, 1 / 3.0);
end;
fsin :=
function(x: Double): Double
begin
result := Sin(x);
end;
fcos :=
function(x: Double): Double
begin
result := Cos(x);
end;
faSin :=
function(x: Double): Double
begin
result := ArcSin(x);
end;
faCos :=
function(x: Double): Double
begin
result := ArcCos(x);
end;
SetLength(FunctionTuples, 3);
FunctionTuples[0].Assign(fsin, faSin);
FunctionTuples[1].Assign(fcos, faCos);
FunctionTuples[2].Assign(cube, croot);
for ft in FunctionTuples do
Writeln(ft.backward(ft.forward(0.5)):2:2);
readln;
end.</syntaxhighlight>
{{out}}
<pre>
0.50
0.50</pre>
=={{header|Dyalect}}==
Line 902 ⟶ 1,001:
Using partial application:
<
func sum(x, y) { x + y }
===Store functions in collections===
<
func doubleMe(x) { x + x }
var arr = []
arr.
arr.
arr.
===Use functions as arguments to other functions===
<
for x in this when pred(x) {
yield x
Line 926 ⟶ 1,025:
}
[1,2,3,4,5].
===Use functions as return values of other functions===
<
(y, x) => fun(x, y)
}</
=={{header|Déjà Vu}}==
<syntaxhighlight lang="dejavu">negate:
- 0
set :A [ @++ $ @negate @-- ]
set :B [ @-- $ @++ @negate ]
test n:
for i range 0 -- len A:
if /= n call compose @B! i @A! i n:
return false
true
test to-num !prompt "Enter a number: "
if:
!print "f^-1(f(x)) = x"
else:
!print "Something went wrong."
</syntaxhighlight>
{{out}}
<pre>Enter a number: 23
f^-1(f(x)) = x</pre>
=={{header|E}}==
Line 940 ⟶ 1,064:
The relevant mathematical operations are provided as methods on floats, so the first thing we must do is define them as functions.
<
def cos(x) { return x.cos() }
def asin(x) { return x.asin() }
Line 948 ⟶ 1,072:
def forward := [sin, cos, cube]
def reverse := [asin, acos, curt]</
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.
<
return fn x { f(g(x)) }
}</
<
> for i => f in forward {
> def g := reverse[i]
Line 965 ⟶ 1,089:
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</
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|EchoLisp}}==
<
;; adapted from Racket
;; (compose f g h ... ) is a built-in defined as :
Line 986 ⟶ 1,110:
0.4999999999999999
0.5
</syntaxhighlight>
=={{header|Ela}}==
Translation of Haskell:
<
open list //zipWith
Line 999 ⟶ 1,124:
funclisti = [asin, acos, croot]
zipWith (\f inversef -> (inversef << f) 0.5) funclist funclisti</
Function (<<) is defined in standard prelude as:
<
Output (calculations are performed on 32-bit floats):
<
=={{header|Elena}}==
ELENA
<
import system'math;
import extensions'routines;
Line 1,029 ⟶ 1,153:
fs.zipBy(gs, (f,g => 0.5r.compose(f,g)))
.forEach
}</
{{out}}
<pre>
Line 1,039 ⟶ 1,163:
=={{header|Elixir}}==
<
def task(val) do
as = [&:math.sin/1, &:math.cos/1, fn x -> x * x * x end]
Line 1,052 ⟶ 1,176:
end
First_class_functions.task(0.5)</
{{out}}
Line 1,062 ⟶ 1,186:
=={{header|Erlang}}==
<syntaxhighlight lang="erlang">
-module( first_class_functions ).
Line 1,079 ⟶ 1,203:
square_inverse( X ) -> math:sqrt( X ).
</syntaxhighlight>
{{out}}
<pre>
Line 1,089 ⟶ 1,213:
=={{header|F_Sharp|F#}}==
<
let cube x = x ** 3.0
Line 1,100 ⟶ 1,224:
let main() = for f in composed do printfn "%f" (f 0.5)
main()</
Output:
Line 1,109 ⟶ 1,233:
=={{header|Factor}}==
The constants A and B consist of arrays containing quotations (aka anonymous functions).
<
IN: rosettacode.first-class-functions
Line 1,119 ⟶ 1,243:
: test-fcf ( -- )
0.5 A B compose-all
[ call( x -- y ) ] with map . ;</
{{out}}
<pre>{ 0.5 0.4999999999999999 0.5 }</pre>
Line 1,127 ⟶ 1,251:
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.
<
class FirstClassFns
{
Line 1,147 ⟶ 1,271:
}
}
</syntaxhighlight>
Output:
Line 1,157 ⟶ 1,281:
=={{header|Forth}}==
<
>r >r :noname
r> compile,
Line 1,178 ⟶ 1,302:
loop ;
main \ 0.5 0.5 0.5</
=={{header|FreeBASIC}}==
Like C, FreeBASIC doesn't have first class functions so I've contented myself by translating their code:
{{trans|C}}
<
#Include "crt/math.bi" '' include math functions in C runtime library
Line 1,254 ⟶ 1,379:
Print
Print "Press any key to quit"
Sleep</
{{out}}
Line 1,267 ⟶ 1,392:
=={{header|GAP}}==
<
Composition := function(f, g)
local h;
Line 1,302 ⟶ 1,427:
# Now a test
ApplyList(z, 3);
[ 3, 3, 3 ]</
=={{header|Go}}==
<
import "math"
Line 1,331 ⟶ 1,456:
fmt.Println(compose(funclisti[i], funclist[i])(.5))
}
}</
Output:
<pre>
Line 1,341 ⟶ 1,466:
=={{header|Groovy}}==
Solution:
<
Test program:
<
def cubeRoot = { it ** (1/3) }
Line 1,351 ⟶ 1,476:
println ([funcList, inverseList].transpose().collect { f, finv -> compose(f, finv) }.collect{ it(0.5) })
println ([inverseList, funcList].transpose().collect { finv, f -> compose(finv, f) }.collect{ it(0.5) })</
Output:
Line 1,358 ⟶ 1,483:
=={{header|Haskell}}==
<
cube x = x ** 3.0
Line 1,375 ⟶ 1,500:
main :: IO ()
main = print $ zipWith (\f i -> f . i $ 0.5) funclist invlist </
{{output}}
<pre>[0.5,0.4999999999999999,0.5000000000000001]</pre>
Line 1,381 ⟶ 1,506:
=={{header|Icon}} and {{header|Unicon}}==
The Unicon solution can be modified to work in Icon. See [[Function_composition#Icon_and_Unicon]].
<
procedure main(arglist)
Line 1,397 ⟶ 1,522:
procedure cuberoot(x)
return x ^ (1./3)
end</
Please refer to See [[Function_composition#Icon_and_Unicon]] for 'compose'.
Line 1,412 ⟶ 1,537:
However, here are the basics which were requested:
<
cos=: 2&o.
cube=: ^&3
Line 1,421 ⟶ 1,546:
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</
<syntaxhighlight lang="text"> A unqcol 0.5
0.479426 0.877583 0.125 0.25
BA unqcol 0.5
0.5 0.5 0.5 0.5</
===Tacit (unorthodox) version===
In J only adverbs and conjunctions (functionals) can produce verbs (functions)... Unless they are forced to cloak as verbs (functions). (Note that this takes advantage of a bug/feature of the interpreter ; see [http://rosettacode.org/wiki/Closures/Value_capture#Tacit_.28unorthodox.29_version unorthodox tacit] .) The resulting functions (which correspond to functionals) can take and produce functions:
<
inverse=. (<'^:')(0:`)(,^:)&_1 NB. Producing the function inverse corresponding to the functional ^:_1
compose=. (<'@:')(0:`)(,^:) NB. Producing the function compose corresponding to the functional @:
Line 1,452 ⟶ 1,577:
BA of &> 0.5 NB. Evaluating the compositions at 0.5
0.5 0.5 0.5
</syntaxhighlight>
=={{header|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.
{{works with|Java|1.5+}}
<
public class FirstClass{
Line 1,526 ⟶ 1,651:
System.out.println(Math.pow(Math.sqrt(0.5), 2));
}
}</
Output:
<pre>Compositions:
Line 1,538 ⟶ 1,663:
{{works with|Java|8+}}
<
import java.util.function.Function;
Line 1,564 ⟶ 1,689:
System.out.println(Math.pow(Math.sqrt(0.5), 2));
}
}</
=={{header|JavaScript}}==
===ES5===
<
var cube = function (x) {
return Math.pow(x, 3);
Line 1,590 ⟶ 1,715:
// Applying the composition to 0.5
console.log(compose(inv[i], fun[i])(0.5));
}</
===ES6===
<
var cube = x => Math.pow(x, 3);
Line 1,609 ⟶ 1,734:
// Applying the composition to 0.5
console.log(compose(inv[i], fun[i])(0.5));
}</
Line 1,616 ⟶ 1,741:
0.4999999999999999
0.5</pre>
=={{header|jq}}==
{{works with|jq}}
'''Also works with gojq, the Go implementation of jq'''
'''Also works with fq, a Go implementation of a large subset of jq'''
jq does not support functions as "first class objects" in the sense specified in the task description
but it does give near-first-class status to functions and functional expressions, which can
for example, be passed as arguments to functions. In fact, it is quite straightforward, though possibly misleading,
to transcribe the [[#Wren|Wren]] entry to jq, as follows:
<syntaxhighlight lang=jq>
# Apply g first
def compose(f; g): g | f;
def A: [sin, cos, .*.*.];
def B: [asin, acos, pow(.; 1/3) ];
0.5
| range(0;3) as $i
| compose( A[$i]; B[$i] )
</syntaxhighlight>
However this transcription is inefficient because at each iteration (i.e. for each $i), all three components of A and of B are computed.
To avoid this, one would have to ignore A and B, and instead write:
<pre>
0.5
| compose(sin; asin), compose(cos; acos), compose(pow(.;3); pow(.; 1/3))
</pre>
{{output}}
Using gojq:
<pre>
0.5
0.5000000000000001
0.5000000000000001
</pre>
=={{header|Julia}}==
<
function compose(f::Function, g::Function)
Line 1,628 ⟶ 1,789:
func, inverse = pair
println(compose(func, inverse)(value))
end</
Output:
Line 1,635 ⟶ 1,796:
0.5000000000000001
</pre>
=={{header|Kotlin}}==
<syntaxhighlight lang="kotlin">
import kotlin.math.*
fun compose(f: (Double) -> Double, g: (Double) -> Double ): (Double) -> Double = { f(g(it)) }
Line 1,644 ⟶ 1,806:
fun cube(d: Double) = d * d * d
fun main(
val listA = listOf(
val listB = listOf(
val x = 0.5
for (i in 0..2) println(compose(listA[i], listB[i])(x))
}</
{{out}}
Line 1,660 ⟶ 1,822:
=={{header|Lambdatalk}}==
Tested in [http://epsilonwiki.free.fr/ELS_YAW/?view=p227]
<syntaxhighlight lang="scheme">
{def cube {lambda {:x} {pow :x 3}}}
{def cuberoot {lambda {:x} {pow :x {/ 1 3}}}}
Line 1,675 ⟶ 1,837:
0.49999999999999994
0.5000000000000001
</syntaxhighlight>
=={{header|Lang}}==
<syntaxhighlight lang="lang">
fp.cube = ($x) -> return parser.op($x ** 3)
fp.cuberoot = ($x) -> return parser.op($x ** (1/3))
# fn.concat can be used as compose
&funcs $= [fn.sin, fn.cos, fp.cube]
&invFuncs $= [fn.asin, fn.acos, fp.cuberoot]
$pair
foreach($[pair], fn.arrayZip(&funcs, &invFuncs)) {
parser.op(fn.println(($pair[0] ||| $pair[1])(.5)))
}
</syntaxhighlight>
=={{header|Lasso}}==
<
define cube(x::decimal) => {
Line 1,707 ⟶ 1,886:
)
/loop</
Output:
Line 1,717 ⟶ 1,896:
=={{header|Lingo}}==
Lingo does not support functions as first-class objects. But with the limitations described under [https://www.rosettacode.org/wiki/Function_composition#Lingo Function composition] the task can be solved:
<
A = [#sin, #cos, #square]
B = [#asin, #acos, #sqrt]
Line 1,728 ⟶ 1,907:
res = call(f, _movie, testValue)
put res = testValue
end repeat</
{{out}}
Line 1,738 ⟶ 1,917:
User-defined arithmetic functions used in code above:
<
return x*x
end
Line 1,750 ⟶ 1,929:
on acos (x)
return PI/2 - asin(x)
end</
=={{header|Lua}}==
<
fn = {math.sin, math.cos, function(x) return x^3 end}
Line 1,761 ⟶ 1,940:
local f = compose(v, inv[i])
print(f(0.5))
end</
Output:
<syntaxhighlight lang="text">0.5
0.5
0.5</
=={{header|M2000 Interpreter}}==
Cos, Sin works with degrees, Number pop number from stack of values, so we didn't use a variable like this POW3INV =Lambda (x)->x**(1/3)
<syntaxhighlight lang="m2000 interpreter">
Module CheckFirst {
RAD = lambda -> number/180*pi
Line 1,801 ⟶ 1,980:
}
CheckFirst
</syntaxhighlight>
=={{header|Maple}}==
The composition operator in Maple is denoted by "@". We use "zip" to produce the list of compositions. The cubing procedure and its inverse are each computed.
<syntaxhighlight lang="maple">
> A := [ sin, cos, x -> x^3 ]:
> B := [ arcsin, arccos, rcurry( surd, 3 ) ]:
Line 1,813 ⟶ 1,992:
> zip( `@`, B, A )( 2/3 );
[2/3, 2/3, 2/3]
</syntaxhighlight>
=={{header|Mathematica}} / {{header|Wolfram Language}}==
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.
<
funcsi = {ArcSin, ArcCos, #^(1/3) &};
compositefuncs = Composition @@@ Transpose[{funcs, funcsi}];
Table[i[0.666], {i, compositefuncs}]</
gives back:
<
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:
<
f@g@h@x
x//h//g//f</
all give back:
<syntaxhighlight lang
=={{header|Maxima}}==
<
b: [asin, acos, lambda([x], x^(1/3))]$
compose(f, g) := buildq([f, g], lambda([x], f(g(x))))$
map(lambda([fun], fun(x)), map(compose, a, b));
[x, x, x]</
=={{header|Mercury}}==
Line 1,845 ⟶ 2,024:
===firstclass.m===
<syntaxhighlight lang="mercury">
:- module firstclass.
Line 1,863 ⟶ 2,042:
write_list(Results, ", ", write_float, !IO),
write_string("\n", !IO).
</syntaxhighlight>
===Use and output===
Line 1,874 ⟶ 2,053:
{{works with|min|0.19.3}}
Note <code>concat</code> is what performs the function composition, as functions are lists in min.
<
('asin 'acos (1 3 / pow)) =B
Line 1,881 ⟶ 2,060:
A rest #A
B rest #B
) while</
{{out}}
<pre>
Line 1,892 ⟶ 2,071:
{{trans|Python}}
<
using System.Console;
using System.Math;
Line 1,908 ⟶ 2,087:
WriteLine($[compose(f, g)(0.5) | (f, g) in ZipLazy(funcs, ifuncs)]);
}
}</
===Use and Output===
Line 1,917 ⟶ 2,096:
=={{header|newLISP}}==
<
(lambda (f g) (expand (lambda (x) (f (g x))) 'f 'g))
> (define (cube x) (pow x 3))
Line 1,929 ⟶ 2,108:
> (map (fn (f g) ((compose f g) 0.5)) functions inverses)
(0.5 0.5 0.5)
</syntaxhighlight>
=={{header|Nim}}==
{{trans|ES6}}
Note that when defining a sequence <code>@[a, b, c]</code>, “a” defines the type of the elements. So, if there is an ambiguity, we need to precise the type.
For instance <code>@[math.sin, cos]</code> wouldn’t compile as there exists two “sin” functions, one for “float32” and one for “float64”.
So, we have to write either <code>@[(proc(x: float64): float64]) math.sin, cos]</code> to avoid the ambiguity or make sure there is no ambiguity as regards the first element.
Here, in first sequence, we put in first position our function “sin” defined only for “float64” and in second position the standard one “math.cos”. And in second sequence, we used the type <code>MF64 = proc(x: float64): float64</code> to suppress the ambiguity.
<syntaxhighlight lang="nim">from math import nil # Require qualifier to access functions.
type MF64 = proc(x: float64): float64
proc cube(x: float64) : float64 =
math.pow(x, 3)
proc cuberoot(x: float64) : float64
math.pow(x, 1/3)
proc compose[A](f: proc(x: A): A, g: proc(x: A): A) : (proc(x: A): A) =
proc c(x: A): A
f(g(x))
return c
proc sin(x: float64) : float64
math.sin(x)
proc acos(x: float64) : float64 =
math.arccos(x)
var fun = @[sin, math.cos, cube]
var inv = @[
for i in 0..2:
echo
Output:
<pre>0.5
Line 1,966 ⟶ 2,153:
=={{header|Objeck}}==
<
lambdas Func {
Line 1,991 ⟶ 2,178:
func(13.5)->Get()->PrintLine();
}
}</
=={{header|OCaml}}==
<
val cube : float -> float = <fun>
Line 2,010 ⟶ 2,197:
# List.map2 (fun f inversef -> (compose inversef f) 0.5) funclist funclisti ;;
- : float list = [0.5; 0.499999999999999889; 0.5]</
=={{header|Octave}}==
<
r = x.^3;
endfunction
Line 2,028 ⟶ 2,215:
for i = 1:3
disp(compose(f1{i}, f2{i})(.5))
endfor</
{{Out}}
Line 2,036 ⟶ 2,223:
=={{header|Oforth}}==
<
[ #cos, #sin, #[ 3 pow ] ] [ #acos, #asin, #[ 3 inv powf ] ] zipWith(#compose)
map(#[ 0.5 swap perform ]) conform(#[ 0.5 == ]) println
</syntaxhighlight>
{{Out}}
<pre>
Line 2,047 ⟶ 2,234:
=={{header|Ol}}==
<
; creation of new function from preexisting functions at run-time
(define (compose f g) (lambda (x) (f (g x))))
Line 2,061 ⟶ 2,248:
(define identity (compose (ref collection 2) (ref collection 1)))
(print (identity 11211776))
</syntaxhighlight>
=={{header|Oz}}==
Line 2,067 ⟶ 2,254:
(To be executed in the Oz OPI, by typing ctl+. ctl+b)
<
fun {Compose F G}
Line 2,087 ⟶ 2,274:
{Show {{Compose I F} 0.5}}
end
</syntaxhighlight>
This will output the following in the Emulator output window
<syntaxhighlight lang="oz">
0.5
0.5
0.5
</syntaxhighlight>
=={{header|PARI/GP}}==
{{works with|PARI/GP|2.4.2 and above}}
<
x -> f(g(x))
};
Line 2,108 ⟶ 2,295:
print(compose(A[i],B[i])(.5))
)
};</
Usage note: In Pari/GP 2.4.3 the vectors can be written as
<
B=[asin, acos, x->sqrt(x)];</
Output:
Line 2,119 ⟶ 2,306:
=={{header|Perl}}==
<
sub compose {
Line 2,137 ⟶ 2,324:
print join "\n", map {
compose($flist1[$_], $flist2[$_]) -> (0.5)
} 0..2;</
Output:
<pre>0.5
0.5
0.5</pre>
=={{header|Phix}}==
There is not really any direct support for this sort of thing in Phix, but it is all pretty trivial to manage explicitly.<br>
In the following, as it stands, constant m cannot be used the same way as a routine_id, and a standard routine_id cannot be passed to the first argument of call_composite, but tagging ctable entries so that you know exactly what to do with them does not sound difficult to me.
<!--<syntaxhighlight lang="phix">(phixonline)-->
<span style="color: #004080;">sequence</span> <span style="color: #000000;">ctable</span> <span style="color: #0000FF;">=</span> <span style="color: #0000FF;">{}</span>
<span style="color: #008080;">function</span> <span style="color: #000000;">compose</span><span style="color: #0000FF;">(</span><span style="color: #004080;">integer</span> <span style="color: #000000;">f</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">g</span><span style="color: #0000FF;">)</span>
<span style="color: #000000;">ctable</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">append</span><span style="color: #0000FF;">(</span><span style="color: #000000;">ctable</span><span style="color: #0000FF;">,{</span><span style="color: #000000;">f</span><span style="color: #0000FF;">,</span><span style="color: #000000;">g</span><span style="color: #0000FF;">})</span>
<span style="color: #004080;">integer</span> <span style="color: #000000;">cdx</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">length</span><span style="color: #0000FF;">(</span><span style="color: #000000;">ctable</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">return</span> <span style="color: #000000;">cdx</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">function</span>
<span style="color: #008080;">function</span> <span style="color: #000000;">call_composite</span><span style="color: #0000FF;">(</span><span style="color: #004080;">integer</span> <span style="color: #000000;">cdx</span><span style="color: #0000FF;">,</span> <span style="color: #004080;">atom</span> <span style="color: #000000;">x</span><span style="color: #0000FF;">)</span>
<span style="color: #004080;">integer</span> <span style="color: #0000FF;">{</span><span style="color: #000000;">f</span><span style="color: #0000FF;">,</span><span style="color: #000000;">g</span><span style="color: #0000FF;">}</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">ctable</span><span style="color: #0000FF;">[</span><span style="color: #000000;">cdx</span><span style="color: #0000FF;">]</span>
<span style="color: #008080;">return</span> <span style="color: #000000;">f</span><span style="color: #0000FF;">(</span><span style="color: #000000;">g</span><span style="color: #0000FF;">(</span><span style="color: #000000;">x</span><span style="color: #0000FF;">))</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">function</span>
<span style="color: #008080;">function</span> <span style="color: #000000;">plus1</span><span style="color: #0000FF;">(</span><span style="color: #004080;">atom</span> <span style="color: #000000;">x</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">return</span> <span style="color: #000000;">x</span><span style="color: #0000FF;">+</span><span style="color: #000000;">1</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">function</span>
<span style="color: #008080;">function</span> <span style="color: #000000;">halve</span><span style="color: #0000FF;">(</span><span style="color: #004080;">atom</span> <span style="color: #000000;">x</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">return</span> <span style="color: #000000;">x</span><span style="color: #0000FF;">/</span><span style="color: #000000;">2</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">function</span>
<span style="color: #008080;">constant</span> <span style="color: #000000;">m</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">compose</span><span style="color: #0000FF;">(</span><span style="color: #000000;">halve</span><span style="color: #0000FF;">,</span><span style="color: #000000;">plus1</span><span style="color: #0000FF;">)</span>
<span style="color: #0000FF;">?</span><span style="color: #000000;">call_composite</span><span style="color: #0000FF;">(</span><span style="color: #000000;">m</span><span style="color: #0000FF;">,</span><span style="color: #000000;">1</span><span style="color: #0000FF;">)</span> <span style="color: #000080;font-style:italic;">-- displays 1</span>
<span style="color: #0000FF;">?</span><span style="color: #000000;">call_composite</span><span style="color: #0000FF;">(</span><span style="color: #000000;">m</span><span style="color: #0000FF;">,</span><span style="color: #000000;">4</span><span style="color: #0000FF;">)</span> <span style="color: #000080;font-style:italic;">-- displays 2.5</span>
<!--</syntaxhighlight>-->
=={{header|PHP}}==
Line 2,203 ⟶ 2,368:
Non-anonymous functions can only be passed around by name, but the syntax for calling them is identical in both cases. Object or class methods require a different syntax involving array pseudo-types and <tt>call_user_func</tt>. So PHP could be said to have ''some'' first class functionality.
<
return function ($x) use ($f, $g) {
return $f($g($x));
Line 2,215 ⟶ 2,380:
$f = $compose($inv[$i], $fn[$i]);
echo $f(0.5), PHP_EOL;
}</
Output:
Line 2,224 ⟶ 2,389:
=={{header|PicoLisp}}==
<
(de compose (F G)
Line 2,240 ⟶ 2,405:
(prinl (format ((compose Inv Fun) 0.5) *Scl)) )
'(sin cos cube)
'(asin acos cubeRoot) )</
Output:
<pre>0.500001
Line 2,248 ⟶ 2,413:
=={{header|PostScript}}==
<syntaxhighlight lang="ps">
% PostScript has 'sin' and 'cos', but not these
/asin { dup dup 1. add exch 1. exch sub mul sqrt atan } def
Line 2,272 ⟶ 2,437:
.5 exch exec ==
} for
</syntaxhighlight>
=={{header|Prolog}}==
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
<
Line 2,301 ⟶ 2,466:
% we display the results
maplist(writeln, R).
</syntaxhighlight>
Output :
<pre> ?- first_class.
Line 2,312 ⟶ 2,477:
=={{header|Python}}==
<
>>> from math import sin, cos, acos, asin
>>> # Add a user defined function and its inverse
Line 2,326 ⟶ 2,491:
>>> [compose(inversef, f)(.5) for f, inversef in zip(funclist, funclisti)]
[0.5, 0.4999999999999999, 0.5]
>>></
Or, equivalently:
{{Works with|Python|3.7}}
<
from math import (acos, cos, asin, sin)
Line 2,389 ⟶ 2,554:
if __name__ == '__main__':
main()</
{{Out}}
<pre>[0.49999999999999994, 0.5000000000000001, 0.5000000000000001]</pre>
=={{header|Quackery}}==
Preamble. Quackery has first class functions, but it doesn't have floating point numbers.
However, as it is implemented in Python, we can drop down into Python for that functionality, and represent floating point numbers as strings in Quackery. This code implements that, with a light sprinkle of syntactic sugar for the compiler so we can use <code>f 0.5</code> rather than <code>$ "0.5"</code> to represent the floating point number <code>0.5</code>
<syntaxhighlight lang="Quackery"> [ $ \
try:
float(string_from_stack())
except:
to_stack(False)
else:
to_stack(True)
\ python ] is isfloat ( $ --> b )
[ nextword
dup isfloat not if
[ $ '"f" needs to be followed by a number.'
message put bail ]
' [ ' ] swap nested join
nested swap dip join ] builds f ( [ $ --> [ $ )
[ $ \
import math
a = string_from_stack()
a = str(math.sin(float(a)))
string_to_stack(a) \ python ] is sin ( $ --> $ )
[ $ \
import math
a = string_from_stack()
a = str(math.asin(float(a)))
string_to_stack(a) \ python ] is asin ( $ --> $ )
[ $ \
import math
a = string_from_stack()
a = str(math.cos(float(a)))
string_to_stack(a) \ python ] is cos ( $ --> $ )
[ $ \
import math
a = string_from_stack()
a = str(math.acos(float(a)))
string_to_stack(a) \ python ] is acos ( $ --> $ )
[ $ \
a = string_from_stack()
b = string_from_stack()
c = str(float(b) * float(a))
string_to_stack(c) \ python ] is f* ( $ $ --> $ )
[ $ \
a = string_from_stack()
b = string_from_stack()
c = str(float(b) / float(a))
string_to_stack(c) \ python ] is f/ ( $ $ --> $ )
[ $ \
a = string_from_stack()
b = string_from_stack()
c = str(float(b) ** float(a))
string_to_stack(c) \ python ] is f** ( $ $ --> $ )</syntaxhighlight>
…and now the task…
<syntaxhighlight lang="Quackery"> [ dup dup f* f* ] is cubed ( $ --> $ )
[ f 1 f 3 f/ f** ] is cuberoot ( $ --> $ )
[ table sin cos cubed ] is A ( n --> [ )
[ table asin acos cuberoot ] is B ( n --> [ )
[ dip nested nested join ] is compose ( x x --> [ )
[ dup dip A B compose do ] is ->A->B-> ( f n --> f )
' [ f 0.5 f 1.234567 ]
witheach
[ do 3 times
[ dup echo$
say " -> "
i^ A echo
say " -> "
i^ B echo
say " -> "
dup i^ ->A->B-> echo$
cr ]
drop cr ]</syntaxhighlight>
{{out}}
<pre>0.5 -> sin -> asin -> 0.5
0.5 -> cos -> acos -> 0.4999999999999999
0.5 -> cubed -> cuberoot -> 0.5
1.234567 -> sin -> asin -> 1.234567
1.234567 -> cos -> acos -> 1.234567
1.234567 -> cubed -> cuberoot -> 1.234567</pre>
=={{header|R}}==
<
croot <- function(x) x^(1/3)
compose <- function(f, g) function(x){f(g(x))}
Line 2,403 ⟶ 2,669:
for(i in 1:3) {
print(compose(f1[[i]], f2[[i]])(.5))
}</
{{Out}}
Line 2,412 ⟶ 2,678:
Alternatively:
<
{{Out}}
Line 2,418 ⟶ 2,684:
=={{header|Racket}}==
<
(define (compose f g) (λ (x) (f (g x))))
Line 2,427 ⟶ 2,693:
(for ([f funlist] [i ifunlist])
(displayln ((compose i f) 0.5)))</
{{out}}
Line 2,435 ⟶ 2,701:
0.5
</pre>
=={{header|Raku}}==
(formerly Perl 6)
Here we use the <tt>Z</tt> ("zipwith") metaoperator to zip the 𝐴 and 𝐵 lists with builtin composition operator, <tt>∘</tt> (or just <tt>o</tt>). The <tt>.()</tt> construct invokes the function contained in the <tt>$_</tt> (current topic) variable.
<syntaxhighlight lang="raku" line>my \𝐴 = &sin, &cos, { $_ ** <3/1> }
my \𝐵 = &asin, &acos, { $_ ** <1/3> }
say .(.5) for 𝐴 Z∘ 𝐵</syntaxhighlight>
{{output}}
<pre>0.5
0.4999999999999999
0.5000000000000001
</pre>
It is not clear why we don't get exactly 0.5, here.
Operators, both builtin and user-defined, are first class too.
<syntaxhighlight lang="raku" line>my @a = 1,2,3;
my @op = &infix:<+>, &infix:<->, &infix:<*>;
for flat @a Z @op -> $v, &op { say 42.&op($v) }</syntaxhighlight>
{{output}}
<pre>43
40
126</pre>
=={{header|REBOL}}==
{{incomplete|REBOL|Fails to demonstrate that the result of applying the composition of each function in A and its inverse in B to a value, is the original value}}
<
Title: "First Class Functions"
URL: http://rosettacode.org/wiki/First-class_functions
Line 2,466 ⟶ 2,760:
A: next A B: next B ; Advance to next pair.
]</
=={{header|REXX}}==
Line 2,477 ⟶ 2,771:
These six functions (generally) only support non-negative integers, so a special test in the program below only
<br>supplies appropriate integers when testing the first function listed in the '''A''' collection.
<
A = 'd2x square sin cos' /*a list of functions to demonstrate.*/
B = 'x2d sqrt Asin Acos' /*the inverse functions of above list. */
Line 2,535 ⟶ 2,829:
right(inv@, 3*w)'='left(left('', invV>=0)invV, w)
end /*k*/
return</
'''output'''
<pre>
Line 2,584 ⟶ 2,878:
=={{header|Ruby}}==
<
croot = proc{|x| x ** (1.quo 3)}
compose = proc {|f,g| proc {|x| f[g[x]]}}
Line 2,590 ⟶ 2,884:
invlist = [Math.method(:asin), Math.method(:acos), croot]
puts funclist.zip(invlist).map {|f, invf| compose[invf, f][0.5]}</
{{out}}
Line 2,602 ⟶ 2,896:
This solution uses a feature of Nightly Rust that allows us to return a closure from a function without using the extra indirection of a pointer. Stable Rust can also accomplish this challenge -- the only difference being that compose would return a <code>Box<Fn(T) -> V></code> which would result in an extra heap allocation.
<
fn main() {
let cube = |x: f64| x.powi(3);
Line 2,625 ⟶ 2,919:
move |x| g(f(x))
}</
=={{header|Scala}}==
<
// functions as values
Line 2,645 ⟶ 2,939:
// output results of applying the functions
comp foreach {f => print(f(0.5) + " ")}</
Output:
<pre>0.5 0.4999999999999999 0.5000000000000001</pre>
Line 2,651 ⟶ 2,945:
Here's how you could add a composition operator to make that syntax prettier:
<
def o[A](g: A => B) = (x: A) => f(g(x))
}
Line 2,657 ⟶ 2,951:
// now functions can be composed thus
println((cube o cube o cuberoot)(0.5)) </
=={{header|Scheme}}==
<
(define (cube x) (expt x 3))
(define (cube-root x) (expt x (/ 1 3)))
Line 2,675 ⟶ 2,969:
(go (cdr f) (cdr g)))))
(go function inverse)</
Output:
0.5
Line 2,683 ⟶ 2,977:
=={{header|Sidef}}==
{{trans|Perl}}
<
func (*args) {
f(g(args...))
Line 2,697 ⟶ 2,991:
for a,b (flist1 ~Z flist2) {
say compose(a, b)(0.5)
}</
{{out}}
<pre>
Line 2,709 ⟶ 3,003:
Compose is already defined in slate as (note the examples in the comment):
<
"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.
Line 2,730 ⟶ 3,024:
].
#**`er asMethod: #compose: on: {Method traits. Method traits}.</
used as:
<
n@(Number traits) cubeRoot [n raisedTo: 1 / 3].
define: #forward -> {#cos `er. #sin `er. #cube `er}.
Line 2,738 ⟶ 3,032:
define: #composedMethods -> (forward with: reverse collect: #compose: `er).
composedMethods do: [| :m | inform: (m applyWith: 0.5)].</
=={{header|Smalltalk}}==
{{works with|GNU Smalltalk}}
<
"commodities"
Number extend [
Line 2,764 ⟶ 3,058:
].
compounds do: [ :r | (r value: 0.5) displayNl ].</
Output:
Line 2,773 ⟶ 3,067:
=={{header|Standard ML}}==
<
val cube = fn : real -> real
- fun croot x = Math.pow(x, 1.0 / 3.0);
Line 2,785 ⟶ 3,079:
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</
=={{header|Stata}}==
Line 2,791 ⟶ 3,085:
In Mata it's not possible to get the address of a builtin function, so here we define user functions.
<
return(sin(x))
}
Line 2,824 ⟶ 3,118:
for(i=1;i<=length(a);i++) {
printf("%10.5f\n",compose(a[i],b[i],0.5))
}</
=={{header|SuperCollider}}==
<syntaxhighlight lang="supercollider">
a = [sin(_), cos(_), { |x| x ** 3 }];
b = [asin(_), acos(_), { |x| x ** (1/3) }];
c = a.collect { |x, i| x <> b[i] };
c.every { |x| x.(0.5) - 0.5 < 0.00001 }
</syntaxhighlight>
=={{header|Swift}}==
{{works with|Swift|1.2+}}
<
func compose<A,B,C>(f: (B) -> C, g: (A) -> B) -> (A) -> C {
return { f(g($0)) }
Line 2,842 ⟶ 3,136:
let funclist = [ { (x: Double) in sin(x) }, { (x: Double) in cos(x) }, { (x: Double) in pow(x, 3) } ]
let funclisti = [ { (x: Double) in asin(x) }, { (x: Double) in acos(x) }, { (x: Double) in cbrt(x) } ]
println(map(zip(funclist, funclisti)) { f, inversef in compose(f, inversef)(0.5) })</
{{out}}
<pre>
Line 2,851 ⟶ 3,145:
The following is a transcript of an interactive session:<br>
{{works with|tclsh|8.5}}
<
% proc cube x {expr {$x**3}}
% proc croot x {expr {$x**(1/3.)}}
Line 2,867 ⟶ 3,161:
0.8372297964617733
% {*}$backward [{*}$forward 0.5]
0.5000000000000017</
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.
Line 2,878 ⟶ 3,172:
(Note: The names of the inverse functions may not display as intended unless you have the “TI Uni” font.)
<
Local funs,invs,composed,x,i
Line 2,894 ⟶ 3,188:
DelVar rc_cube,rc_curt © Clean up our globals
EndPrgm</
=={{header|TXR}}==
Line 2,903 ⟶ 3,197:
<code>chain</code> composes a variable number of functions, but unlike <code>compose</code>, from left to right, not right to left.
<
cos
(op expt @1 3)])
Line 2,912 ⟶ 3,206:
(each ((f funlist) (i invlist))
(prinl [(chain f i) 0.5]))</
{{out}}
Line 2,926 ⟶ 3,220:
functions into a single function returning a list, and apply it to the
argument 0.5.
<
#import flo
Line 2,934 ⟶ 3,228:
#cast %eL
main = (gang (+)*p\functions inverses) 0.5</
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>)
Line 2,944 ⟶ 3,238:
output:
<pre><5.000000e-01,5.000000e-01,5.000000e-01></pre>
=={{header|Wren}}==
In Wren, there is a distinction between functions and methods. Essentially, the former are independent objects which can do all the things required of 'first class functions' and the latter are subroutines which are tied to a particular class. As sin, cos etc. are instance methods of the Num class, we need to wrap them in functions to complete this task.
<syntaxhighlight lang="wren">var compose = Fn.new { |f, g| Fn.new { |x| f.call(g.call(x)) } }
var A = [
Fn.new { |x| x.sin },
Fn.new { |x| x.cos },
Fn.new { |x| x * x * x }
]
var B = [
Fn.new { |x| x.asin },
Fn.new { |x| x.acos },
Fn.new { |x| x.pow(1/3) }
]
var x = 0.5
for (i in 0..2) {
System.print(compose.call(A[i], B[i]).call(x))
}</syntaxhighlight>
{{out}}
<pre>
0.5
0.5
0.5
</pre>
=={{header|XBS}}==
<syntaxhighlight lang="xbs">func cube(x:number):number{
send x^3;
}
func cuberoot(x:number):number{
send x^(1/3);
}
func compose(f:function,g:function):function{
send func(n:number){
send f(g(n));
}
}
const a:[function]=[math.sin,math.cos,cube];
const b:[function]=[math.asin,math.acos,cuberoot];
each a as k,v{
log(compose(v,b[k])(0.5))
}</syntaxhighlight>
{{out}}
<pre>
0.5
0.4999999999999999
0.5000000000000001
</pre>
=={{header|zkl}}==
In zkl, methods bind their instance so something like x.sin is the sine method bound to x (whatever real number x is). eg var a=(30.0).toRad().sin; is a method and a() will always return 0.5 (ie basically a const in this case). Which means you can't just use the word "sin", it has to be used in conjunction with an instance.
<
var b=T(fcn(x){ x.asin().toDeg() }, fcn(x){ x.acos().toDeg() }, fcn(x){ x.pow(1.0/3) });
Line 2,954 ⟶ 3,303:
ab.run(True,5.0); //-->L(5.0,5.0,5.0)
a.run(True,5.0) //-->L(0.0871557,0.996195,125)</
fcomp is the function composition function, fcomp(b,a) returns the function (x)-->b(a(x)). List.run(True,x) is inverse of List.apply/map, it returns a list of list[i](x). The True is to return the result, False is just do it for the side effects.
Line 2,963 ⟶ 3,312:
{{omit from|PlainTeX}}
{{omit from|PureBasic}}
{{omit from|Scratch}}
{{omit from|TI-83 BASIC|Cannot define functions.}}
|