【发布时间】:2012-05-14 17:42:23
【问题描述】:
在我的代码中,我有一个提供基本读/写操作的数据库访问上下文,称为CouchDB.ctx。然后我的应用程序中的各种模块使用附加功能扩展该类,例如Async.ctx。
我正在实现一个 Cache 模块,它包裹在一个 Source 模块周围。 Cache 模块函数采用上下文参数并操作数据库。然后将一些调用连同上下文一起转发到Source 模块。
我需要按照以下方式定义一个仿函数:
module CouchDB = struct
class ctx = object
method get : string -> string option monad
method put : string -> string -> unit monad
end
end
module AsyncDB = struct
class ctx = object
inherit CouchDB.ctx
method delay : 'a. float -> (ctx -> 'a monad) -> 'a monad
end
end
module type SOURCE = sig
class ctx = #CouchDB.ctx (* <-- incorrect *)
type source
val get : source -> ctx -> string monad
end
module Cache = functor(S:SOURCE) -> struct
class ctx = S.ctx
type source = S.source
let get source ctx =
bind (ctx # get source) (function
| Some cache -> return cache
| None ->
bind (S.get source ctx)
(fun data -> bind (ctx # put source data)
(fun () -> return data))
end
module SomeSource = struct
class ctx = AsyncDB.ctx
type source = string
let get s ctx =
ctx # async 300 (some_long_computation s)
end
module SomeCache = Cache(SomeSource)
问题是我无法表达Source 模块使用的上下文应该是CouchDB.ctx 的子类型这一事实。以上代码返回错误:
A type variable is unbound in this type declaration.
In type #CouchDB.ctx as 'a the variable 'a is unbound
如何表达这种类型约束?
【问题讨论】:
-
我很好奇你的
SOURCE签名。我心中的宣言应该是module type SOURCE = sig class ctx : object inherit CouchDB.ctx end (* ... *) end;这不是你需要的吗?
标签: types ocaml signature type-constraints