OCaml 对象中的递归函数

发布于 2024-07-14 15:59:18 字数 415 浏览 7 评论 0原文

我试图在对象方法的上下文中找出 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

小…楫夜泊 2024-07-21 15:59:18

您仍然需要在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 like method 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 by doIt 100 is a better idea.

木有鱼丸 2024-07-21 15:59:18

我的 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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文