Jump to content

First-class functions: Difference between revisions

→‎{{header|Mercury}}: Reimplemented using more idiomatic use of higher-order functions for ease of expression.
m (→‎firstclass.m: Corrected composition order.)
(→‎{{header|Mercury}}: Reimplemented using more idiomatic use of higher-order functions for ease of expression.)
Line 864:
# 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 mapped in corresponding members through an anonymous function that compose the resulting pairs of functions and apply them to the value 0.5.
# 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===
Line 884 ⟶ 880:
Forward = [math.sin, math.cos, (func(X) = math.ln(X))],
Reverse = [math.asin, math.acos, (func(X) = math.exp(X))],
Results = list.map_corresponding(
apply(list.zip(Forward, Reverse), [], Results),
(func(F, R) =
compose(R, F, 0.5)
), Forward, Reverse),
io.write_list(Results, ", ", io.write_float, !IO),
io.write_string("\n", !IO).</lang>
 
:- 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(R, F, 0.5) | A], Results).
apply([_], _, _) :- throw("This can't happen!").</lang>
 
===Use and output===
Cookies help us deliver our services. By using our services, you agree to our use of cookies.