这个问题类似于 this one ,但我想声明一个递归仿函数而不是递归模块。所以我有 :
一个接口(interface)A
:
module type A = sig
type t
val basic_func: ...
val complex_func: ...
end
一个仿函数
ComplexImpl
实现A.complex_func
根据 A.basic_func
:module ComplexImpl (SomeA : A) =
struct
let complex_impl params =
SomeA.basic_func ...
...
end
另一个接口(interface)
I
:module type I = sig
type t
...
end
还有一个仿函数
B
它接受类型为 I
的参数, 实现接口(interface) A
并使用 ComplexImpl
实现complex_func
.我想写这样的东西:(* I can't write 'rec' here *)
module rec B (SomeI : I) :
A with type t = SomeI.t
= struct
type t = SomeI.t
(* this line does not work *)
module Impl = ComplexImpl(B(I))
let basic_func (x : t) = ...
let complex_func (x : t) =
Impl.complex_impl x
end
但我不能声明递归仿函数......
我发现实现递归仿函数的唯一方法是自行参数化它:
module B (SomeI : I) (CopyOfB : A with type t = SomeI.t) :
A with type t = SomeI.t
= struct
type t = SomeI.t
(* this line works *)
module Impl = ComplexImpl(CopyOfB)
let basic_func (x : t) = ...
let complex_func (x : t) =
Impl.complex_impl x
end
并像这样使用它:
module rec RealB = B(SomeI)(RealB)
但是语法很冗长,不是很安全(如果有人放置了一个不同于
RealB
的参数怎么办),如果 RealB
会变得非常棘手。本身就是一个仿函数...
最佳答案
递归模块具有以下形式的语法限制:
module rec Name : module_type = module_expr
这意味着不能使用以下方法声明递归仿函数:
module rec Name (Arg : module_type) : module_type = module_expr
但必须改为:
module rec Name : functor (Arg : module_type) -> module_type =
functor (Arg : module_type) -> module_expr
关于recursion - OCaml 中的递归仿函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28739472/