First-class functions: Difference between revisions
PascalABC.NET
m (Adding translation notice to NIm solution) |
(PascalABC.NET) |
||
(86 intermediate revisions by 37 users not shown) | |||
Line 1:
{{task|Programming language concepts}}
A language has [[wp:First-class function|first-class functions]] if it can do each of the following without recursively invoking a compiler or interpreter or otherwise [[metaprogramming]]:
Line 15 ⟶ 16:
;Related task:
[[First-class Numbers]]
<br><br>
Line 22 ⟶ 23:
{{trans|JavaScript}}
<syntaxhighlight lang="actionscript">
var cube:Function = function(x) {
return Math.pow(x, 3);
Line 43 ⟶ 44:
}
test();</
Output:
<pre>
Line 55 ⟶ 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 110 ⟶ 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 117 ⟶ 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 132 ⟶ 133:
}
</syntaxhighlight>
=={{header|ALGOL 68}}==
Line 146 ⟶ 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 170 ⟶ 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 179 ⟶ 180:
AppleScript does not have built-in functions like sine or cosine.
<
-- a script object with a call(x) handler.
on compose(f, g)
end compose
script increment
end script
script decrement
end script
script twice
end script
script half
end script
script cube
end script
script cuberoot
end script
Line 229 ⟶ 230:
set answers to {}
repeat with i from 1 to 3
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 244 ⟶ 245:
Once we have a function like mReturn, however, we can readily write higher order functions like '''map''', '''zipWith''' and '''mCompose''' below.
<syntaxhighlight lang
set
set
-- Form a list of three composed function objects,
Line 253 ⟶ 254:
-- application of each composed function (base function composed with inverse) to 0.5
on |λ|(f)
mReturn(f)'s |λ|(0.5)
end |λ|
end script
map(testWithHalf, zipWith(mCompose, fs, afs))
--> {0.5, 0.5, 0.5}
end run
-- Simple composition of two unadorned handlers into
Line 268 ⟶ 269:
on mCompose(f, g)
script
on
mReturn(f)'s
end
end script
end mCompose
Line 276 ⟶ 277:
-- map :: (a -> b) -> [a] -> [b]
on map(f, xs)
set lng to length of xs
set lst to {}
repeat with i from 1 to lng
set end of lst to
end repeat
return lst
end tell
end map
-- Lift 2nd class handler function into 1st class script wrapper
-- mReturn :: Handler -> Script
on mReturn(f)
if class of f is script then
f
else
script
property |λ| : f
end script
end if
end mReturn
-- zipWith :: (a -> b -> c) -> [a] -> [b] -> [c]
on zipWith(f, xs, ys)
set lng to min(length of xs, length of ys)
set lst to {}
tell mReturn(f)
set end of lst to |λ|(item i of xs, item i of ys)
return lst
end tell
end zipWith
-- min :: Ord a => a -> a -> a
on min(x, y)
if y < x then
y
else
end if
on sin:r
Line 334 ⟶ 342:
on acos:r
(do shell script "echo 'a(sqrt(1-" & r & "^2)/" & r & ")' | bc -l") as real
end acos:</syntaxhighlight>
{{Out}}
<syntaxhighlight lang="applescript">{0.5, 0.5, 0.5}</syntaxhighlight>
=={{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>
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 373 ⟶ 400:
Result .= "`n" . Compose(FuncArray1[Index], FuncArray2[Index]).(X)
MsgBox, 0, First-Class Functions, % Result
ExitApp</
{{Output}}
Line 386 ⟶ 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 396 ⟶ 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 438 ⟶ 465:
DIM p% LEN(f$) + 4
$(p%+4) = f$ : !p% = p%+4
= p%</
'''Output:'''
<pre>
Line 447 ⟶ 474:
=={{header|Bori}}==
<
double asin (double d) { return Math.asin(d); }
double cos (double d) { return Math.cos(d); }
Line 472 ⟶ 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 485 ⟶ 529:
The <code>compose</code> function uses macro substitution.
<
& (log=.e\L!arg)
& (A=x2d (=.!arg^2) log (=.!arg*pi))
Line 501 ⟶ 545:
& out$((compose$(!F.!G))$3210)
)
)</
Output:
<pre>3210
Line 513 ⟶ 557:
Here goes.
<
#include <stdio.h>
#include <math.h>
Line 584 ⟶ 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 642 ⟶ 686:
}
return 0;
}</
C0(0.4) = 0.4
C0(0.6) = 0.6
Line 658 ⟶ 702:
C2(0.6) = 0.6
C2(0.8) = 0.8
C2(1) = 1</
=={{header|C sharp|C#}}==
<
class Program
{
static void Main(string[] args)
{
var cube = new Func<double, double>
var croot = new Func<double, double>
var
{
(forward: Math.Sin, backward: Math.Asin),
(forward: Math.Cos, backward: Math.Acos),
(forward: cube, backward: croot)
};
{
Console.WriteLine(
}
}
}
</syntaxhighlight>
Output:
Line 692 ⟶ 737:
{{works with|C++11}}
<
#include <functional>
#include <algorithm>
Line 731 ⟶ 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 756 ⟶ 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 770 ⟶ 815:
=={{header|CoffeeScript}}==
{{trans|JavaScript}}
<
cube = (x) -> Math.pow x, 3
cuberoot = (x) -> Math.pow x, 1 / 3
Line 782 ⟶ 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 789 ⟶ 834:
=={{header|Common Lisp}}==
<
(defun cube (x) (expt x 3))
(defun cube-root (x) (expt x (/ 3)))
Line 801 ⟶ 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 819 ⟶ 864:
foreach (immutable i, f; dir)
writefln("%6.3f", compose!(f, inv[i])(0.5));
}</
{{out}}
<pre> 0.500
Line 827 ⟶ 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 844 ⟶ 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 857 ⟶ 902:
print(compose(functions[i], inverses[i])(0.5));
}
}</
{{out}}
<pre>
Line 864 ⟶ 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
0.50</pre>
=={{header|Dyalect}}==
===Create new functions from preexisting functions at run-time===
Using partial application:
<syntaxhighlight lang="dyalect">func apply(fun, x) { y => fun(x, y) }
func sum(x, y) { x + y }
let sum2 = apply(sum, 2)</syntaxhighlight>
===Store functions in collections===
<syntaxhighlight lang="dyalect">func sum(x, y) { x + y }
func doubleMe(x) { x + x }
var arr = []
arr.Add(sum)
arr.Add(doubleMe)
arr.Add(arr.ToString)</syntaxhighlight>
===Use functions as arguments to other functions===
<syntaxhighlight lang="dyalect">func Iterator.Filter(pred) {
for x in this when pred(x) {
yield x
}
}
[1,2,3,4,5].Iterate().Filter(x => x % 2 == 0)</syntaxhighlight>
===Use functions as return values of other functions===
<syntaxhighlight lang="dyalect">func flip(fun, x, y) {
(y, x) => fun(x, y)
}</syntaxhighlight>
=={{header|Déjà Vu}}==
<
- 0
Line 884 ⟶ 1,052:
else:
!print "Something went wrong."
</syntaxhighlight>
{{out}}
Line 896 ⟶ 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 904 ⟶ 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 921 ⟶ 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 942 ⟶ 1,110:
0.4999999999999999
0.5
</syntaxhighlight>
=={{header|Ela}}==
Translation of Haskell:
<
open list //zipWith
Line 955 ⟶ 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 6.x :
<
{
= f(
}
{
fs
.forEach(printingLn)
}</syntaxhighlight>
{{out}}
<pre>
Line 995 ⟶ 1,163:
=={{header|Elixir}}==
<
def task(val) do
as = [&:math.sin/1, &:math.cos/1, fn x -> x * x * x end]
Line 1,008 ⟶ 1,176:
end
First_class_functions.task(0.5)</
{{out}}
Line 1,018 ⟶ 1,186:
=={{header|Erlang}}==
<syntaxhighlight lang="erlang">
-module( first_class_functions ).
Line 1,035 ⟶ 1,203:
square_inverse( X ) -> math:sqrt( X ).
</syntaxhighlight>
{{out}}
<pre>
Line 1,045 ⟶ 1,213:
=={{header|F_Sharp|F#}}==
<
let cube x = x ** 3.0
Line 1,056 ⟶ 1,224:
let main() = for f in composed do printfn "%f" (f 0.5)
main()</
Output:
Line 1,065 ⟶ 1,233:
=={{header|Factor}}==
The constants A and B consist of arrays containing quotations (aka anonymous functions).
<
IN: rosettacode.first-class-functions
Line 1,075 ⟶ 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,083 ⟶ 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,103 ⟶ 1,271:
}
}
</syntaxhighlight>
Output:
Line 1,113 ⟶ 1,281:
=={{header|Forth}}==
<
>r >r :noname
r> compile,
Line 1,134 ⟶ 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}}
<syntaxhighlight lang="freebasic">' FB 1.05.0 Win64
#Include "crt/math.bi" '' include math functions in C runtime library
' Declare function pointer type
' This implicitly assumes default StdCall calling convention on Windows
Type Class2Func As Function(As Double) As Double
' A couple of functions with the above prototype
Function functionA(v As Double) As Double
Return v*v*v '' cube of v
End Function
Function functionB(v As Double) As Double
Return Exp(Log(v)/3) '' same as cube root of v which would normally be v ^ (1.0/3.0) in FB
End Function
' A function taking a function as an argument
Function function1(f2 As Class2Func, val_ As Double) As Double
Return f2(val_)
End Function
' A function returning a function
Function whichFunc(idx As Long) As Class2Func
Return IIf(idx < 4, @functionA, @functionB)
End Function
' Additional function needed to treat CDecl function pointer as StdCall
' Get compiler warning otherwise
Function cl2(f As Function CDecl(As Double) As Double) As Class2Func
Return CPtr(Class2Func, f)
End Function
' A list of functions
' Using C Runtime library versions of trig functions as it doesn't appear
' to be possible to apply address operator (@) to FB's built-in versions
Dim funcListA(0 To 3) As Class2Func = {@functionA, cl2(@sin_), cl2(@cos_), cl2(@tan_)}
Dim funcListB(0 To 3) As Class2Func = {@functionB, cl2(@asin_), cl2(@acos_), cl2(@atan_)}
' Composing Functions
Function invokeComposed(f1 As Class2Func, f2 As Class2Func, val_ As double) As Double
Return f1(f2(val_))
End Function
Type Composition
As Class2Func f1, f2
End Type
Function compose(f1 As Class2Func, f2 As Class2Func) As Composition Ptr
Dim comp As Composition Ptr = Allocate(SizeOf(Composition))
comp->f1 = f1
comp->f2 = f2
Return comp
End Function
Function callComposed(comp As Composition Ptr, val_ As Double ) As Double
Return comp->f1(comp->f2(val_))
End Function
Dim ix As Integer
Dim c As Composition Ptr
Print "function1(functionA, 3.0) = "; CSng(function1(whichFunc(0), 3.0))
Print
For ix = 0 To 3
c = compose(funcListA(ix), funcListB(ix))
Print "Composition"; ix; "(0.9) = "; CSng(callComposed(c, 0.9))
Next
Deallocate(c)
Print
Print "Press any key to quit"
Sleep</syntaxhighlight>
{{out}}
<pre>
function1(functionA, 3.0) = 27
Composition 0(0.9) = 0.9
Composition 1(0.9) = 0.9
Composition 2(0.9) = 0.9
Composition 3(0.9) = 0.9
</pre>
=={{header|GAP}}==
<
Composition := function(f, g)
local h;
Line 1,157 ⟶ 1,412:
end;
# Inverse and Sqrt are in the built-in library. Note that
# For example,
# gap> Sqrt(7);
Line 1,172 ⟶ 1,427:
# Now a test
ApplyList(z, 3);
[ 3, 3, 3 ]</
=={{header|Go}}==
<
import "math"
Line 1,201 ⟶ 1,456:
fmt.Println(compose(funclisti[i], funclist[i])(.5))
}
}</
Output:
<pre>
Line 1,211 ⟶ 1,466:
=={{header|Groovy}}==
Solution:
<
Test program:
<
def cubeRoot = { it ** (1/3) }
Line 1,221 ⟶ 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,228 ⟶ 1,483:
=={{header|Haskell}}==
<
croot :: Floating a => a -> a
croot x = x ** (1/3)
-- compose already exists in Haskell as the `.` operator
-- compose :: (a -> b) -> (b -> c) -> a -> c
-- compose f g = \x -> g (f x)
funclist :: Floating a => [a -> a]
funclist = [sin, cos, cube ]
invlist :: Floating a => [a -> a]
invlist = [asin, acos, croot]
main :: IO ()
main = print $ zipWith (\f i -> f . i $ 0.5) funclist invlist </syntaxhighlight>
{{output}}
<pre>[0.5,0.4999999999999999,0.5000000000000001]</pre>
=={{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,255 ⟶ 1,522:
procedure cuberoot(x)
return x ^ (1./3)
end</
Please refer to See [[Function_composition#Icon_and_Unicon]] for 'compose'.
Line 1,264 ⟶ 1,531:
=={{header|J}}==
===Explicit version===
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 - for those uncomfortable with this terminology it is best to think of these as type distinctions - the type which appears in data structures and the type which may be applied are distinct though each may be directly derived from the other).
However, here are the basics which were requested:
<
cos=: 2&o.
cube=: ^&3
Line 1,276 ⟶ 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:
<syntaxhighlight lang="j"> train =. (<'`:')(0:`)(,^:)&6 NB. Producing the function train corresponding to the functional `:6
inverse=. (<'^:')(0:`)(,^:)&_1 NB. Producing the function inverse corresponding to the functional ^:_1
compose=. (<'@:')(0:`)(,^:) NB. Producing the function compose corresponding to the functional @:
an =. <@:((,'0') ; ]) NB. Producing the atomic representation of a noun
of =. train@:([ ; an) NB. Evaluating a function for an argument
box =. < @: train"0 NB. Producing a boxed list of the trains of the components
]A =. box (1&o.)`(2&o.)`(^&3) NB. Producing a boxed list containing the Sin, Cos and Cubic functions
┌────┬────┬───┐
│1&o.│2&o.│^&3│
└────┴────┴───┘
]B =. inverse &.> A NB. Producing their inverses
┌────────┬────────┬───────┐
│1&o.^:_1│2&o.^:_1│^&3^:_1│
└────────┴────────┴───────┘
]BA=. B compose &.> A NB. Producing the compositions of the functions and their inverses
┌────────────────┬────────────────┬──────────────┐
│1&o.^:_1@:(1&o.)│2&o.^:_1@:(2&o.)│^&3^:_1@:(^&3)│
└────────────────┴────────────────┴──────────────┘
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,355 ⟶ 1,651:
System.out.println(Math.pow(Math.sqrt(0.5), 2));
}
}</
Output:
<pre>Compositions:
Line 1,367 ⟶ 1,663:
{{works with|Java|8+}}
<
import java.util.function.Function;
Line 1,393 ⟶ 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,419 ⟶ 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,438 ⟶ 1,734:
// Applying the composition to 0.5
console.log(compose(inv[i], fun[i])(0.5));
}</
Line 1,445 ⟶ 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,457 ⟶ 1,789:
func, inverse = pair
println(compose(func, inverse)(value))
end</
Output:
Line 1,464 ⟶ 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)) }
fun cube(d: Double) = d * d * d
fun main() {
val listA = listOf(::sin, ::cos, ::cube)
val listB = listOf(::asin, ::acos, ::cbrt)
val x = 0.5
for (i in 0..2) println(compose(listA[i], listB[i])(x))
}</syntaxhighlight>
{{out}}
<pre>
0.5
0.4999999999999999
0.5000000000000001
</pre>
=={{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}}}}
{def compose {lambda {:f :g :x} {:f {:g :x}}}}
{def fun sin cos cube}
{def inv asin acos cuberoot}
{def display {lambda {:i}
{br}{compose {nth :i {fun}}
{nth :i {inv}} 0.5}}}
{map display {serie 0 2}}
Output:
0.5
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,495 ⟶ 1,886:
)
/loop</
Output:
Line 1,502 ⟶ 1,893:
0.500000
</pre>
=={{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:
<syntaxhighlight lang="lingo">-- sin, cos and sqrt are built-in, square, asin and acos are user-defined
A = [#sin, #cos, #square]
B = [#asin, #acos, #sqrt]
testValue = 0.5
repeat with i = 1 to 3
-- for implementation details of compose() see https://www.rosettacode.org/wiki/Function_composition#Lingo
f = compose(A[i], B[i])
res = call(f, _movie, testValue)
put res = testValue
end repeat</syntaxhighlight>
{{out}}
<pre>
-- 1
-- 1
-- 1
</pre>
User-defined arithmetic functions used in code above:
<syntaxhighlight lang="lingo">on square (x)
return x*x
end
on asin (x)
res = atan(sqrt(x*x/(1-x*x)))
if x<0 then res = -res
return res
end
on acos (x)
return PI/2 - asin(x)
end</syntaxhighlight>
=={{header|Lua}}==
<
fn = {math.sin, math.cos, function(x) return x^3 end}
Line 1,512 ⟶ 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
ASIN = lambda RAD -> {
Read x : x=Round(x,10)
If x>=0 and X<1 Then {
=RAD(abs(2*Round(ATN(x/(1+SQRT(1-x**2))))))
} Else.if x==1 Then {
=RAD(90)
} Else error "asin exit limit"
}
ACOS=lambda ASIN (x) -> PI/2 - ASIN(x)
POW3 = Lambda ->number**3
POW3INV =Lambda ->number**(1/3)
COSRAD =lambda ->Cos(number*180/pi)
SINRAD=lambda ->Sin(number*180/pi)
Composed=lambda (f1, f2) -> {
=lambda f1, f2 (x)->{
=f1(f2(x))
}
}
Dim Base 0, A(3), B(3), C(3)
A(0)=ACOS, ASIN, POW3INV
B(0)=COSRAD, SINRAD, POW3
C(0)=Composed(ACOS, COSRAD), Composed(ASIN, SINRAD), Composed(POW3INV, POW3)
Print $("0.00")
For i=0 To 2 {
Print A(i)(B(i)(.5)), C(i)(.5)
}
}
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,529 ⟶ 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,561 ⟶ 2,024:
===firstclass.m===
<syntaxhighlight lang="mercury">
:- module firstclass.
Line 1,579 ⟶ 2,042:
write_list(Results, ", ", write_float, !IO),
write_string("\n", !IO).
</syntaxhighlight>
===Use and output===
Line 1,586 ⟶ 2,049:
(Limitations of the IEEE floating point representation make the cos/acos pairing lose a little bit of accuracy.)
=={{header|min}}==
{{works with|min|0.19.3}}
Note <code>concat</code> is what performs the function composition, as functions are lists in min.
<syntaxhighlight lang="min">('sin 'cos (3 pow)) =A
('asin 'acos (1 3 / pow)) =B
(A bool) (
0.5 A first B first concat -> puts!
A rest #A
B rest #B
) while</syntaxhighlight>
{{out}}
<pre>
0.5
0.4999999999999999
0.5
</pre>
=={{header|Nemerle}}==
{{trans|Python}}
<
using System.Console;
using System.Math;
Line 1,606 ⟶ 2,087:
WriteLine($[compose(f, g)(0.5) | (f, g) in ZipLazy(funcs, ifuncs)]);
}
}</
===Use and Output===
Line 1,615 ⟶ 2,096:
=={{header|newLISP}}==
<
(lambda (f g) (expand (lambda (x) (f (g x))) 'f 'g))
> (define (cube x) (pow x 3))
Line 1,627 ⟶ 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
0.4999999999999999
0.5</pre>
=={{header|Objeck}}==
<syntaxhighlight lang="objeck">use Collection.Generic;
lambdas Func {
Double : (FloatHolder) ~ FloatHolder
}
class FirstClass {
function : Main(args : String[]) ~ Nil {
vector := Vector->New()<Func2Holder <FloatHolder, FloatHolder> >;
# store functions in collections
vector->AddBack(Func2Holder->New(\Func->Double : (v)
=> v * v)<FloatHolder, FloatHolder>);
# new function from preexisting function at run-time
vector->AddBack(Func2Holder->New(\Func->Double : (v)
=> Float->SquareRoot(v->Get()))<FloatHolder, FloatHolder>);
# process collection
each(i : vector) {
# return value of other functions and pass argument to other function
Show(vector->Get(i)<Func2Holder>->Get()<FloatHolder, FloatHolder>);
};
}
function : Show(func : (FloatHolder) ~ FloatHolder) ~ Nil {
func(13.5)->Get()->PrintLine();
}
}</syntaxhighlight>
=={{header|OCaml}}==
<
val cube : float -> float = <fun>
Line 1,680 ⟶ 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 1,698 ⟶ 2,215:
for i = 1:3
disp(compose(f1{i}, f2{i})(.5))
endfor</
{{Out}}
Line 1,706 ⟶ 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>
1
</pre>
=={{header|Ol}}==
<syntaxhighlight lang="scheme">
; creation of new function from preexisting functions at run-time
(define (compose f g) (lambda (x) (f (g x))))
; storing functions in collection
(define (quad x) (* x x x x))
(define (quad-root x) (sqrt (sqrt x)))
(define collection (tuple quad quad-root))
; use functions as arguments to other functions
; and use functions as return values of other functions
(define identity (compose (ref collection 2) (ref collection 1)))
(print (identity 11211776))
</syntaxhighlight>
=={{header|Oz}}==
Line 1,720 ⟶ 2,254:
(To be executed in the Oz OPI, by typing ctl+. ctl+b)
<
fun {Compose F G}
Line 1,740 ⟶ 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 1,761 ⟶ 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 1,770 ⟶ 2,304:
0.5000000000000000000000000000
0.5000000000000000000000000000</pre>
=={{header|PascalABC.NET}}==
<syntaxhighlight lang="delphi">
function Cube(x: real) := x**3;
function CubeRoot(x: real) := x**(1/3);
function Composition<T>(f1,f2: T -> T): T -> T := x -> f1(f2(x));
begin
var A := Arr(Sin,Cos,Cube);
var B := Arr(ArcSin,ArcCos,CubeRoot);
for var i:=0 to A.Length-1 do
Println(Composition(A[i],B[i])(0.5));
// Build-in composition f1 * f2
foreach var (f1,f2) in A.Zip(B) do
Println((f1 * f2)(0.5));
end.
</syntaxhighlight>
{{out}}
<pre>
0.5
0.5
0.5
0.5
0.5
0.5
</pre>
=={{header|Perl}}==
<
sub compose {
Line 1,790 ⟶ 2,353:
print join "\n", map {
compose($flist1[$_], $flist2[$_]) -> (0.5)
} 0..2;</
Output:
<pre>0.5
Line 1,796 ⟶ 2,359:
0.5</pre>
=={{header|
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 1,827 ⟶ 2,397:
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 1,839 ⟶ 2,409:
$f = $compose($inv[$i], $fn[$i]);
echo $f(0.5), PHP_EOL;
}</
Output:
Line 1,848 ⟶ 2,418:
=={{header|PicoLisp}}==
<
(de compose (F G)
Line 1,864 ⟶ 2,434:
(prinl (format ((compose Inv Fun) 0.5) *Scl)) )
'(sin cos cube)
'(asin acos cubeRoot) )</
Output:
<pre>0.500001
0.499999
0.500000</pre>
=={{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
/acos { dup dup 1. add exch 1. exch sub mul sqrt exch atan } def
/cube { 3 exp } def
/cuberoot { 1. 3. div exp } def
/compose { % f g -> { g f }
[ 3 1 roll exch
% procedures are not executed when encountered directly
% insert an 'exec' after procedures, but not after operators
1 index type /operatortype ne { /exec cvx exch } if
dup type /operatortype ne { /exec cvx } if
] cvx
} def
/funcs [ /sin load /cos load /cube load ] def
/ifuncs [ /asin load /acos load /cuberoot load ] def
0 1 funcs length 1 sub { /i exch def
ifuncs i get funcs i get compose
.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 1,897 ⟶ 2,495:
% we display the results
maplist(writeln, R).
</syntaxhighlight>
Output :
<pre> ?- first_class.
Line 1,908 ⟶ 2,506:
=={{header|Python}}==
<
>>> from math import sin, cos, acos, asin
>>> # Add a user defined function and its inverse
Line 1,922 ⟶ 2,520:
>>> [compose(inversef, f)(.5) for f, inversef in zip(funclist, funclisti)]
[0.5, 0.4999999999999999, 0.5]
>>></
Or, equivalently:
{{Works with|Python|3.7}}
<syntaxhighlight lang="python">'''First-class functions'''
from math import (acos, cos, asin, sin)
from inspect import signature
# main :: IO ()
def main():
'''Composition of several functions.'''
pwr = flip(curry(pow))
fs = [sin, cos, pwr(3.0)]
ifs = [asin, acos, pwr(1 / 3.0)]
print([
f(0.5) for f in
zipWith(compose)(fs)(ifs)
])
# GENERIC FUNCTIONS ------------------------------
# compose (<<<) :: (b -> c) -> (a -> b) -> a -> c
def compose(g):
'''Right to left function composition.'''
return lambda f: lambda x: g(f(x))
# curry :: ((a, b) -> c) -> a -> b -> c
def curry(f):
'''A curried function derived
from an uncurried function.'''
return lambda a: lambda b: f(a, b)
# flip :: (a -> b -> c) -> b -> a -> c
def flip(f):
'''The (curried or uncurried) function f with its
two arguments reversed.'''
if 1 < len(signature(f).parameters):
return lambda a, b: f(b, a)
else:
return lambda a: lambda b: f(b)(a)
# zipWith :: (a -> b -> c) -> [a] -> [b] -> [c]
def zipWith(f):
'''A list constructed by zipping with a
custom function, rather than with the
default tuple constructor.'''
return lambda xs: lambda ys: [
f(a)(b) for (a, b) in zip(xs, ys)
]
if __name__ == '__main__':
main()</syntaxhighlight>
{{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 1,934 ⟶ 2,698:
for(i in 1:3) {
print(compose(f1[[i]], f2[[i]])(.5))
}</
{{Out}}
Line 1,943 ⟶ 2,707:
Alternatively:
<
{{Out}}
Line 1,949 ⟶ 2,713:
=={{header|Racket}}==
<
(define (compose f g) (λ (x) (f (g x))))
Line 1,959 ⟶ 2,722:
(for ([f funlist] [i ifunlist])
(displayln ((compose i f) 0.5)))</syntaxhighlight>
{{out}}
<
0.5
0.4999999999999999
0.5
</
=={{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,000 ⟶ 2,789:
A: next A B: next B ; Advance to next pair.
]</
=={{header|REXX}}==
Line 2,011 ⟶ 2,800:
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,069 ⟶ 2,858:
right(inv@, 3*w)'='left(left('', invV>=0)invV, w)
end /*k*/
return</
'''output'''
<pre>
Line 2,104 ⟶ 2,893:
The reason why '''Asin[sin(n)]''' may not equal '''n''':
Each of the trigonometric functions is periodic in the real part of its argument, running through all its values twice in each interval of <big>2<big><math>
'''Sine''' and '''cosecant''' begin their period at <big>2<big><math>
'''Cosine''' and '''secant''' begin their period at <big>2<big><math>
'''Tangent''' begins its period at <big>2<big><math>
'''Cotangent''' begins its period at <big>2<big><math>
<br>The above text is from the Wikipedia webpage: http://en.wikipedia.org/wiki/Inverse_trigonometric_functions
Line 2,118 ⟶ 2,907:
=={{header|Ruby}}==
<
croot = proc{|x| x ** (1.quo 3)}
compose = proc {|f,g| proc {|x| f[g[x]]}}
Line 2,124 ⟶ 2,913:
invlist = [Math.method(:asin), Math.method(:acos), croot]
puts funclist.zip(invlist).map {|f, invf| compose[invf, f][0.5]}</
{{out}}
Line 2,132 ⟶ 2,921:
0.5
</pre>
=={{header|Rust}}==
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.
<syntaxhighlight lang="rust">#![feature(conservative_impl_trait)]
fn main() {
let cube = |x: f64| x.powi(3);
let cube_root = |x: f64| x.powf(1.0 / 3.0);
let flist : [&Fn(f64) -> f64; 3] = [&cube , &f64::sin , &f64::cos ];
let invlist: [&Fn(f64) -> f64; 3] = [&cube_root, &f64::asin, &f64::acos];
let result = flist.iter()
.zip(&invlist)
.map(|(f,i)| compose(f,i)(0.5))
.collect::<Vec<_>>();
println!("{:?}", result);
}
fn compose<'a, F, G, T, U, V>(f: F, g: G) -> impl 'a + Fn(T) -> V
where F: 'a + Fn(T) -> U,
G: 'a + Fn(U) -> V,
{
move |x| g(f(x))
}</syntaxhighlight>
=={{header|Scala}}==
<
// functions as values
Line 2,151 ⟶ 2,968:
// output results of applying the functions
comp foreach {f => print(f(0.5) + " ")}</
Output:
<pre>0.5 0.4999999999999999 0.5000000000000001</pre>
Line 2,157 ⟶ 2,974:
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,163 ⟶ 2,980:
// 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,181 ⟶ 2,998:
(go (cdr f) (cdr g)))))
(go function inverse)</
Output:
0.5
Line 2,189 ⟶ 3,006:
=={{header|Sidef}}==
{{trans|Perl}}
<
func (*args) {
f(g(args...))
}
}
var cube = func(a) { a.pow(3) }
var croot = func(a) { a.root(3) }
var flist1 = [
var flist2 = [
for a,b (flist1
say compose(
}</
{{out}}
<pre>
0.5
0.5
0.5
</pre>
Line 2,215 ⟶ 3,032:
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,236 ⟶ 3,053:
].
#**`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,244 ⟶ 3,061:
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,270 ⟶ 3,087:
].
compounds do: [ :r | (r value: 0.5) displayNl ].</
Output:
Line 2,279 ⟶ 3,096:
=={{header|Standard ML}}==
<
val cube = fn : real -> real
- fun croot x = Math.pow(x, 1.0 / 3.0);
Line 2,291 ⟶ 3,108:
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}}==
In Mata it's not possible to get the address of a builtin function, so here we define user functions.
<syntaxhighlight lang="stata">function _sin(x) {
return(sin(x))
}
function _asin(x) {
return(asin(x))
}
function _cos(x) {
return(cos(x))
}
function _acos(x) {
return(acos(x))
}
function cube(x) {
return(x*x*x)
}
function cuberoot(x) {
return(sign(x)*abs(x)^(1/3))
}
function compose(f,g,x) {
return((*f)((*g)(x)))
}
a=&_sin(),&_cos(),&cube()
b=&_asin(),&_acos(),&cuberoot()
for(i=1;i<=length(a);i++) {
printf("%10.5f\n",compose(a[i],b[i],0.5))
}</syntaxhighlight>
=={{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,301 ⟶ 3,165:
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,310 ⟶ 3,174:
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,326 ⟶ 3,190:
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,337 ⟶ 3,201:
(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,353 ⟶ 3,217:
DelVar rc_cube,rc_curt © Clean up our globals
EndPrgm</
=={{header|TXR}}==
Line 2,362 ⟶ 3,226:
<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,371 ⟶ 3,235:
(each ((f funlist) (i invlist))
(prinl [(chain f i) 0.5]))</
{{out}}
Line 2,385 ⟶ 3,249:
functions into a single function returning a list, and apply it to the
argument 0.5.
<
#import flo
Line 2,393 ⟶ 3,257:
#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,403 ⟶ 3,267:
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,413 ⟶ 3,332:
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,422 ⟶ 3,341:
{{omit from|PlainTeX}}
{{omit from|PureBasic}}
{{omit from|Scratch}}
{{omit from|TI-83 BASIC|Cannot define functions.}}
[[Category:Functions and subroutines]]
|