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