OCaml 对象中的递归函数
我试图在对象方法的上下文中找出 OCaml 的递归。 我已经尝试过以下代码,但似乎无法编译它。
class foo =
object (self)
method loopTest =
let rec doIt x =
Printf.printf "%d\n" x;
if x>1 then doIt (x+1)
end;;
如何在方法中创建此类递归函数?
修改后的代码:
class foo =
object (self)
method loopTest =
let rec doIt x =
Printf.printf "%d\n" x;
if x<10 then doIt (x+1) in doIt 0
end;;
I am trying to figure out recursion for OCaml in the context of an object's method. I have tried the following code but can't seem to get it to compile.
class foo =
object (self)
method loopTest =
let rec doIt x =
Printf.printf "%d\n" x;
if x>1 then doIt (x+1)
end;;
How do I create a recursive function of this sort within a method?
Revised code:
class foo =
object (self)
method loopTest =
let rec doIt x =
Printf.printf "%d\n" x;
if x<10 then doIt (x+1) in doIt 0
end;;
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您仍然需要在loopTest方法中调用doIt。
let
只是定义了 doIt,就像method
只是定义了一个方法,并不调用它。 编译器检测到这一点是因为它不知道从 LoopTest 返回什么(例如没有返回类型 void 的方法,但在 C# 或 Java 中没有实现)。另外,您将陷入此代码的无限循环中,也许
if x>1 then doIt (x-1)
后面跟着doIt 100
是一个更好的主意。You still need to call doIt in your loopTest method.
let
just defines doIt, just likemethod
just defines a method, and does not call it. The compiler detects this because it doesn't know what to return from loopTest (like a method that does not have return type void, but has no implementation in C# or Java).Also, you're in for an infinite loop with this code, maybe
if x>1 then doIt (x-1)
followed bydoIt 100
is a better idea.我的 OCaml 已经生锈了,但我不认为 let 会评估它所绑定的内容。 如果您希望 testLoop 调用 doIt,请添加 in doIt 或类似内容。
My OCaml is rusty, but I don't think let evaluates to what it bound. If you want testLoop to call doIt, tack on a in doIt or similar.