First-class functions/Use numbers analogously: Difference between revisions
First-class functions/Use numbers analogously (view source)
Revision as of 12:05, 4 March 2024
, 3 months agoAdded FreeBASIC
(Adding F#) |
(Added FreeBASIC) |
||
(37 intermediate revisions by 21 users not shown) | |||
Line 21:
<small>To paraphrase the task description: Do what was done before, but with numbers rather than functions</small>
<br><br>
=={{header|11l}}==
{{trans|Python}}
<syntaxhighlight lang="11l">V (x, xi, y, yi) = (2.0, 0.5, 4.0, 0.25)
V z = x + y
V zi = 1.0 / (x + y)
V multiplier = (n1, n2) -> (m -> @=n1 * @=n2 * m)
V numlist = [x, y, z]
V numlisti = [xi, yi, zi]
print(zip(numlist, numlisti).map((n, inversen) -> multiplier(inversen, n)(.5)))</syntaxhighlight>
{{out}}
<pre>
[0.5, 0.5, 0.5]
</pre>
=={{header|Ada}}==
<
procedure Firstclass is
generic
Line 44 ⟶ 61:
end;
end loop;
end Firstclass;</
{{out}}
<pre>5.00000E-01
Line 56 ⟶ 73:
Note: Standard ALGOL 68's scoping rules forbids exporting a '''proc'''[edure] (or '''format''') out of it's scope (closure). Hence this specimen will run on [[ELLA ALGOL 68]], but is non-standard. For a discussion of first-class functions in ALGOL 68 consult [http://www.cs.ru.nl/~kees/home/papers/psi96.pdf "The Making of Algol 68"] - [[wp:Cornelis_H.A._Koster|C.H.A. Koster]] (1993). <!-- Retrieved April 28, 2007 -->
<
x := 2,
xi := 0.5,
Line 77 ⟶ 94:
inv n = inv num list[key];
print ((multiplier(inv n, n)(.5), new line))
OD</
Output:
<pre>
Line 91 ⟶ 108:
The First Class Functions example uses C. H. Lindsey's partial parameterization extension to Algol 68 which implemented in Algol 68G but not in algol68toc.
This example uses an alternative (technically, invalid Algol 68 as the author notes) accepted by algol68toc but not Algol 68G.
=={{header|Arturo}}==
<syntaxhighlight lang="arturo">x: 2.0
xi: 0.5
y: 4.0
yi: 0.25
z: x + y
zi: 1 / z
multiplier: function [m n][
function [a] with [m n][
a*m*n
]
]
couple @[x y z] @[xi yi zi]
| map 'p -> multiplier p\0 p\1
| map => [call & -> 0.5]
| print</syntaxhighlight>
{{out}}
<pre>0.5 0.5 0.5</pre>
=={{header|Axiom}}==
<
(z,zi) := (x+y,1/(x+y))
(numbers,invers) := ([x,y,z],[xi,yi,zi])
multiplier(a:Float,b:Float):(Float->Float) == (m +-> a*b*m)
[multiplier(number,inver) 0.5 for number in numbers for inver in invers]
</
<
Type: List(Float)</
We can also curry functions, possibly with function composition, with the same output as before:
<
[mult(number*inver) 0.5 for number in numbers for inver in invers]
[(mult(number)*mult(inver)) 0.5 for number in numbers for inver in invers]</
Using the Spad code in [[First-class functions#Axiom]], this can be done more economically using:
<
For comparison, [[First-class functions#Axiom]] gave:
<
inv := [asin$Float, acos$Float, (x:Float):Float +-> x^(1/3)]
[(f*g) 0.5 for f in fns for g in inv]
</syntaxhighlight>
- which has the same output.
=={{header|BBC BASIC}}==
{{works with|BBC BASIC for Windows}}
<
x = 2 : xi = 1/2
y = 4 : yi = 0.25
Line 143 ⟶ 184:
DIM p% LEN(f$) + 4
$(p%+4) = f$ : !p% = p%+4
= p%</
'''Output:'''
<pre>
Line 151 ⟶ 192:
</pre>
Compare with the implementation of First-class functions:
<
DEF FNsin(a) = SIN(a)
DEF FNasn(a) = ASN(a)
Line 184 ⟶ 225:
DIM p% LEN(f$) + 4
$(p%+4) = f$ : !p% = p%+4
= p%</
=={{header|C sharp|C#}}==
{{works with|C#|4.0}}
The structure here is exactly the same as the C# entry in [[First-class functions]]. The "var" keyword allows us to use the same initialization code for an array of doubles as an array of functions. Note that variable names have been changed to correspond with the new functionality.
<
using System.Linq;
Line 216 ⟶ 257:
}
}
</syntaxhighlight>
=={{header|C++}}==
<syntaxhighlight lang="cpp">#include <array>
#include <iostream>
int main()
{
double x = 2.0;
double xi = 0.5;
double y = 4.0;
double yi = 0.25;
double z = x + y;
double zi = 1.0 / ( x + y );
const std::array values{x, y, z};
const std::array inverses{xi, yi, zi};
auto multiplier = [](double a, double b)
{
return [=](double m){return a * b * m;};
};
for(size_t i = 0; i < values.size(); ++i)
{
auto new_function = multiplier(values[i], inverses[i]);
double value = new_function(i + 1.0);
std::cout << value << "\n";
}
}
</syntaxhighlight>
{{out}}
<pre>
1
2
3
</pre>
=={{header|Clojure}}==
<
(def xi 0.5)
(def y 4.0)
Line 234 ⟶ 311:
> (for [[n i] (zipmap numbers invers)]
((multiplier n i) 0.5))
(0.5 0.5 0.5)</
For comparison:
<
(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 247 ⟶ 324:
=={{header|Common Lisp}}==
<
#'(lambda (x) (* f g x)))
Line 266 ⟶ 343:
inverse
value
(funcall multiplier value))))</
Output:
Line 276 ⟶ 353:
The code from [[First-class functions]], for comparison:
<
(defun cube (x) (expt x 3))
(defun cube-root (x) (expt x (/ 3)))
Line 288 ⟶ 365:
function
value
(funcall composed value)))</
Output:
Line 297 ⟶ 374:
=={{header|D}}==
<
auto multiplier(double a, double b)
Line 321 ⟶ 398:
writefln("%f * %f * %f == %f", f[i], r[i], 1.0, mult(1));
}
}</
Output:
<pre>2.000000 * 0.500000 * 1.000000 == 1.000000
Line 331 ⟶ 408:
This is written to have identical structure to [[First-class functions#E]], though the variable names are different.
<
def xi := 0.5
def y := 4.0
Line 348 ⟶ 425:
def b := reverse[i]
println(`s = $s, a = $a, b = $b, multiplier($a, $b)($s) = ${multiplier(a, b)(s)}`)
}</
Output:
Line 357 ⟶ 434:
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|Elena}}==
{{trans|C#}}
ELENA
<
import extensions
{
var numlist :=
var numlisti :=
var multiplied := numlist
multiplied
}</syntaxhighlight>
{{out}}
<pre>
Line 387 ⟶ 465:
=={{header|Erlang}}==
<syntaxhighlight lang="erlang">
-module( first_class_functions_use_numbers ).
Line 401 ⟶ 479:
multiplier( N1, N2 ) -> fun(M) -> N1 * N2 * M end.
</syntaxhighlight>
{{out}}
<pre>
Line 410 ⟶ 488:
</pre>
=={{header|F_Sharp|F#}}==
<
let x = 2.0
let xi = 0.5
Line 425 ⟶ 503:
|> List.map ((|>) 0.5)
|> printfn "%A"
</syntaxhighlight>
{{out}}
<pre>
Line 433 ⟶ 511:
=={{header|Factor}}==
Compared to http://rosettacode.org/wiki/First-class_functions, the call to "compose" is replaced with the call to "mutliplier"
<
IN: q
Line 450 ⟶ 528:
: example ( -- )
0.5 A B create-all
[ call( x -- y ) ] with map . ;</
{{out}}
<pre>{ 0.5 0.5 0.5 }</pre>
Line 456 ⟶ 534:
=={{header|Fantom}}==
<
class Main
{
Line 477 ⟶ 555:
}
}
</syntaxhighlight>
The <code>combine</code> function is very similar to the <code>compose</code> function in 'First-class functions'. In both cases a new function is returned:
<
static |Obj -> Obj| compose (|Obj -> Obj| fn1, |Obj -> Obj| fn2)
{
return |Obj x -> Obj| { fn2 (fn1 (x)) }
}
</syntaxhighlight>
=={{header|FreeBASIC}}==
FreeBASIC does not support first-class functions or function closures, which means that you cannot create a function that returns another function or that has a function defined inside it.
However, similar behavior can be achieved with subroutines and global variables.
<syntaxhighlight lang="vbnet">Dim As Double x = 2.0, xi = 0.5
Dim As Double y = 4.0, yi = 0.25
Dim As Double z = x + y, zi = 1.0 / (x + y)
Dim As Double values(2) = {x, y, z}
Dim As Double inverses(2) = {xi, yi, zi}
Dim Shared As Double m = 0.5
Function multiplier(a As Double, d As Double) As Double
Return a * d * m
End Function
For i As Byte = 0 To Ubound(values)
Dim As Double new_function = multiplier(values(i), inverses(i))
Print values(i); " *"; inverses(i); " *"; m; " ="; new_function
Next i
Sleep</syntaxhighlight>
{{out}}
<pre> 2 * 0.5 * 0.5 = 0.5
4 * 0.25 * 0.5 = 0.5
6 * 0.1666666666666667 * 0.5 = 0.5</pre>
=={{header|Go}}==
Line 502 ⟶ 607:
At point C, numbers and their inverses have been multiplied and bound to first class functions. The ordered collection arrays could be modified at this point and the function objects would be unaffected.
<
import "fmt"
Line 537 ⟶ 642:
return n1n2 * m
}
}</
Output:
<pre>
Line 560 ⟶ 665:
[[/Go interface type|This can also be done with an interface type]] rather than the "empty interface" (<code>interface{}</code>) for better type safety and to avoid the <code>eval</code> function and type switch.
<
import "fmt"
Line 607 ⟶ 712:
panic("unsupported multiplier type")
return 0 // never reached
}</
=={{header|Groovy}}==
<
def ε = 0.00000001 // tolerance(epsilon): acceptable level of "wrongness" to account for rounding error
Line 621 ⟶ 726:
}
println()
}</
{{out}}
<pre>2.000 * 0.500 * 1.000 == 1.000
Line 643 ⟶ 748:
=={{header|Haskell}}==
<
where
Line 670 ⟶ 775:
in printf "%f * %f * 0.5 = %f\n" number inverse (new_function 0.5)
mapM_ print_pair pairs
</syntaxhighlight>
This is very close to the first-class functions example, but given as a full Haskell program rather than an interactive session.
Line 681 ⟶ 786:
[[First-class functions]] task solution. The solution here
is simpler and more direct since it handles a specific function definition.
<
procedure main(A)
Line 690 ⟶ 795:
procedure multiplier(n1,n2)
return makeProc { repeat inVal := n1 * n2 * (inVal@&source)[1] }
end</
A sample run:
Line 706 ⟶ 811:
This seems to satisfy the new problem statement:
<
xi =: 0.5
y =: 4.0
Line 716 ⟶ 821:
rev =: xi,yi,zi
multiplier =: 2 : 'm * n * ]'</
An equivalent but perhaps prettier definition of multiplier would be:
<syntaxhighlight lang="j">multiplier=: {{m*n*]}}</syntaxhighlight>
Or, if J's "right bracket is the right identity function" bothers you, you might prefer the slightly more verbose but still equivalent:
<syntaxhighlight lang="j">multiplier=: {{m*n*{{y}}}}</syntaxhighlight>
Example use:
<syntaxhighlight lang="text"> fwd multiplier rev 0.5
0.5 0.5 0.5</
For contrast, here are the final results from [[First-class functions#J]]:
<syntaxhighlight lang="text"> BA unqcol 0.5
0.5 0.5 0.5 0.5</
===Tacit (unorthodox) version===
Although the pseudo-code to generate the numbers can certainly be written (see above [http://rosettacode.org/wiki/First-class_functions/Use_numbers_analogously#Explicit_version Explicit version] ) this is not done for this version because it would destroy part of the analogy (J encourages, from the programming perspective, to process all components at once as opposed to one component at a time). In addition, this version is done in terms of boxed lists of numbers instead of plain list of numbers, again, to preserve the analogy.
<syntaxhighlight lang="text"> multiplier=. train@:((;:'&*') ;~ an@: *)
]A=. 2 ; 4 ; (2 + 4) NB. Corresponds to ]A=. box (1&o.)`(2&o.)`(^&3)
Line 745 ⟶ 858:
└───┴───┴───┘
BA of &> 0.5 NB. Corresponds to BA of &> 0.5 (exactly)
0.5 0.5 0.5</
Please refer to [http://rosettacode.org/wiki/First-class_functions#Tacit_.28unorthodox.29_version First-class functions tacit (unorthodox) version] for the definitions of the functions train, an and of.
=={{header|Java}}==
<syntaxhighlight lang="java">
import java.util.List;
import java.util.function.BiFunction;
import java.util.function.Function;
public class FirstClassFunctionsUseNumbersAnalogously {
public static void main(String[] args) {
final double x = 2.0, xi = 0.5,
y = 4.0, yi = 0.25,
z = x + y, zi = 1.0 / ( x + y );
List<Double> list = List.of( x, y, z );
List<Double> inverseList = List.of( xi, yi, zi );
BiFunction<Double, Double, Function<Double, Double>> multiplier = (a, b) -> product -> a * b * product;
for ( int i = 0; i < list.size(); i++ ) {
Function<Double, Double> multiply = multiplier.apply(list.get(i), inverseList.get(i));
final double argument = (double) ( i + 1 );
System.out.println(multiply.apply(argument));
}
}
}
</syntaxhighlight>
{{ out }}
<pre>
1.0
2.0
3.0
</pre>
=={{header|jq}}==
It may be helpful to compare the following definition of "multiplier" with its Ruby counterpart [[#Ruby|below]]. Whereas the Ruby definition must name all its positional parameters, the jq equivalent is defined as a filter that obtains them implicitly from its input.
<
# zip this and that
def zip(that): [., that] | transpose;
# The task:
Line 771 ⟶ 917:
def multiplier(j): .[0] * .[1] * j;
numlist | zip(invlist) | map( multiplier(0.5) )</
{{out}}
$ jq -n -c -f First_class_functions_Use_numbers_analogously.jq
[0.5,0.5,0.5]
=={{header|JavaScript}}==
<syntaxhighlight lang="javascript">const x = 2.0;
const xi = 0.5;
const y = 4.0;
const yi = 0.25;
const z = x + y;
const zi = 1.0 / (x + y);
const pairs = [[x, xi], [y, yi], [z, zi]];
const testVal = 0.5;
const multiplier = (a, b) => m => a * b * m;
const test = () => {
return pairs.map(([a, b]) => {
const f = multiplier(a, b);
const result = f(testVal);
return `${a} * ${b} * ${testVal} = ${result}`;
});
}
test().join('\n');</syntaxhighlight>
{{out}}
<pre>
2 * 0.5 * 0.5 = 0.5
4 * 0.25 * 0.5 = 0.5
6 * 0.16666666666666666 * 0.5 = 0.5
</pre>
=={{header|Julia}}==
Line 783 ⟶ 957:
In Julia, like Python and R, functions can be treated as like as other Types.
<
y, yi = 4.0, 0.25
z, zi = x + y, 1.0 / ( x + y )
Line 792 ⟶ 966:
numlisti = [xi, yi, zi]
@show collect(multiplier(n, invn)(0.5) for (n, invn) in zip(numlist, numlisti))</
{{out}}
Line 798 ⟶ 972:
=={{header|Kotlin}}==
<
fun multiplier(n1: Double, n2: Double) = { m: Double -> n1 * n2 * m}
Line 815 ⟶ 989:
println("${multiplier(a[i], ai[i])(m)} = multiplier(${a[i]}, ${ai[i]})($m)")
}
}</
{{out}}
Line 825 ⟶ 999:
=={{header|Lua}}==
<syntaxhighlight lang="lua">
-- This function returns another function that
-- keeps n1 and n2 in scope, ie. a closure.
Line 845 ⟶ 1,019:
print(v .. " * " .. invs[k] .. " * 0.5 = " .. new_function(0.5))
end
</syntaxhighlight>
{{out}}
<pre>
Line 851 ⟶ 1,025:
4 * 0.25 * 0.5 = 0.5
6 * 0.16666666666667 * 0.5 = 0.5
</pre>
=={{header|M2000 Interpreter}}==
<syntaxhighlight lang="m2000 interpreter">
Module CheckIt {
\\ by default numbers are double
x = 2
xi = 0.5
y = 4
yi = 0.25
z = x + y
zi = 1 / ( x + y )
Composed=lambda (a, b)-> {
=lambda a,b (n)->{
=a*b*n
}
}
numbers=(x,y,z)
inverses=(xi,yi,zi)
Dim Base 0, combo(3)
combo(0)=Composed(x,xi), Composed(y,yi), Composed(z,zi)
num=each(numbers)
inv=each(inverses)
fun=each(combo())
While num, inv, fun {
Print $("0.00"), Array(num);" * ";Array(inv);" * 0.50 = "; combo(fun^)(0.5),$("")
Print
}
}
Checkit
\\ for functions we have this definition
Composed=lambda (f1, f2) -> {
=lambda f1, f2 (x)->{
=f1(f2(x))
}
}
</syntaxhighlight>
{{out}}
<pre>
2.00 * 0.50 * 0.50 = 0.50
4.00 * 0.25 * 0.50 = 0.50
6.00 * 0.17 * 0.50 = 0.50
</pre>
Line 857 ⟶ 1,074:
This code demonstrates the example using structure similar to function composition, however the composition function is replace with the multiplier function.
<
num={2,4,2+4};
numi=1/num;
multiplierfuncs = multiplier @@@ Transpose[{num, numi}];
</syntaxhighlight>
The resulting functions are unity multipliers:
Line 869 ⟶ 1,086:
Note that unlike Composition, the above definition of multiplier only allows for exactly two arguments. The definition can be changed to allow any nonzero number of arguments:
<
</syntaxhighlight>
=={{header|Nemerle}}==
{{trans|Python}}
<
using System.Console;
using Nemerle.Collections.NCollectionsExtensions;
Line 890 ⟶ 1,107:
WriteLine($[multiplier(n, m) (0.5)|(n, m) in ZipLazy(nums, inums)]);
}
}</
=={{header|Never}}==
<syntaxhighlight lang="never">
func multiplier(a : float, b : float) -> (float) -> float {
let func(m : float) -> float { a * b * m }
}
func main() -> int {
var x = 2.0;
var xi = 0.5;
var y = 4.0;
var yi = 0.25;
var z = x + y;
var zi = 1.0 / z;
var f = [ x, y, z ] : float;
var i = [ xi, yi, zi ] : float;
var c = 0;
var mult = let func(m : float) -> float { 0.0 };
for (c = 0; c < 3; c = c + 1) {
mult = multiplier(f[c], i[c]);
prints(f[c] + " * " + i[c] + " * " + 1.0 + " = " + mult(1) + "\n")
};
0
}
</syntaxhighlight>
{{output}}
<pre>
2.00 * 0.50 * 1.00 = 1.00
4.00 * 0.25 * 1.00 = 1.00
6.00 * 0.17 * 1.00 = 1.00
</pre>
=={{header|Nim}}==
<syntaxhighlight lang="nim">
func multiplier(a, b: float): auto =
let ab = a * b
result = func(c: float): float = ab * c
let
x = 2.0
xi = 0.5
y = 4.0
yi = 0.25
z = x + y
zi = 1.0 / ( x + y )
let list = [x, y, z]
let invlist = [xi, yi, zi]
for i in 0..list.high:
# Create a multiplier function...
let f = multiplier(list[i], invlist[i])
# ... and apply it.
echo f(0.5)</syntaxhighlight>
{{out}}
<pre>0.5
0.5
0.5</pre>
=={{header|Objeck}}==
Similar however this code does not generate a list of functions.
<syntaxhighlight lang="objeck">use Collection.Generic;
class FirstClass {
function : Main(args : String[]) ~ Nil {
x := 2.0;
xi := 0.5;
y := 4.0;
yi := 0.25;
z := x + y;
zi := 1.0 / (x + y);
numlist := CompareVector->New()<FloatHolder>;
numlist->AddBack(x); numlist->AddBack(y); numlist->AddBack(z);
numlisti := Vector->New()<FloatHolder>;
numlisti->AddBack(xi); numlisti->AddBack(yi); numlisti->AddBack(zi);
each(i : numlist) {
v := numlist->Get(i); vi := numlisti->Get(i);
mult := Multiplier(v, vi);
r := mult(0.5);
"{$v} * {$vi} * 0.5 = {$r}"->PrintLine();
};
}
function : Multiplier(a : FloatHolder, b : FloatHolder) ~ (FloatHolder) ~ FloatHolder {
return \(FloatHolder) ~ FloatHolder : (c) => a * b * c;
}
}
</syntaxhighlight>
{{output}}
<pre>
2 * 0.5 * 0.5 = 0.5
4 * 0.25 * 0.5 = 0.5
6 * 0.166667 * 0.5 = 0.5
</pre>
=={{header|OCaml}}==
<
# let y = 4.0;;
Line 914 ⟶ 1,233:
(* or just apply the generated function immediately... *)
# List.map2 (fun n inv -> (multiplier n inv) 0.5) coll inv_coll;;
- : float list = [0.5; 0.5; 0.5]</
=={{header|Oforth}}==
<
: firstClassNum
Line 928 ⟶ 1,247:
x y + ->z
x y + inv ->zi
[ x, y, z ] [ xi, yi, zi ] zipWith(#multiplier) map(#[ 0.5 swap perform ] ) . ;</
{{out}}
<pre>
Line 935 ⟶ 1,254:
=={{header|Oz}}==
<
[X Y Z] = [2.0 4.0 Z=X+Y]
Line 953 ⟶ 1,272:
do
{Show {{Multiplier N I} 0.5}}
end</
"Multiplier" is like "Compose", but with multiplication instead of function application. Otherwise the code is identical except for the argument types (numbers instead of functions).
Line 959 ⟶ 1,278:
=={{header|PARI/GP}}==
{{works with|PARI/GP|2.4.2 and above}}
<
x -> n1 * n2 * x
};
Line 968 ⟶ 1,287:
print(multiplier(y,yi)(0.5));
print(multiplier(z,zi)(0.5));
};</
The two are very similar, though as requested the test numbers are in 6 variables instead of two vectors.
=={{header|Pascal}}==
Works with FPC (currently only version 3.3.1).
<syntaxhighlight lang="pascal">
program FunTest;
{$mode objfpc}
{$modeswitch functionreferences}
{$modeswitch anonymousfunctions}
uses
SysUtils;
type
TMultiplier = reference to function(n: Double): Double;
function GetMultiplier(a, b: Double): TMultiplier;
var
prod: Double;
begin
prod := a * b;
Result := function(n: Double): Double begin Result := prod * n end;
end;
var
Multiplier: TMultiplier;
I: Integer;
x, xi, y, yi: Double;
Numbers, Inverses: array of Double;
begin
x := 2.0;
xi := 0.5;
y := 4.0;
yi := 0.25;
Numbers := [x, y, x + y];
Inverses := [xi, yi, 1.0 / (x + y)];
for I := 0 to High(Numbers) do begin
Multiplier := GetMultiplier(Numbers[I], Inverses[I]);
WriteLn(Multiplier(0.5));
end;
end.
</syntaxhighlight>
{{out}}
<pre>
5.0000000000000000E-001
5.0000000000000000E-001
5.0000000000000000E-001
</pre>
=={{header|Perl}}==
<
my ( $n1, $n2 ) = @_;
sub {
Line 992 ⟶ 1,357:
print multiplier( $number, $inverse )->(0.5), "\n";
}
</syntaxhighlight>
Output:
<pre>0.5
Line 999 ⟶ 1,364:
</pre>
The entry in first-class functions uses the same technique:
<
my ($f, $g) = @_;
Line 1,008 ⟶ 1,373:
...
compose($flist1[$_], $flist2[$_]) -> (0.5)
</syntaxhighlight>
=={{header|Phix}}==
Just as there is no real support for first class functions, not much that is pertinent to this task for numbers either, but the manual way is just as trivial:
<!--<syntaxhighlight lang="phix">(phixonline)-->
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span>
<span style="color: #004080;">sequence</span> <span style="color: #000000;">mtable</span> <span style="color: #0000FF;">=</span> <span style="color: #0000FF;">{}</span>
<span style="color: #008080;">function</span> <span style="color: #000000;">multiplier</span><span style="color: #0000FF;">(</span><span style="color: #004080;">atom</span> <span style="color: #000000;">n1</span><span style="color: #0000FF;">,</span> <span style="color: #004080;">atom</span> <span style="color: #000000;">n2</span><span style="color: #0000FF;">)</span>
<span style="color: #000000;">mtable</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">append</span><span style="color: #0000FF;">(</span><span style="color: #000000;">mtable</span><span style="color: #0000FF;">,{</span><span style="color: #000000;">n1</span><span style="color: #0000FF;">,</span><span style="color: #000000;">n2</span><span style="color: #0000FF;">})</span>
<span style="color: #008080;">return</span> <span style="color: #7060A8;">length</span><span style="color: #0000FF;">(</span><span style="color: #000000;">mtable</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;">call_multiplier</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: #004080;">atom</span> <span style="color: #000000;">m</span><span style="color: #0000FF;">)</span>
<span style="color: #004080;">atom</span> <span style="color: #0000FF;">{</span><span style="color: #000000;">n1</span><span style="color: #0000FF;">,</span><span style="color: #000000;">n2</span><span style="color: #0000FF;">}</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">mtable</span><span style="color: #0000FF;">[</span><span style="color: #000000;">f</span><span style="color: #0000FF;">]</span>
<span style="color: #008080;">return</span> <span style="color: #000000;">n1</span><span style="color: #0000FF;">*</span><span style="color: #000000;">n2</span><span style="color: #0000FF;">*</span><span style="color: #000000;">m</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">function</span>
<span style="color: #008080;">constant</span> <span style="color: #000000;">x</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">2</span><span style="color: #0000FF;">,</span>
<span style="color: #000000;">xi</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">0.5</span><span style="color: #0000FF;">,</span>
<span style="color: #000000;">y</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">4</span><span style="color: #0000FF;">,</span>
<span style="color: #000000;">yi</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">0.25</span><span style="color: #0000FF;">,</span>
<span style="color: #000000;">z</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">x</span> <span style="color: #0000FF;">+</span> <span style="color: #000000;">y</span><span style="color: #0000FF;">,</span>
<span style="color: #000000;">zi</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">1</span> <span style="color: #0000FF;">/</span> <span style="color: #0000FF;">(</span> <span style="color: #000000;">x</span> <span style="color: #0000FF;">+</span> <span style="color: #000000;">y</span> <span style="color: #0000FF;">)</span>
<span style="color: #0000FF;">?</span><span style="color: #000000;">call_multiplier</span><span style="color: #0000FF;">(</span><span style="color: #000000;">multiplier</span><span style="color: #0000FF;">(</span><span style="color: #000000;">x</span><span style="color: #0000FF;">,</span><span style="color: #000000;">xi</span><span style="color: #0000FF;">),</span><span style="color: #000000;">0.5</span><span style="color: #0000FF;">)</span>
<span style="color: #0000FF;">?</span><span style="color: #000000;">call_multiplier</span><span style="color: #0000FF;">(</span><span style="color: #000000;">multiplier</span><span style="color: #0000FF;">(</span><span style="color: #000000;">y</span><span style="color: #0000FF;">,</span><span style="color: #000000;">yi</span><span style="color: #0000FF;">),</span><span style="color: #000000;">0.5</span><span style="color: #0000FF;">)</span>
<span style="color: #0000FF;">?</span><span style="color: #000000;">call_multiplier</span><span style="color: #0000FF;">(</span><span style="color: #000000;">multiplier</span><span style="color: #0000FF;">(</span><span style="color: #000000;">z</span><span style="color: #0000FF;">,</span><span style="color: #000000;">zi</span><span style="color: #0000FF;">),</span><span style="color: #000000;">0.5</span><span style="color: #0000FF;">)</span>
<!--</syntaxhighlight>-->
{{out}}
<pre>
Line 1,064 ⟶ 1,411:
Compared to first class functions, there are (as in my view there should be) significant differences in the treatment of numbers and functions, but as mentioned on that page tagging ctable entries should be quite sufficient.
<!--<syntaxhighlight lang="phix">(phixonline)-->
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span>
<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|PicoLisp}}==
<
(de multiplier (N1 N2)
Line 1,102 ⟶ 1,452:
(prinl (format ((multiplier Inv Num) 0.5) *Scl)) )
(list X Y Z)
(list Xi Yi Zi) ) )</
Output:
<pre>0.500000
Line 1,110 ⟶ 1,460:
that the function 'multiplier' above accepts two numbers, while 'compose'
below accepts two functions:
<
(de compose (F G)
Line 1,126 ⟶ 1,476:
(prinl (format ((compose Inv Fun) 0.5) *Scl)) )
'(sin cos cube)
'(asin acos cubeRoot) )</
With a similar output:
<pre>0.500001
Line 1,134 ⟶ 1,484:
=={{header|Python}}==
This new task:
<
>>> # Number literals
>>> x,xi, y,yi = 2.0,0.5, 4.0,0.25
Line 1,148 ⟶ 1,498:
>>> [multiplier(inversen, n)(.5) for n, inversen in zip(numlist, numlisti)]
[0.5, 0.5, 0.5]
>>></
The Python solution to First-class functions for comparison:
<
>>> from math import sin, cos, acos, asin
>>> # Add a user defined function and its inverse
Line 1,165 ⟶ 1,515:
>>> [compose(inversef, f)(.5) for f, inversef in zip(funclist, funclisti)]
[0.5, 0.4999999999999999, 0.5]
>>></
As can be see, the treatment of functions is very close to the treatment of numbers. there are no extra wrappers, or function pointer syntax added, for example.
=={{header|R}}==
<
x = 2.0
xi = 0.5
Line 1,183 ⟶ 1,533:
Output
[1] 0.5 0.5 0.5
</syntaxhighlight>
Compared to original first class functions
<
[1] 0.5 0.5 0.5</
=={{header|Racket}}==
<syntaxhighlight lang="racket">
#lang racket
Line 1,209 ⟶ 1,559:
((multiplier n i) 0.5))
;; -> '(0.5 0.5 0.5)
</syntaxhighlight>
=={{header|Raku}}==
(formerly Perl 6)
{{works with|Rakudo|2015-09-10}}
<syntaxhighlight lang="raku" line>sub multiplied ($g, $f) { return { $g * $f * $^x } }
my $x = 2.0;
my $xi = 0.5;
my $y = 4.0;
my $yi = 0.25;
my $z = $x + $y;
my $zi = 1.0 / ( $x + $y );
my @numbers = $x, $y, $z;
my @inverses = $xi, $yi, $zi;
for flat @numbers Z @inverses { say multiplied($^g, $^f)(.5) }</syntaxhighlight>
Output:
<pre>0.5
0.5
0.5</pre>
The structure of this is identical to first-class function task.
=={{header|REXX}}==
The REXX language doesn't have an easy method to call functions by using a variable name,
<br>but the '''interpret''' instruction can be used to provide that capability.
<syntaxhighlight lang="rexx">/*REXX program to use a first-class function to use numbers analogously. */
nums= 2.0 4.0 6.0 /*various numbers, can have fractions.*/
invs= 1/2.0 1/4.0 1/6.0 /*inverses of the above (real) numbers.*/
m= 0.5 /*multiplier when invoking new function*/
do j=1 for words(nums); num= word(nums, j); inv= word(invs, j)
nf= multiplier(num, inv); interpret call nf m /*sets the var RESULT.*/
say 'number=' @(num) 'inverse=' @(inv) 'm=' @(m) 'result=' @(result)
end /*j*/
exit /*stick a fork in it, we're all done. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
@: return left( arg(1) / 1, 15) /*format the number, left justified. */
multiplier: procedure expose n1n2; parse arg n1,n2; n1n2= n1 * n2; return 'a_new_func'
a_new_func: return n1n2 * arg(1)</syntaxhighlight>
{{out|output|text= when using the internal default inputs:}}
<pre>
number= 2 inverse= 0.5 m= 0.5 result= 0.5
number= 4 inverse= 0.25 m= 0.5 result= 0.5
number= 6 inverse= 0.166666667 m= 0.5 result= 0.5
</pre>
=={{header|Ruby}}==
<
numlist = [x=2, y=4, x+y]
invlist = [0.5, 0.25, 1.0/(x+y)]
p numlist.zip(invlist).map {|n, invn| multiplier[invn, n][0.5]}
# => [0.5, 0.5, 0.5]</
This structure is identical to the treatment of Ruby's [[First-class functions#Ruby|first-class functions]] -- create a Proc object that returns a Proc object (a closure). These examples show that 0.5 times number ''n'' (or passed to function ''f'') times inverse of ''n'' (or passed to inverse of ''f'') returns the original number, 0.5.
=={{header|Rust}}==
<
fn main() {
let (x, xi) = (2.0, 0.5);
Line 1,241 ⟶ 1,636:
move |m| x*y*m
}
</syntaxhighlight>
This is very similar to the [[First-class functions#Rust|first-class functions]] implementation save that the type inference works a little bit better here (e.g. when declaring <code>numlist</code> and <code>invlist</code>) and <code>multiplier</code>'s declaration is substantially simpler than <code>compose</code>'s. Both of these boil down to the fact that closures and regular functions are actually different types in Rust so we have to be generic over them but here we are only dealing with 64-bit floats.
=={{header|Scala}}==
<
x: Double = 2.0
Line 1,279 ⟶ 1,674:
0.5
0.5
0.5</
=={{header|Scheme}}==
This implementation closely follows the Scheme implementation of the [[First-class functions]] problem.
<
(define xi 0.5)
(define y 4.0)
Line 1,301 ⟶ 1,696:
(newline))
n1 n2))
(go number inverse)</
Output:
0.5
Line 1,308 ⟶ 1,703:
=={{header|Sidef}}==
<
func (n3) {
n1 * n2 * n3
Line 1,326 ⟶ 1,721:
for f,g (numbers ~Z inverses) {
say multiplier(f, g)(0.5)
}</
{{out}}
<pre>
Line 1,336 ⟶ 1,731:
=={{header|Slate}}==
{{incorrect|Slate|Compare and contrast the resultant program with the corresponding entry in First-class functions.}}
<
define: #x -> 2.
define: #y -> 4.
Line 1,342 ⟶ 1,737:
define: #numlisti -> (numlist collect: [| :x | 1.0 / x]).
numlist with: numlisti collect: [| :n1 :n2 | (multiplier applyTo: {n1. n2}) applyWith: 0.5].</
=={{header|Tcl}}==
{{works with|Tcl|8.5}}
<
proc multiplier {a b} {
list apply {{ab m} {expr {$ab*$m}}} [expr {$a*$b}]
}</
Note that, as with Tcl's solution for [[First-class functions#Tcl|First-class functions]], the resulting term must be expanded on application. For example, study this interactive session:
<
apply {{ab m} {expr {$ab*$m}}} 6
% {*}$mult23 5
30</
Formally, for the task:
<
set xi 0.5
set y 4.0
Line 1,366 ⟶ 1,761:
foreach a $numlist b $numlisti {
puts [format "%g * %g * 0.5 = %g" $a $b [{*}[multiplier $a $b] 0.5]]
}</
Which produces this output:
<pre>2 * 0.5 * 0.5 = 0.5
4 * 0.25 * 0.5 = 0.5
6 * 0.166667 * 0.5 = 0.5</pre>
=={{header|TXR}}==
This solution seeks a non-strawman interpretation of the exercise: to treat functions and literal numeric terms under the same operations. We develop a three-argument function called <code>binop</code> whose argument is an ordinary function which works on numbers, and two arithmetic arguments which are any combination of functions or numbers. The functions may have any arity from 0 to 2. The <code>binop</code> functions handles all the cases.
The basic rules are:
* When all required arguments are given to a function, it is expected that a number will be produced.
* Zero-argument functions are called to force a number out of them.
* When operands are numbers or zero-argument functions, a numeric result is calculated.
* Otherwise the operation is a functional combinator, returning a function.
<syntaxhighlight lang="txrlisp">(defun binop (numop x y)
(typecase x
(number (typecase y
(number [numop x y])
(fun (caseql (fun-fixparam-count y)
(0 [numop x [y]])
(1 (ret [numop x [y @1]]))
(2 (ret [numop x [y @1 @2]]))
(t (error "~s: right argument has too many params"
%fun% y))))
(t (error "~s: right argument must be function or number"
%fun% y))))
(fun (typecase y
(number (caseql (fun-fixparam-count x)
(0 [numop [x] y])
(1 (ret [numop [x @1] y]))
(2 (ret [numop [x @1 @2] y]))
(t (error "~s: left argument has too many params"
%fun% x))))
(fun (macrolet ((pc (x-param-count y-param-count)
^(+ (* 3 ,x-param-count) ,y-param-count)))
(caseql* (pc (fun-fixparam-count x) (fun-fixparam-count y))
(((pc 0 0)) [numop [x] [y]])
(((pc 0 1)) (ret [numop [x] [y @1]]))
(((pc 0 2)) (ret [numop [x] [y @1 @2]]))
(((pc 1 0)) (ret [numop [x @1] [y]]))
(((pc 1 1)) (ret [numop [x @1] [y @1]]))
(((pc 1 2)) (ret [numop [x @1] [y @1 @2]]))
(((pc 2 0)) (ret [numop [x @1 @2] [y]]))
(((pc 2 1)) (ret [numop [x @1 @2] [y @1]]))
(((pc 2 2)) (ret [numop [x @1 @2] [y @1 @2]]))
(t (error "~s: one or both arguments ~s and ~s\ \
have excess arity" %fun% x y)))))))
(t (error "~s: left argument must be function or number"
%fun% y))))
(defun f+ (x y) [binop + x y])
(defun f- (x y) [binop - x y])
(defun f* (x y) [binop * x y])
(defun f/ (x y) [binop / x y])</syntaxhighlight>
With this, the following sort of thing is possible:
<pre>1> [f* 6 4] ;; ordinary arithmetic.
24
2> [f* f+ f+] ;; product of additions
#<interpreted fun: lambda (#:arg-1-0062 #:arg-2-0063 . #:arg-rest-0061)>
3> [*2 10 20] ;; i.e. (* (+ 10 20) (+ 10 20)) -> (* 30 30)
900
4> [f* 2 f+] ;; doubled addition
#<interpreted fun: lambda (#:arg-1-0017 #:arg-2-0018 . #:arg-rest-0016)>
5> [*4 11 19] ;; i.e. (* 2 (+ 11 19))
60
6> [f* (op f+ 2 @1) (op f+ 3 @1)]
#<interpreted fun: lambda (#:arg-1-0047 . #:arg-rest-0046)>
7> [*6 10 10] ;; i.e. (* (+ 2 10) (+ 3 10)) -> (* 12 13)
156
</pre>
So with these definitions, we can solve the task like this, which demonstrates that numbers and functions are handled by the same operations:
<syntaxhighlight lang="txrlisp">(let* ((x 2.0)
(xi 0.5)
(y 4.0)
(yi 0.25)
(z (lambda () (f+ x y))) ;; z is obviously function
(zi (f/ 1 z))) ;; also a function
(flet ((multiplier (a b) (op f* @1 (f* a b))))
(each ((n (list x y z))
(v (list xi yi zi)))
(prinl [[multiplier n v] 42.0]))))</syntaxhighlight>
{{out}}
<pre>42.0
42.0
42.0</pre>
=={{header|Ursala}}==
Line 1,377 ⟶ 1,864:
composition operator (+), and is named in compliance
with the task specification.
<
#import flo
Line 1,387 ⟶ 1,874:
#cast %eL
main = (gang multiplier*p\numbers inverses) 0.5</
The multiplier could have been written in pattern
matching form like this.
<
The main program might also have been written with an
anonymous function like this.
<
output:
<pre>
<5.000000e-01,5.000000e-01,5.000000e-01>
</pre>
=={{header|Wren}}==
{{libheader|Wren-fmt}}
<syntaxhighlight lang="wren">import "./fmt" for Fmt
var multiplier = Fn.new { |n1, n2| Fn.new { |m| n1 * n2 * m } }
var orderedCollection = Fn.new {
var x = 2.0
var xi = 0.5
var y = 4.0
var yi = 0.25
var z = x + y
var zi = 1.0 / ( x + y )
return [[x, y, z], [xi, yi, zi]]
}
var oc = orderedCollection.call()
for (i in 0..2) {
var x = oc[0][i]
var y = oc[1][i]
var m = 0.5 // rather than 1 to compare with first-class functions task
Fmt.print("$0.1g * $g * $0.1g = $0.1g", x, y, m, multiplier.call(x, y).call(m))
}</syntaxhighlight>
{{out}}
Agreeing with results of first-class functions task:
<pre>
2.0 * 0.5 * 0.5 = 0.5
4.0 * 0.25 * 0.5 = 0.5
6.0 * 0.166667 * 0.5 = 0.5
</pre>
=={{header|zkl}}==
<
//-->L(L(2,0.5),L(4,0.25),L(6,0.166667))</
<
This is actually partial evaluation, multiplier returns n1*n2*X where X isn't known yet. So multiplier(2,3)(4) --> (2*3*)4 --> 24. Even better, multiplier(2,3)(4,5) --> 120, multiplier(2,3)(4,5,6) --> 720, multiplier(2,3)() --> 6.
Alternatively,
<
<
//-->L(Deferred,Deferred,Deferred) // lazy eval of n*(1/n)*X
ms.run(True,1.0) //-->L(1,1,1)
ms.run(True,5.0) //-->L(5,5,5)
ms.run(True,0.5) //-->L(0.5,0.5,0.5)</
List.run(True,X), for each item in the list, does i(X) and collects the results into another list. Sort of an inverted map or fold.
{{omit
{{omit
{{omit
{{omit
{{omit
{{omit
{{omit
{{omit from|Java|Can't pass around expressions like that.}}
{{omit
{{omit
{{
{{omit from|Processing}}
{{omit from|PureBasic}}
{{omit from|TI-83 BASIC}}
{{omit from|TI-89 BASIC}} <!-- Cannot do function composition. Function definitions are dynamic, but functions cannot be passed as values. -->
{{omit
{{omit from|ZX Spectrum Basic}}
[[Category:Functions and subroutines]]
|