"Circular" Function Declaration in SML
I want to use functions in a "circular" way, as show开发者_StackOverflow中文版n in the following example:
fun cll1 (s)= cll2(s);
fun cll2 (s)= cll3(s);
fun cll3 (s)= cll(s);
Writing this produces an error in SML that the constructor cll2
is unbound. Could someone help me write something along these lines? It's possible in C; I'd like to write it in SML.
You want the and
keyword.
fun cll1 s = cll2 s
and cll2 s = cll3 s
and cll3 s = cll s
Obviously these definitions won't do since it's an infinite recursion (ordinarily you'd test for a base case in one or more of the functions), but that's the general form.
in this case, since cll1
depends on cll2
, cll2
on cll3
, and cll3
on something unrelated (i.e. the functions aren't actually as circular as you think), you could just as well write
fun cll3 (s)= cll(s);
fun cll2 (s)= cll3(s);
fun cll1 (s)= cll2(s);
(of course, in this case, since it's all the same, one might as well write val (cll1,cll2,cll3) = (cll,cll,cll)
. but that's probably not very pointful.)
that is, this has nothing to do with circular definitions, not as you've stated your problem; the same occurs with
val a = b
val b = 0
(if the intent is that a = b = 0).
the point to be made here is that, unlike functions in c, declarations in sml are evaluated in order and you have to be explicit if you want to refer to something you haven't declared yet -- and and
is the usual way of doing so, yes, because, semantically, in any case, it indicates that the set of functions is intended to be taken together, so that they can refer to each other.
精彩评论