我试图制作一个交替使用两个模块(相同类型)的函数,同时深入递归。我将模块作为参数传递,当我向模块添加存在类型时,一切都出错了。让我感到惊讶的是,如果我将函数设置为非递归函数(就像我发现的所有远程类似示例一样),它就可以工作。
以下是我认为最小的例子(只传递一个模块):
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
为什么它不起作用,我该怎么做才能使它发挥作用?
答案 0 :(得分:3)
不确定完全理解您的错误,但在进行递归时,通常最好将类型注释放在最高级别。 这是一个有效的版本:
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