[m-users.] Anonymous recursive functions/predicates
Mark Clements (gmail)
samuel.legotus at gmail.com
Fri Aug 20 15:50:45 AEST 2021
In the process of translating some old SML code to Mercury, I was unable
to translate for an anonymous recursive function. Such
functions/predicates are useful for quickly rolling loops. Is there any
way to declare or use an anonymous recursive function in Mercury?
As a simple example which counts the number of predicates that are true
in a range (and which could be written in a number of other ways:):
:- func count2(func(int) = bool, int, int) = int.
count2(Predicate, Start, Finish) = Result :-
%% Loop is an anonymous function that tries to call itself
Loop = (func(I, Y) = (if I>Finish then Y
else Loop(I+1, if Predicate(I)=yes then Y+1
else Y))),
Result = Loop(Start, 0).
As an example of this function being called:
count2(func(I) = (if I>5 then yes else no), 0, 10)
but this gives an error:
: In clause for `count2(in, in, in) = out':
: mode error: variable `Loop' has instantiatedness
: `free',
: expected instantiatedness for non-local variables
: of lambda goals is `ground'.
:
: In clause for `count2(in, in, in) = out':
: in argument 1 (i.e. the function term) of
: higher-order function call:
: mode error: variable `Loop' has instantiatedness
: `free',
: expecting higher-order func inst of arity 2.
Any guidance here would be appreciated.
Sincerely, Mark.
More information about the users
mailing list