OCaml:在定义函数之前声明它
有没有办法在 OCaml 中定义函数之前先声明它?我正在使用 OCaml 解释器。
我有两个函数:
let myFunctionA =
(* some stuff here..... *) myFunctionB (*some stuff *)
let myFunctionB =
(* some stuff here .... *) myFunctionA (* some stuff *)
但这不起作用,因为 myFunctionA 在创建之前无法调用 myFunctionB。
我已经进行了一些谷歌搜索,但似乎找不到任何东西。我怎样才能做到这一点?
Is there a way to declare a function before defining it in OCaml? I'm using an OCaml interpreter.
I have two functions:
let myFunctionA =
(* some stuff here..... *) myFunctionB (*some stuff *)
let myFunctionB =
(* some stuff here .... *) myFunctionA (* some stuff *)
This doesn't work though, since myFunctionA can't call myFunctionB before it's made.
I've done a few google searches but can't seem to find anything. How can I accomplish this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您想要的是使这两个函数相互递归。您必须使用“let ... and ...”,而不是使用“let ... let ...”,如下所示:
What you want is to make these two functions mutually recursive. Instead of using "let ... let ...", you have to use "let rec ... and ..." as follows:
实际上“let rec ..”有一个非常严重的限制:它只能在单个模块中工作。这迫使程序员在不需要的地方编写大模块......这个问题在低级 C 中不会发生!
有几种解决方法,但都不能令人满意。第一种方法是创建一个函数类型的变量,并最初在其中存储引发异常的函数,然后存储所需的值。
第二种是使用类类型和类(以及一种间接寻址)。如果您有很多相互递归的函数,这是最好的方法(因为您只需要向每个函数传递一个对象)。
最简单也是最丑陋的是将函数作为参数相互传递,这种解决方案很快就会失控。在遵循所有定义的模块中,您可以通过引入一组“let rec”包装器来简化调用代码。不幸的是,这无助于定义函数,并且通常大多数调用都会发生在此类定义中。
Actually "let rec .." has a very serious limitation: it only works within a single module. This forces the programmer to write big modules where it is not desired .. a problem which does not occur in lowly C!
There are several workarounds, all unsatisfactory. The first is to make a variable of the function type and initially store a function raising an exception in it, then later store the desired value.
The second is to use class types and classes (and one indirection). If you have a lot of mutually recursive functions this is the best way (because you only need to pass a single object to each of them).
The easiest and most ugly is to pass the functions to each other as arguments, a solution which rapidly gets out of control. In a module following all the definitions you can simplify the calling code by introducing a set of "let rec" wrappers. Unfortunately, this does not help defining the functions, and it is common that most of the calls will occur in such definitions.