gpt4 book ai didi

oop - OCaml 对象中的递归函数

转载 作者:行者123 更新时间:2023-12-01 11:10:24 24 4
gpt4 key购买 nike

我试图在对象方法的上下文中找出 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;;

最佳答案

您仍然需要在 loopTest 方法中调用 doIt。 let只是定义了doIt,就像method只是定义了一个方法,并没有调用它。编译器检测到这一点,因为它不知道从 loopTest 返回什么(就像一个没有返回类型 void,但在 C# 或 Java 中没有实现的方法)。

此外,您正在使用此代码进行无限循环,也许 if x>1 then doIt (x-1) 后跟 doIt 100 更好想法。

关于oop - OCaml 对象中的递归函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/625946/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com