“圆形” SML 中的函数声明
我想以“循环”方式使用函数,如以下示例所示:
fun cll1 (s)= cll2(s);
fun cll2 (s)= cll3(s);
fun cll3 (s)= cll(s);
编写此代码会在 SML 中产生错误,表明构造函数 cll2
未绑定。有人可以帮我写一些类似的东西吗?在C语言中这是可能的;我想用SML 写它。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您需要
and
关键字。显然,这些定义行不通,因为它是无限递归(通常您会在一个或多个函数中测试基本情况),但这是一般形式。
You want the
and
keyword.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.
在本例中,由于
cll1
依赖于cll2
,cll2
依赖于cll3
,而cll3
> 在一些不相关的事情上(即函数实际上并不像你想象的那样循环),你也可以写(当然,在这种情况下,因为它都是一样的,人们不妨写
val (cll1 ,cll2,cll3) = (cll,cll,cll)
但这可能不是很有意义。)也就是说,这与循环定义无关,不像您所说的那样;同样的情况也会发生
(如果意图是 a = b = 0)。
这里要指出的一点是,与 c 中的函数不同,sml 中的声明是按顺序求值的,如果您想引用尚未声明的内容,则必须明确 - 以及
and
是这样做的常用方法,是的,因为从语义上讲,在任何情况下,它都表明该组函数旨在组合在一起,以便它们可以相互引用。in this case, since
cll1
depends oncll2
,cll2
oncll3
, andcll3
on something unrelated (i.e. the functions aren't actually as circular as you think), you could just as well write(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
(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.