First-class functions: Difference between revisions

m
(Added Delphi example)
imported>Arakov
 
(28 intermediate revisions by 15 users not shown)
Line 23:
 
{{trans|JavaScript}}
<syntaxhighlight lang="actionscript">
<lang ActionScript>
var cube:Function = function(x) {
return Math.pow(x, 3);
Line 44:
}
 
test();</langsyntaxhighlight>
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.
 
<langsyntaxhighlight Adalang="ada">with Ada.Float_Text_IO,
Ada.Integer_Text_IO,
Ada.Text_IO,
Line 111:
end;
end loop;
end First_Class_Functions;</langsyntaxhighlight>
 
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}}
<langsyntaxhighlight lang="aikido">
import math
 
Line 133:
}
 
</syntaxhighlight>
</lang>
 
=={{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.
<langsyntaxhighlight lang="algol68">MODE F = PROC (REAL)REAL;
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</langsyntaxhighlight>
Output:
<pre>+.500000000000000e +0
Line 180:
AppleScript does not have built-in functions like sine or cosine.
 
<langsyntaxhighlight lang="applescript">-- Compose two functions, where each function is
-- 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}</langsyntaxhighlight>
 
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.
 
<langsyntaxhighlight AppleScriptlang="applescript">on run
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:</langsyntaxhighlight>
{{Out}}
<langsyntaxhighlight AppleScriptlang="applescript">{0.5, 0.5, 0.5}</langsyntaxhighlight>
 
=={{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]
<langsyntaxhighlight AutoHotkeylang="autohotkey">#NoEnv
; 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</langsyntaxhighlight>
 
{{Output}}
Line 391 ⟶ 413:
=={{header|Axiom}}==
Using the interpreter:
<langsyntaxhighlight Axiomlang="axiom">fns := [sin$Float, cos$Float, (x:Float):Float +-> x^3]
inv := [asin$Float, acos$Float, (x:Float):Float +-> x^(1/3)]
[(f*g) 0.5 for f in fns for g in inv]</langsyntaxhighlight>
Using the Spad compiler:
<langsyntaxhighlight Axiomlang="axiom">)abbrev package TESTP TestPackage
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])</langsyntaxhighlight>
This would be called using:
<syntaxhighlight lang Axiom="axiom">(fns * inv) 0.5</langsyntaxhighlight>
Output:
<langsyntaxhighlight Axiomlang="axiom">[0.5,0.5,0.5]</langsyntaxhighlight>
 
=={{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.
<langsyntaxhighlight lang="bbcbasic"> REM Create some functions and their inverses:
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%</langsyntaxhighlight>
'''Output:'''
<pre>
Line 452 ⟶ 474:
 
=={{header|Bori}}==
<langsyntaxhighlight lang="bori">double acos (double d) { return Math.acos(d); }
double asin (double d) { return Math.asin(d); }
double cos (double d) { return Math.cos(d); }
Line 477 ⟶ 499:
}
label1.setText(s);
}</langsyntaxhighlight>
Output on Android phone:
<langsyntaxhighlight lang="bori">0.5
0.4999999999999999
0.5000000000000001</langsyntaxhighlight>
 
=={{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.
<langsyntaxhighlight lang="bracmat">( (sqrt=.!arg^1/2)
& (log=.e\L!arg)
& (A=x2d (=.!arg^2) log (=.!arg*pi))
Line 506 ⟶ 545:
& out$((compose$(!F.!G))$3210)
)
)</langsyntaxhighlight>
Output:
<pre>3210
Line 518 ⟶ 557:
Here goes.
 
<langsyntaxhighlight lang="c">#include <stdlib.h>
#include <stdio.h>
#include <math.h>
Line 589 ⟶ 628:
return 0;
}</langsyntaxhighlight>
===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).
<langsyntaxhighlight Clang="c">#include <stdio.h>
#include <stdlib.h>
#include <string.h>
Line 647 ⟶ 686:
}
return 0;
}</langsyntaxhighlight>(Boring) output<syntaxhighlight lang="text">C0(0.2) = 0.2
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</langsyntaxhighlight>
 
=={{header|C sharp|C#}}==
<langsyntaxhighlight lang="csharp">using System;
 
class Program
Line 688 ⟶ 727:
}
}
</syntaxhighlight>
</lang>
 
Output:
Line 698 ⟶ 737:
{{works with|C++11}}
 
<langsyntaxhighlight lang="cpp">
#include <functional>
#include <algorithm>
Line 737 ⟶ 776:
return 0;
}
</syntaxhighlight>
</lang>
 
=={{header|Ceylon}}==
{{works with|Ceylon 1.2.1}}
First, you need to import the numeric module in you module.ceylon file
<langsyntaxhighlight lang="ceylon">module rosetta "1.0.0" {
import ceylon.numeric "1.2.1";
}</langsyntaxhighlight>
And then you can use the math functions in your run.ceylon file
<langsyntaxhighlight lang="ceylon">import ceylon.numeric.float {
 
sin, exp, asin, log
Line 762 ⟶ 801:
print(compose(func, inv)(0.5));
}
}</langsyntaxhighlight>
 
=={{header|Clojure}}==
<langsyntaxhighlight lang="clojure">
(use 'clojure.contrib.math)
(let [fns [#(Math/sin %) #(Math/cos %) (fn [x] (* x x x))]
inv [#(Math/asin %) #(Math/acos %) #(expt % 1/3)]]
(map #(% 0.5) (map #(comp %1 %2) fns inv)))
</syntaxhighlight>
</lang>
Output:
<pre>(0.5 0.4999999999999999 0.5000000000000001)</pre>
Line 776 ⟶ 815:
=={{header|CoffeeScript}}==
{{trans|JavaScript}}
<langsyntaxhighlight lang="coffeescript"># Functions as values of a variable
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]​​​​​​​</langsyntaxhighlight>
Output:
<pre>0.5
Line 795 ⟶ 834:
 
=={{header|Common Lisp}}==
<langsyntaxhighlight lang="lisp">(defun compose (f g) (lambda (x) (funcall f (funcall g x))))
(defun cube (x) (expt x 3))
(defun cube-root (x) (expt x (/ 3)))
Line 807 ⟶ 846:
func
value
(funcall composed value)))</langsyntaxhighlight>
 
Output:
 
<langsyntaxhighlight lang="lisp">(#<FUNCTION ASIN> ∘ #<FUNCTION SIN>)(0.5) = 0.5
(#<FUNCTION ACOS> ∘ #<FUNCTION COS>)(0.5) = 0.5
(#<FUNCTION CUBE-ROOT> ∘ #<FUNCTION CUBE>)(0.5) = 0.5</langsyntaxhighlight>
 
=={{header|D}}==
===Using Standard Compose===
<langsyntaxhighlight lang="d">void main() {
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));
}</langsyntaxhighlight>
{{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.
<langsyntaxhighlight lang="d">void main() {
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));
}</langsyntaxhighlight>
 
=={{header|Dart}}==
<langsyntaxhighlight lang="dart">import 'dart:math' as Math;
cube(x) => x*x*x;
cuberoot(x) => Math.pow(x, 1/3);
Line 863 ⟶ 902:
print(compose(functions[i], inverses[i])(0.5));
}
}</langsyntaxhighlight>
{{out}}
<pre>
Line 874 ⟶ 913:
{{libheader| System.Math}}
{{Trans|C#}}
<syntaxhighlight lang="delphi">
<lang Delphi>
program First_class_functions;
 
Line 950 ⟶ 989:
 
readln;
end.</langsyntaxhighlight>
{{out}}
<pre>0.50
Line 962 ⟶ 1,001:
Using partial application:
 
<langsyntaxhighlight Dyalectlang="dyalect">func apply(fun, x) { y => fun(x, y) }
 
func sum(x, y) { x + y }
 
funclet sum2 = apply(sum, 2)</langsyntaxhighlight>
 
===Store functions in collections===
 
<langsyntaxhighlight Dyalectlang="dyalect">func sum(x, y) { x + y }
func doubleMe(x) { x + x }
 
var arr = []
arr.addAdd(sum)
arr.addAdd(doubleMe)
arr.addAdd(arr.toStringToString)</langsyntaxhighlight>
 
===Use functions as arguments to other functions===
 
<langsyntaxhighlight Dyalectlang="dyalect">func Iterator.filterFilter(pred) {
for x in this when pred(x) {
yield x
Line 986 ⟶ 1,025:
}
 
[1,2,3,4,5].iterIterate().filterFilter(x => x % 2 == 0)</langsyntaxhighlight>
 
===Use functions as return values of other functions===
 
<langsyntaxhighlight Dyalectlang="dyalect">func flip(fun, x, y) {
(y, x) => fun(x, y)
}</langsyntaxhighlight>
 
=={{header|Déjà Vu}}==
<langsyntaxhighlight lang="dejavu">negate:
- 0
 
Line 1,013 ⟶ 1,052:
else:
!print "Something went wrong."
</syntaxhighlight>
</lang>
 
{{out}}
Line 1,025 ⟶ 1,064:
The relevant mathematical operations are provided as methods on floats, so the first thing we must do is define them as functions.
 
<langsyntaxhighlight lang="e">def sin(x) { return x.sin() }
def cos(x) { return x.cos() }
def asin(x) { return x.asin() }
Line 1,033 ⟶ 1,072:
 
def forward := [sin, cos, cube]
def reverse := [asin, acos, curt]</langsyntaxhighlight>
 
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.
<langsyntaxhighlight lang="e">def compose(f, g) {
return fn x { f(g(x)) }
}</langsyntaxhighlight>
 
<langsyntaxhighlight lang="e">? def x := 0.5 \
> for i => f in forward {
> def g := reverse[i]
Line 1,050 ⟶ 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</langsyntaxhighlight>
 
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}}==
<langsyntaxhighlight lang="scheme">
;; adapted from Racket
;; (compose f g h ... ) is a built-in defined as :
Line 1,071 ⟶ 1,110:
0.4999999999999999
0.5
</syntaxhighlight>
</lang>
 
=={{header|Ela}}==
Translation of Haskell:
 
<langsyntaxhighlight lang="ela">open number //sin,cos,asin,acos
open list //zipWith
 
Line 1,085 ⟶ 1,124:
funclisti = [asin, acos, croot]
 
zipWith (\f inversef -> (inversef << f) 0.5) funclist funclisti</langsyntaxhighlight>
 
Function (<<) is defined in standard prelude as:
 
<langsyntaxhighlight lang="ela">(<<) f g x = f (g x)</langsyntaxhighlight>
 
Output (calculations are performed on 32-bit floats):
 
<langsyntaxhighlight lang="ela">[0.5,0.5,0.499999989671302]</langsyntaxhighlight>
 
=={{header|Elena}}==
ELENA 56.0x :
<langsyntaxhighlight lang="elena">import system'routines;
import system'math;
import extensions'routines;
Line 1,114 ⟶ 1,153:
fs.zipBy(gs, (f,g => 0.5r.compose(f,g)))
.forEach:(printingLn)
}</langsyntaxhighlight>
{{out}}
<pre>
Line 1,124 ⟶ 1,163:
 
=={{header|Elixir}}==
<langsyntaxhighlight lang="elixir">defmodule First_class_functions do
def task(val) do
as = [&:math.sin/1, &:math.cos/1, fn x -> x * x * x end]
Line 1,137 ⟶ 1,176:
end
 
First_class_functions.task(0.5)</langsyntaxhighlight>
 
{{out}}
Line 1,147 ⟶ 1,186:
 
=={{header|Erlang}}==
<syntaxhighlight lang="erlang">
<lang Erlang>
-module( first_class_functions ).
 
Line 1,164 ⟶ 1,203:
 
square_inverse( X ) -> math:sqrt( X ).
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 1,174 ⟶ 1,213:
 
=={{header|F_Sharp|F#}}==
<langsyntaxhighlight lang="fsharp">open System
 
let cube x = x ** 3.0
Line 1,185 ⟶ 1,224:
let main() = for f in composed do printfn "%f" (f 0.5)
 
main()</langsyntaxhighlight>
 
Output:
Line 1,194 ⟶ 1,233:
=={{header|Factor}}==
The constants A and B consist of arrays containing quotations (aka anonymous functions).
<langsyntaxhighlight lang="factor">USING: assocs combinators kernel math.functions prettyprint sequences ;
IN: rosettacode.first-class-functions
 
Line 1,204 ⟶ 1,243:
: test-fcf ( -- )
0.5 A B compose-all
[ call( x -- y ) ] with map . ;</langsyntaxhighlight>
{{out}}
<pre>{ 0.5 0.4999999999999999 0.5 }</pre>
Line 1,212 ⟶ 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.
 
<langsyntaxhighlight lang="fantom">
class FirstClassFns
{
Line 1,232 ⟶ 1,271:
}
}
</syntaxhighlight>
</lang>
 
Output:
Line 1,242 ⟶ 1,281:
 
=={{header|Forth}}==
<langsyntaxhighlight lang="forth">: compose ( xt1 xt2 -- xt3 )
>r >r :noname
r> compile,
Line 1,263 ⟶ 1,302:
loop ;
 
main \ 0.5 0.5 0.5</langsyntaxhighlight>
 
=={{header|FreeBASIC}}==
Like C, FreeBASIC doesn't have first class functions so I've contented myself by translating their code:
{{trans|C}}
<langsyntaxhighlight lang="freebasic">' FB 1.05.0 Win64
 
#Include "crt/math.bi" '' include math functions in C runtime library
Line 1,340 ⟶ 1,379:
Print
Print "Press any key to quit"
Sleep</langsyntaxhighlight>
 
{{out}}
Line 1,353 ⟶ 1,392:
 
=={{header|GAP}}==
<langsyntaxhighlight lang="gap"># Function composition
Composition := function(f, g)
local h;
Line 1,388 ⟶ 1,427:
# Now a test
ApplyList(z, 3);
[ 3, 3, 3 ]</langsyntaxhighlight>
 
=={{header|Go}}==
<langsyntaxhighlight lang="go">package main
 
import "math"
Line 1,417 ⟶ 1,456:
fmt.Println(compose(funclisti[i], funclist[i])(.5))
}
}</langsyntaxhighlight>
Output:
<pre>
Line 1,427 ⟶ 1,466:
=={{header|Groovy}}==
Solution:
<langsyntaxhighlight lang="groovy">def compose = { f, g -> { x -> f(g(x)) } }</langsyntaxhighlight>
 
Test program:
<langsyntaxhighlight lang="groovy">def cube = { it * it * it }
def cubeRoot = { it ** (1/3) }
 
Line 1,437 ⟶ 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) })</langsyntaxhighlight>
 
Output:
Line 1,444 ⟶ 1,483:
 
=={{header|Haskell}}==
<langsyntaxhighlight lang="haskell">cube :: Floating a => a -> a
cube x = x ** 3.0
 
Line 1,461 ⟶ 1,500:
 
main :: IO ()
main = print $ zipWith (\f i -> f . i $ 0.5) funclist invlist </langsyntaxhighlight>
{{output}}
<pre>[0.5,0.4999999999999999,0.5000000000000001]</pre>
Line 1,467 ⟶ 1,506:
=={{header|Icon}} and {{header|Unicon}}==
The Unicon solution can be modified to work in Icon. See [[Function_composition#Icon_and_Unicon]].
<langsyntaxhighlight Uniconlang="unicon">link compose
procedure main(arglist)
 
Line 1,483 ⟶ 1,522:
procedure cuberoot(x)
return x ^ (1./3)
end</langsyntaxhighlight>
Please refer to See [[Function_composition#Icon_and_Unicon]] for 'compose'.
 
Line 1,498 ⟶ 1,537:
 
However, here are the basics which were requested:
<langsyntaxhighlight lang="j"> sin=: 1&o.
cos=: 2&o.
cube=: ^&3
Line 1,507 ⟶ 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</langsyntaxhighlight>
 
<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</langsyntaxhighlight>
 
===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:
 
<langsyntaxhighlight 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 @:
Line 1,538 ⟶ 1,577:
BA of &> 0.5 NB. Evaluating the compositions at 0.5
0.5 0.5 0.5
</syntaxhighlight>
</lang>
 
=={{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+}}
<langsyntaxhighlight lang="java5">import java.util.ArrayList;
 
public class FirstClass{
Line 1,612 ⟶ 1,651:
System.out.println(Math.pow(Math.sqrt(0.5), 2));
}
}</langsyntaxhighlight>
Output:
<pre>Compositions:
Line 1,624 ⟶ 1,663:
 
{{works with|Java|8+}}
<langsyntaxhighlight lang="java5">import java.util.ArrayList;
import java.util.function.Function;
 
Line 1,650 ⟶ 1,689:
System.out.println(Math.pow(Math.sqrt(0.5), 2));
}
}</langsyntaxhighlight>
 
=={{header|JavaScript}}==
===ES5===
<langsyntaxhighlight lang="javascript">// Functions as values of a variable
var cube = function (x) {
return Math.pow(x, 3);
Line 1,676 ⟶ 1,715:
// Applying the composition to 0.5
console.log(compose(inv[i], fun[i])(0.5));
}</langsyntaxhighlight>
 
===ES6===
<langsyntaxhighlight lang="javascript">// Functions as values of a variable
var cube = x => Math.pow(x, 3);
 
Line 1,695 ⟶ 1,734:
// Applying the composition to 0.5
console.log(compose(inv[i], fun[i])(0.5));
}</langsyntaxhighlight>
 
 
Line 1,702 ⟶ 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}}==
<langsyntaxhighlight Julialang="julia">#!/usr/bin/julia
 
function compose(f::Function, g::Function)
Line 1,714 ⟶ 1,789:
func, inverse = pair
println(compose(func, inverse)(value))
end</langsyntaxhighlight>
 
Output:
Line 1,723 ⟶ 1,798:
 
=={{header|Kotlin}}==
 
<lang scala>// version 1.0.6
<syntaxhighlight lang="kotlin">
import kotlin.math.*
 
fun compose(f: (Double) -> Double, g: (Double) -> Double ): (Double) -> Double = { f(g(it)) }
Line 1,729 ⟶ 1,806:
fun cube(d: Double) = d * d * d
 
fun main(args: Array<String>) {
val listA = listOf(Math::sin, Math::cos, ::cube)
val listB = listOf(Math::asin, Math::acos, Math::cbrt)
val x = 0.5
for (i in 0..2) println(compose(listA[i], listB[i])(x))
}</langsyntaxhighlight>
 
{{out}}
Line 1,745 ⟶ 1,822:
=={{header|Lambdatalk}}==
Tested in [http://epsilonwiki.free.fr/ELS_YAW/?view=p227]
<syntaxhighlight lang="scheme">
<lang Scheme>
{def cube {lambda {:x} {pow :x 3}}}
{def cuberoot {lambda {:x} {pow :x {/ 1 3}}}}
Line 1,760 ⟶ 1,837:
0.49999999999999994
0.5000000000000001
</syntaxhighlight>
</lang>
 
=={{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}}==
<langsyntaxhighlight Lassolang="lasso">#!/usr/bin/lasso9
 
define cube(x::decimal) => {
Line 1,792 ⟶ 1,886:
)
 
/loop</langsyntaxhighlight>
 
Output:
Line 1,802 ⟶ 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:
<langsyntaxhighlight lang="lingo">-- sin, cos and sqrt are built-in, square, asin and acos are user-defined
A = [#sin, #cos, #square]
B = [#asin, #acos, #sqrt]
Line 1,813 ⟶ 1,907:
res = call(f, _movie, testValue)
put res = testValue
end repeat</langsyntaxhighlight>
 
{{out}}
Line 1,823 ⟶ 1,917:
 
User-defined arithmetic functions used in code above:
<langsyntaxhighlight lang="lingo">on square (x)
return x*x
end
Line 1,835 ⟶ 1,929:
on acos (x)
return PI/2 - asin(x)
end</langsyntaxhighlight>
 
=={{header|Lua}}==
<langsyntaxhighlight lang="lua">function compose(f,g) return function(...) return f(g(...)) end end
 
fn = {math.sin, math.cos, function(x) return x^3 end}
Line 1,846 ⟶ 1,940:
local f = compose(v, inv[i])
print(f(0.5))
end</langsyntaxhighlight>
 
Output:
<syntaxhighlight lang="text">0.5
0.5
0.5</langsyntaxhighlight>
 
=={{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">
<lang M2000 Interpreter>
Module CheckFirst {
RAD = lambda -> number/180*pi
Line 1,886 ⟶ 1,980:
}
CheckFirst
</syntaxhighlight>
</lang>
 
=={{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">
<lang Maple>
> A := [ sin, cos, x -> x^3 ]:
> B := [ arcsin, arccos, rcurry( surd, 3 ) ]:
Line 1,898 ⟶ 1,992:
> zip( `@`, B, A )( 2/3 );
[2/3, 2/3, 2/3]
</syntaxhighlight>
</lang>
 
=={{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.
<langsyntaxhighlight Mathematicalang="mathematica">funcs = {Sin, Cos, #^3 &};
funcsi = {ArcSin, ArcCos, #^(1/3) &};
compositefuncs = Composition @@@ Transpose[{funcs, funcsi}];
Table[i[0.666], {i, compositefuncs}]</langsyntaxhighlight>
gives back:
<langsyntaxhighlight Mathematicalang="mathematica">{0.666, 0.666, 0.666}</langsyntaxhighlight>
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:
<langsyntaxhighlight Mathematicalang="mathematica">Composition[f,g,h][x]
f@g@h@x
x//h//g//f</langsyntaxhighlight>
all give back:
<syntaxhighlight lang Mathematica="mathematica">f[g[h[x]]]</langsyntaxhighlight>
 
=={{header|Maxima}}==
<langsyntaxhighlight lang="maxima">a: [sin, cos, lambda([x], x^3)]$
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]</langsyntaxhighlight>
 
=={{header|Mercury}}==
Line 1,930 ⟶ 2,024:
 
===firstclass.m===
<syntaxhighlight lang="mercury">
<lang Mercury>
:- module firstclass.
 
Line 1,948 ⟶ 2,042:
write_list(Results, ", ", write_float, !IO),
write_string("\n", !IO).
</syntaxhighlight>
</lang>
 
===Use and output===
Line 1,959 ⟶ 2,053:
{{works with|min|0.19.3}}
Note <code>concat</code> is what performs the function composition, as functions are lists in min.
<langsyntaxhighlight lang="min">('sin 'cos (3 pow)) =A
('asin 'acos (1 3 / pow)) =B
 
Line 1,966 ⟶ 2,060:
A rest #A
B rest #B
) while</langsyntaxhighlight>
{{out}}
<pre>
Line 1,977 ⟶ 2,071:
 
{{trans|Python}}
<langsyntaxhighlight Nemerlelang="nemerle">using System;
using System.Console;
using System.Math;
Line 1,993 ⟶ 2,087:
WriteLine($[compose(f, g)(0.5) | (f, g) in ZipLazy(funcs, ifuncs)]);
}
}</langsyntaxhighlight>
 
===Use and Output===
Line 2,002 ⟶ 2,096:
 
=={{header|newLISP}}==
<langsyntaxhighlight newLISPlang="newlisp">> (define (compose f g) (expand (lambda (x) (f (g x))) 'f 'g))
(lambda (f g) (expand (lambda (x) (f (g x))) 'f 'g))
> (define (cube x) (pow x 3))
Line 2,014 ⟶ 2,108:
> (map (fn (f g) ((compose f g) 0.5)) functions inverses)
(0.5 0.5 0.5)
</syntaxhighlight>
</lang>
 
=={{header|Nim}}==
{{trans|ES6}} 
 
<lang nim>from math import nil
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 {.procvar.} =
math.pow(x, 3)
 
proc cuberoot(x: float64) : float64 {.procvar.} =
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 {.closure.} =
f(g(x))
return c
 
proc sin(x: float64) : float64 {.procvar.} =
math.sin(x)
 
proc asin(x: float64) : float64 {.procvar.}=
proc acos(x: float64) : float64 =
math.arcsin(x)
proc cos(x: float64) : float64 {.procvar.} =
math.cos(x)
proc acos(x: float64) : float64 {.procvar.} =
math.arccos(x)
 
var fun = @[sin, math.cos, cube]
var inv = @[asinMF64 math.arcsin, acos, cuberoot]
 
for i in 0..2:
echo $compose(inv[i], fun[i])(0.5)</langsyntaxhighlight>
Output:
<pre>0.5
Line 2,051 ⟶ 2,153:
 
=={{header|Objeck}}==
<langsyntaxhighlight lang="objeck">use Collection.Generic;
 
lambdas Func {
Line 2,076 ⟶ 2,178:
func(13.5)->Get()->PrintLine();
}
}</langsyntaxhighlight>
 
=={{header|OCaml}}==
<langsyntaxhighlight lang="ocaml"># let cube x = x ** 3. ;;
val cube : float -> float = <fun>
 
Line 2,095 ⟶ 2,197:
 
# List.map2 (fun f inversef -> (compose inversef f) 0.5) funclist funclisti ;;
- : float list = [0.5; 0.499999999999999889; 0.5]</langsyntaxhighlight>
 
=={{header|Octave}}==
<langsyntaxhighlight lang="octave">function r = cube(x)
r = x.^3;
endfunction
Line 2,113 ⟶ 2,215:
for i = 1:3
disp(compose(f1{i}, f2{i})(.5))
endfor</langsyntaxhighlight>
 
{{Out}}
Line 2,121 ⟶ 2,223:
 
=={{header|Oforth}}==
<langsyntaxhighlight Oforthlang="oforth">: compose(f, g) #[ g perform f perform ] ;
 
[ #cos, #sin, #[ 3 pow ] ] [ #acos, #asin, #[ 3 inv powf ] ] zipWith(#compose)
map(#[ 0.5 swap perform ]) conform(#[ 0.5 == ]) println
</syntaxhighlight>
</lang>
{{Out}}
<pre>
Line 2,132 ⟶ 2,234:
 
=={{header|Ol}}==
<langsyntaxhighlight lang="scheme">
; creation of new function from preexisting functions at run-time
(define (compose f g) (lambda (x) (f (g x))))
Line 2,146 ⟶ 2,248:
(define identity (compose (ref collection 2) (ref collection 1)))
(print (identity 11211776))
</syntaxhighlight>
</lang>
 
=={{header|Oz}}==
Line 2,152 ⟶ 2,254:
(To be executed in the Oz OPI, by typing ctl+. ctl+b)
 
<langsyntaxhighlight lang="oz">declare
 
fun {Compose F G}
Line 2,172 ⟶ 2,274:
{Show {{Compose I F} 0.5}}
end
</syntaxhighlight>
</lang>
This will output the following in the Emulator output window
<syntaxhighlight lang="oz">
<lang oz>
0.5
0.5
0.5
</syntaxhighlight>
</lang>
 
=={{header|PARI/GP}}==
{{works with|PARI/GP|2.4.2 and above}}
<langsyntaxhighlight lang="parigp">compose(f,g)={
x -> f(g(x))
};
Line 2,193 ⟶ 2,295:
print(compose(A[i],B[i])(.5))
)
};</langsyntaxhighlight>
Usage note: In Pari/GP 2.4.3 the vectors can be written as
<langsyntaxhighlight lang="parigp"> A=[sin, cos, x->x^2];
B=[asin, acos, x->sqrt(x)];</langsyntaxhighlight>
 
Output:
Line 2,204 ⟶ 2,306:
 
=={{header|Perl}}==
<langsyntaxhighlight lang="perl">use Math::Complex ':trig';
 
sub compose {
Line 2,222 ⟶ 2,324:
print join "\n", map {
compose($flist1[$_], $flist2[$_]) -> (0.5)
} 0..2;</langsyntaxhighlight>
Output:
<pre>0.5
Line 2,230 ⟶ 2,332:
=={{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 hethe 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)-->
<lang Phix>sequence ctable = {}
<span style="color: #004080;">sequence</span> <span style="color: #000000;">ctable</span> <span style="color: #0000FF;">=</span> <span style="color: #0000FF;">{}</span>
function compose(integer f, g)
<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>
ctable = append(ctable,{f,g})
<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>
integer cdx = length(ctable)
<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>
return cdx
<span style="color: #008080;">return</span> <span style="color: #000000;">cdx</span>
end function
<span style="color: #008080;">end</span> <span style="color: #008080;">function</span>
function call_composite(integer cdx, atom x)
<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>
integer {f,g} = ctable[cdx]
<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>
return f(g(x))
<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>
end function
<span style="color: #008080;">end</span> <span style="color: #008080;">function</span>
function plus1(atom x)
<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>
return x+1
<span style="color: #008080;">return</span> <span style="color: #000000;">x</span><span style="color: #0000FF;">+</span><span style="color: #000000;">1</span>
end function
<span style="color: #008080;">end</span> <span style="color: #008080;">function</span>
function halve(atom x)
<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>
return x/2
<span style="color: #008080;">return</span> <span style="color: #000000;">x</span><span style="color: #0000FF;">/</span><span style="color: #000000;">2</span>
end function
<span style="color: #008080;">end</span> <span style="color: #008080;">function</span>
constant m = compose(halve,plus1)
<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>
?call_composite(m,1) -- displays 1
<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>
?call_composite(m,4) -- displays 2.5</lang>
<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,264 ⟶ 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.
 
<langsyntaxhighlight lang="php">$compose = function ($f, $g) {
return function ($x) use ($f, $g) {
return $f($g($x));
Line 2,276 ⟶ 2,380:
$f = $compose($inv[$i], $fn[$i]);
echo $f(0.5), PHP_EOL;
}</langsyntaxhighlight>
 
Output:
Line 2,285 ⟶ 2,389:
 
=={{header|PicoLisp}}==
<langsyntaxhighlight PicoLisplang="picolisp">(load "@lib/math.l")
 
(de compose (F G)
Line 2,301 ⟶ 2,405:
(prinl (format ((compose Inv Fun) 0.5) *Scl)) )
'(sin cos cube)
'(asin acos cubeRoot) )</langsyntaxhighlight>
Output:
<pre>0.500001
Line 2,309 ⟶ 2,413:
=={{header|PostScript}}==
 
<syntaxhighlight lang="ps">
<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,333 ⟶ 2,437:
.5 exch exec ==
} for
</syntaxhighlight>
</lang>
 
=={{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
 
<langsyntaxhighlight Prologlang="prolog">:- use_module(library(lambda)).
 
 
Line 2,362 ⟶ 2,466:
% we display the results
maplist(writeln, R).
</syntaxhighlight>
</lang>
Output :
<pre> ?- first_class.
Line 2,373 ⟶ 2,477:
=={{header|Python}}==
 
<langsyntaxhighlight lang="python">>>> # Some built in functions and their inverses
>>> from math import sin, cos, acos, asin
>>> # Add a user defined function and its inverse
Line 2,387 ⟶ 2,491:
>>> [compose(inversef, f)(.5) for f, inversef in zip(funclist, funclisti)]
[0.5, 0.4999999999999999, 0.5]
>>></langsyntaxhighlight>
 
 
Or, equivalently:
{{Works with|Python|3.7}}
<langsyntaxhighlight lang="python">'''First-class functions'''
 
from math import (acos, cos, asin, sin)
Line 2,450 ⟶ 2,554:
 
if __name__ == '__main__':
main()</langsyntaxhighlight>
{{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}}==
<langsyntaxhighlight Rlang="r">cube <- function(x) x^3
croot <- function(x) x^(1/3)
compose <- function(f, g) function(x){f(g(x))}
Line 2,464 ⟶ 2,669:
for(i in 1:3) {
print(compose(f1[[i]], f2[[i]])(.5))
}</langsyntaxhighlight>
 
{{Out}}
Line 2,473 ⟶ 2,678:
Alternatively:
 
<langsyntaxhighlight Rlang="r">sapply(mapply(compose,f1,f2),do.call,list(.5))</langsyntaxhighlight>
 
{{Out}}
Line 2,479 ⟶ 2,684:
 
=={{header|Racket}}==
<langsyntaxhighlight lang="racket">#lang racket
 
(define (compose f g) (λ (x) (f (g x))))
Line 2,488 ⟶ 2,693:
(for ([f funlist] [i ifunlist])
(displayln ((compose i f) 0.5)))</langsyntaxhighlight>
 
{{out}}
Line 2,499 ⟶ 2,704:
=={{header|Raku}}==
(formerly Perl 6)
Here we use the <tt>Z</tt> ("zipwith") metaoperator to zip the 𝐴 and 𝐵 lists with abuiltin user-definedcomposition compose functionoperator, expressed<tt>∘</tt> as(or an infix operator,just <tt>o</tt>). The <tt>.()</tt> construct invokes the function contained in the <tt>$_</tt> (current topic) variable.
<lang perl6>sub infix:<∘> (&𝑔, &𝑓) { -> \x { 𝑔 𝑓 x } }
 
<syntaxhighlight lang="raku" line>my \𝐴 = &sin, &cos, { $_ ** <3/1> }
my \𝐵 = &asin, &acos, { $_ ** <1/3> }
 
say .(.5) for 𝐴 Z∘ 𝐵</langsyntaxhighlight>
 
Output:
{{output}}
<pre>0.5
0.4999999999999999
0.5
0.5000000000000001
0.5</pre>
</pre>
 
It is not clear why we don't get exactly 0.5, here.
 
Operators, both buildinbuiltin and user-defined, are first class too.
 
<syntaxhighlight lang="raku" perl6line>my @a = 1,2,3;
my @op = &infix:<+>, &infix:<->, &infix:<*>;
for flat @a Z @op -> $v, &op { say 42.&op($v) }</langsyntaxhighlight>
 
{{output}}
Line 2,524 ⟶ 2,732:
=={{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}}
<langsyntaxhighlight REBOLlang="rebol">REBOL [
Title: "First Class Functions"
URL: http://rosettacode.org/wiki/First-class_functions
Line 2,552 ⟶ 2,760:
 
A: next A B: next B ; Advance to next pair.
]</langsyntaxhighlight>
 
=={{header|REXX}}==
Line 2,563 ⟶ 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 &nbsp; '''A''' &nbsp; collection.
<langsyntaxhighlight lang="rexx">/*REXX program demonstrates first─class functions (as a list of the names of functions).*/
A = 'd2x square sin cos' /*a list of functions to demonstrate.*/
B = 'x2d sqrt Asin Acos' /*the inverse functions of above list. */
Line 2,621 ⟶ 2,829:
right(inv@, 3*w)'='left(left('', invV>=0)invV, w)
end /*k*/
return</langsyntaxhighlight>
'''output'''
<pre>
Line 2,670 ⟶ 2,878:
 
=={{header|Ruby}}==
<langsyntaxhighlight lang="ruby">cube = proc{|x| x ** 3}
croot = proc{|x| x ** (1.quo 3)}
compose = proc {|f,g| proc {|x| f[g[x]]}}
Line 2,676 ⟶ 2,884:
invlist = [Math.method(:asin), Math.method(:acos), croot]
 
puts funclist.zip(invlist).map {|f, invf| compose[invf, f][0.5]}</langsyntaxhighlight>
 
{{out}}
Line 2,688 ⟶ 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.
 
<langsyntaxhighlight lang="rust">#![feature(conservative_impl_trait)]
fn main() {
let cube = |x: f64| x.powi(3);
Line 2,711 ⟶ 2,919:
move |x| g(f(x))
 
}</langsyntaxhighlight>
 
=={{header|Scala}}==
<langsyntaxhighlight lang="scala">import math._
 
// functions as values
Line 2,731 ⟶ 2,939:
 
// output results of applying the functions
comp foreach {f => print(f(0.5) + " ")}</langsyntaxhighlight>
Output:
<pre>0.5 0.4999999999999999 0.5000000000000001</pre>
Line 2,737 ⟶ 2,945:
Here's how you could add a composition operator to make that syntax prettier:
 
<langsyntaxhighlight lang="scala">class SweetFunction[B,C](f: B => C) {
def o[A](g: A => B) = (x: A) => f(g(x))
}
Line 2,743 ⟶ 2,951:
 
// now functions can be composed thus
println((cube o cube o cuberoot)(0.5)) </langsyntaxhighlight>-->
 
=={{header|Scheme}}==
<langsyntaxhighlight lang="scheme">(define (compose f g) (lambda (x) (f (g x))))
(define (cube x) (expt x 3))
(define (cube-root x) (expt x (/ 1 3)))
Line 2,761 ⟶ 2,969:
(go (cdr f) (cdr g)))))
 
(go function inverse)</langsyntaxhighlight>
Output:
0.5
Line 2,769 ⟶ 2,977:
=={{header|Sidef}}==
{{trans|Perl}}
<langsyntaxhighlight lang="ruby">func compose(f,g) {
func (*args) {
f(g(args...))
Line 2,783 ⟶ 2,991:
for a,b (flist1 ~Z flist2) {
say compose(a, b)(0.5)
}</langsyntaxhighlight>
{{out}}
<pre>
Line 2,795 ⟶ 3,003:
Compose is already defined in slate as (note the examples in the comment):
 
<langsyntaxhighlight lang="slate">m@(Method traits) ** n@(Method traits)
"Answers a new Method whose effect is that of calling the first method
on the results of the second method applied to whatever arguments are passed.
Line 2,816 ⟶ 3,024:
].
 
#**`er asMethod: #compose: on: {Method traits. Method traits}.</langsyntaxhighlight>
used as:
<langsyntaxhighlight lang="slate">n@(Number traits) cubed [n raisedTo: 3].
n@(Number traits) cubeRoot [n raisedTo: 1 / 3].
define: #forward -> {#cos `er. #sin `er. #cube `er}.
Line 2,824 ⟶ 3,032:
 
define: #composedMethods -> (forward with: reverse collect: #compose: `er).
composedMethods do: [| :m | inform: (m applyWith: 0.5)].</langsyntaxhighlight>
 
=={{header|Smalltalk}}==
{{works with|GNU Smalltalk}}
<langsyntaxhighlight lang="smalltalk">|forward reverse composer compounds|
"commodities"
Number extend [
Line 2,850 ⟶ 3,058:
].
 
compounds do: [ :r | (r value: 0.5) displayNl ].</langsyntaxhighlight>
 
Output:
Line 2,859 ⟶ 3,067:
 
=={{header|Standard ML}}==
<langsyntaxhighlight lang="sml">- fun cube x = Math.pow(x, 3.0);
val cube = fn : real -> real
- fun croot x = Math.pow(x, 1.0 / 3.0);
Line 2,871 ⟶ 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</langsyntaxhighlight>
 
=={{header|Stata}}==
Line 2,877 ⟶ 3,085:
In Mata it's not possible to get the address of a builtin function, so here we define user functions.
 
<langsyntaxhighlight lang="stata">function _sin(x) {
return(sin(x))
}
Line 2,910 ⟶ 3,118:
for(i=1;i<=length(a);i++) {
printf("%10.5f\n",compose(a[i],b[i],0.5))
}</langsyntaxhighlight>
 
=={{header|SuperCollider}}==
<syntaxhighlight lang="supercollider">
<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>
</lang>
 
=={{header|Swift}}==
{{works with|Swift|1.2+}}
<langsyntaxhighlight lang="swift">import Darwin
func compose<A,B,C>(f: (B) -> C, g: (A) -> B) -> (A) -> C {
return { f(g($0)) }
Line 2,928 ⟶ 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) })</langsyntaxhighlight>
{{out}}
<pre>
Line 2,937 ⟶ 3,145:
The following is a transcript of an interactive session:<br>
{{works with|tclsh|8.5}}
<langsyntaxhighlight Tcllang="tcl">% namespace path tcl::mathfunc ;# to import functions like abs() etc.
% proc cube x {expr {$x**3}}
% proc croot x {expr {$x**(1/3.)}}
Line 2,953 ⟶ 3,161:
0.8372297964617733
% {*}$backward [{*}$forward 0.5]
0.5000000000000017</langsyntaxhighlight>
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,964 ⟶ 3,172:
(Note: The names of the inverse functions may not display as intended unless you have the “TI Uni” font.)
 
<langsyntaxhighlight lang="ti89b">Prgm
Local funs,invs,composed,x,i
 
Line 2,980 ⟶ 3,188:
 
DelVar rc_cube,rc_curt © Clean up our globals
EndPrgm</langsyntaxhighlight>
 
=={{header|TXR}}==
Line 2,989 ⟶ 3,197:
<code>chain</code> composes a variable number of functions, but unlike <code>compose</code>, from left to right, not right to left.
 
<langsyntaxhighlight lang="txrlisp">(defvar funlist [list sin
cos
(op expt @1 3)])
Line 2,998 ⟶ 3,206:
 
(each ((f funlist) (i invlist))
(prinl [(chain f i) 0.5]))</langsyntaxhighlight>
 
{{out}}
Line 3,012 ⟶ 3,220:
functions into a single function returning a list, and apply it to the
argument 0.5.
<langsyntaxhighlight Ursalalang="ursala">#import std
#import flo
 
Line 3,020 ⟶ 3,228:
#cast %eL
 
main = (gang (+)*p\functions inverses) 0.5</langsyntaxhighlight>
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 3,033 ⟶ 3,241:
=={{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.
<langsyntaxhighlight ecmascriptlang="wren">var compose = Fn.new { |f, g| Fn.new { |x| f.call(g.call(x)) } }
 
var A = [
Line 3,050 ⟶ 3,258:
for (i in 0..2) {
System.print(compose.call(A[i], B[i]).call(x))
}</langsyntaxhighlight>
 
{{out}}
Line 3,057 ⟶ 3,265:
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.
<langsyntaxhighlight lang="zkl">var a=T(fcn(x){ x.toRad().sin() }, fcn(x){ x.toRad().cos() }, fcn(x){ x*x*x} );
var b=T(fcn(x){ x.asin().toDeg() }, fcn(x){ x.acos().toDeg() }, fcn(x){ x.pow(1.0/3) });
 
Line 3,068 ⟶ 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)</langsyntaxhighlight>
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 3,077 ⟶ 3,312:
{{omit from|PlainTeX}}
{{omit from|PureBasic}}
{{omit from|Scratch}}
{{omit from|TI-83 BASIC|Cannot define functions.}}
 
Anonymous user