recursion - F#递归成员函数: "How to Define it correctly"

标签 recursion f# member-functions

我的理解是,当您在类型中定义递归成员函数时,则无需将函数定义为递归。含义rec关键字。

但是,当我这样做时:

type hello() = class
  member this.recursion(x) =
      match x with
      |10 -> printfn "%A" x
      |_ -> printfn "%A" x
            recursion(x+1)
end

然后我得到递归未定义的错误。

我已经尝试过this.recursion,但是随后我仍然收到警告说:

递归对象引用“this”未使用。递归对象引用的存在将运行时初始化检查添加到此类型和派生类型的成员中。考虑删除此递归对象引用。

所以我想知道在类型中定义递归成员函数的正确方法是什么?

最佳答案

是的,它们在定义为成员时起作用。
正如您已经注意到的,您在调用站点上缺少this。它应该是:

this.recursion(x+1)

但这很好,至少对我而言:
type hello() = class
  member this.recursion(x) =
      match x with
      |10 -> printfn "%A" x
      |_ -> printfn "%A" x
        this.recursion(x+1)
end

无论如何,我会在内部定义它,如其他答案所示,但在方法内部:
type hello() = class
  member this.recursion(x) =
    let rec loop x =
      match x with
      |10 -> printfn "%A" x
      |_ -> printfn "%A" x
            loop (x+1)
    loop x
end

关于recursion - F#递归成员函数: "How to Define it correctly",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41764356/

相关文章:

haskell - Haskell中的递归问题-语法问题?

f# - 如何将 out/ref extern 参数转换为 F#

wpf - F# 为 WPF 应用程序保留一些用户值

c++ - 是否可以将 std::deque 的成员函数作为参数传递?

c++ - 发布版本中成员函数和全局函数的性能差异

c# - 从集合中查找缺失的日期

python - 递归模式获取输入整数并返回回文

c++ - 将类成员函数作为参数传递给全局函数

c++ - 跟踪在 C++ 中调用递归函数的次数

reflection - 检索 F# 函数的 MethodInfo