Jump to content

First-class functions: Difference between revisions

→‎{{header|Nemerle}}: Added a Mercury implementation.
(→‎{{header|Nemerle}}: Added a Mercury implementation.)
Line 859:
all give back:
<lang Mathematica>f[g[h[x]]]</lang>
 
=={{header|Mercury}}==
This solution uses the <code>compose/3</code> function defined in <code>std_util</code> (part of the Mercury standard library) to demonstrate the use of first-class functions. The following process is followed:
# A list of "forward" functions is provided (sin, cosine and a lambda that calls ln).
# A list of "reverse" functions is provided (asin, acosine and a lambda that calls exp).
# The lists are "zipped" together to pair each forward with its reverse.
# The list of paired functions is passed in to the recursive <code>apply/3</code> predicate.
# The functions are taken out in pairs and composed and applied to the value 0.5.
# The results are returned and printed when all function pairs have been processed.
 
Note that the third <code>apply/3</code> clause exists only because the compiler can't see that the list will *always* have a set of pairs. It will never be followed.
 
===firstclass.m===
<lang Mercury>:- module firstclass.
 
:- interface.
:- import_module io.
:- pred main(io::di, io::uo) is det.
 
:- implementation.
:- import_module exception, list, math, std_util.
 
main(!IO) :-
Forward = [math.sin, math.cos, (func(X) = math.ln(X))],
Reverse = [math.asin, math.acos, (func(X) = math.exp(X))],
apply(list.zip(Forward, Reverse), [], Results),
io.write_list(Results, ", ", io.write_float, !IO),
io.write_string("\n", !IO).
 
:- pred apply(list((func(float) = float)), list(float), list(float)).
:- mode apply(in, in, out) is det.
apply([], A, Results) :- Results = A.
apply([F, R|Functions], A, Results) :-
apply(Functions, [compose(F, R, 0.5) | A], Results).
apply([_], _, _) :- throw("This can't happen!").</lang>
 
===Use and output===
<pre><nowiki> $ mmc -E firstclass.m && ./firstclass
0.5, 0.4999999999999999, 0.5</nowiki></pre>
 
(Limitations of the IEEE floating point representation make the cos/acos pairing lose a little bit of accuracy.)
 
=={{header|Nemerle}}==
Cookies help us deliver our services. By using our services, you agree to our use of cookies.