如何让两个方法互相调用?
我对如何让两个方法相互调用有点困惑(即让 A()
调用 B()
和 B()< /code> 调用
A()
)。 似乎 F# 仅在代码中遇到该方法后才“看到”该方法,因此如果没有,它只是表示值或构造函数尚未定义。
我在这里错过了一些非常基本的东西吗?
I'm a bit confused as to how to get two method to call each other (i.e., have A()
call B()
and B()
call A()
). It seems that F# only 'sees' the method after it's been encountered in code, so if it hasn't, it just says value or constructor has not been defined.
Am I missing something very basic here?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
“let rec...and...”是您需要的语法。
另请参阅F# 联合递归中的冒险< /a>.
'let rec... and...' is the syntax you seek.
See also Adventures in F# Co-Recursion.
由于问题是关于方法的,而 Brian 的答案是关于函数的,也许指出您可以对类型使用类似的语法是有用的:
另请注意,默认情况下成员是“let rec”(事实上,我不认为它们不能是递归的)。
Since the question is about methods, and Brian's answer is about functions, maybe it's useful to point out that you can use a similar syntax for types:
Note also that members are 'let rec' by default (in fact I don't think they can be not recursive).
F# 4.1 引入了 相互递归的模块和命名空间。
它们是
and
关键字的替代方案。rec
关键字定义“允许所有包含的代码相互递归”的模块和命名空间。F# 4.1 introduces mutually recursive modules and namespaces.
These are an alternative to the
and
keyword.The
rec
keyword defines modules and namespaces that "allow for all contained code to be mutually recursive."通过 let 声明的函数
这些是相互递归函数。
同一类型内的方法
这很简单; 它就是有效的。 请注意 Abel 的评论。
不同类型中的方法
这对相互递归类型使用
type ... and
语法。注意
通常,仅当呼叫发生在两个方向时才使用
and
。 否则,最好重新排序声明,使被调用的函数排在前面。 避免循环依赖并且在不使用它们的地方不暗示它们通常有助于类型推断和可读性。我建议编辑问题以询问一般功能,或询问不同类型(在这种情况下,我会从此答案中删除前两种情况)。 方法通常被认为是函数的子集,这是通用的数学术语。 然而,从技术上讲,所有 F# 函数都是 CLI 方法,因为这就是它们编译的目的。 事实上,目前尚不清楚问题的要求是什么,但我从接受的答案中假设它不仅要求方法,正如标题所暗示的那样。
Functions declared via let
These are mutually recursive functions.
Methods within the same type
This is trivial; it just works. Note Abel's comment though.
Methods within different types
This uses the
type ... and
syntax for mutually recursive types.Notes
Normally,
and
is only used if the calls occur in both directions. Otherwise, it may be better to re-order the declarations so that the called function comes first. It is often helpful for type-inference and readability to avoid circular dependencies, and to not imply them where they aren't used.I propose to edit the question to either ask for functions in general, or to ask for different types (in which case I would remove the first two cases from this answer). Methods are usually considered to be a subset of functions, which is the general mathematical term. However, all F# functions are technically CLI methods, as that is what they are compiled to. As is, it is not clear what the question is asking for, but I assume from the accepted answer that it does not only ask for methods, as the title would imply.