"Circular" Function Declaration in SML

544 Views Asked by At

I want to use functions in a "circular" way, as shown 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.

2

There are 2 best solutions below

2
On BEST ANSWER

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.

0
On

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.