recursion - OCaml:具有一等模块和存在类型的递归

标签 recursion module ocaml existential-type first-class

我正在尝试创建一个交替使用两个模块(同一类型)的函数,同时深入递归。我将模块作为参数传递,但当我向模块添加存在类型时,一切都出了问题。让我有点惊讶的是,如果我将函数设为非递归(就像我发现的所有远程相似的示例一样),它就会起作用。

这是我认为的最小示例(仅传递一个模块):

module type TEST =
  sig
    type t
    val foo : t -> unit
  end

let rec foo
          (type a)
          (module Test : TEST with type t = a)
          (arg : a) : unit =
   (* Test.foo arg *) (* <- works *)
   (* I tried various type annotations, but none worked: *)
   foo (module Test : TEST with type t = a) (arg : a)

示例的错误消息:

Error: This expression has type
         (module TEST with type t = a) -> a -> 'b
       but an expression was expected of type 
         (module TEST with type t = a) -> a -> 'b
       The type constructor a would escape its scope

为什么它不起作用?我该怎么做才能使它起作用?

最佳答案

不确定是否完全理解您的错误,但是在进行递归时,通常最好将类型注释放在最高级别。 这是一个有效的版本:

module type TEST =
sig
  type t
  val foo : t -> unit
end

let rec foo : type a. (module TEST with type t = a) -> a -> unit
  = fun (module Test) arg ->
    if true
      then foo (module Test) arg 
      else Test.foo arg

关于recursion - OCaml:具有一等模块和存在类型的递归,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48381401/

相关文章:

java - 如何在Java中实现递归方法中的引用传递

python - 删除后我从哪里访问 __name__?

gtk - 如何读取这个 OCaml 类型签名?

emacs - 图阿雷格模式找不到 ocaml?

ocaml - 如何在 OCAML 中获取 Uint64 的二进制表示

python - 从字典/JSON 构建层次结构

python - 递归并找到最大数

python - 如何使用加密模块加密变量?

c - 操作给定路径的递归函数

javascript - 无法去除 webpack bundle js 文件中的注释