假设我有一个选项列表:
let opts = [Some 1; None; Some 4]
我想将这些转换为列表选项,例如:
None
,结果是 None
针对这种特定情况编写此代码相对简单(使用 Core 和
Monad
模块):let sequence foo =
let open Option in
let open Monad_infix in
List.fold ~init:(return []) ~f:(fun acc x ->
acc >>= fun acc' ->
x >>= fun x' ->
return (x' :: acc')
) foo;;
但是,正如问题标题所暗示的那样,我真的很想对类型构造函数进行抽象,而不是专门用于
Option
。 Core 似乎使用仿函数来提供更高级类型的效果,但我不清楚如何编写要在模块上抽象的函数。在 Scala 中,我会使用一个隐式上下文绑定(bind)来要求一些 Monad[M[_]]
的可用性。我期待没有办法隐式传递模块,但我将如何显式地做到这一点?换句话说,我可以写一些近似于此的东西:let sequence (module M : Monad.S) foo =
let open M in
let open M.Monad_infix in
List.fold ~init:(return []) ~f:(fun acc x ->
acc >>= fun acc' ->
x >>= fun x' ->
return (x' :: acc')
) foo;;
这是可以用一流的模块完成的事情吗?
编辑:好的,所以我实际上并没有想到尝试使用该特定代码,而且它似乎比我预期的更接近工作!似乎语法实际上是有效的,但我得到了这个结果:
Error: This expression has type 'a M.t but an expression was expected of type 'a M.t
The type constructor M.t would escape its scope
错误的第一部分似乎令人困惑,因为它们匹配,所以我猜问题出在第二部分 - 这里的问题是返回类型似乎没有确定吗?我想它取决于传入的模块 - 这是一个问题吗?有没有办法修复这个实现?
最佳答案
首先,这是您的代码的自包含版本(使用旧版
标准库的 List.fold_left
) 对于没有的人
核心在手,仍然想尝试编译你的例子。
module type MonadSig = sig
type 'a t
val bind : 'a t -> ('a -> 'b t) -> 'b t
val return : 'a -> 'a t
end
let sequence (module M : MonadSig) foo =
let open M in
let (>>=) = bind in
List.fold_left (fun acc x ->
acc >>= fun acc' ->
x >>= fun x' ->
return (x' :: acc')
) (return []) foo;;
你得到的错误信息意味着(令人困惑的第一行可以
被忽略)M.t 定义是本地的
M
模块,和一定不能逃避它的范围,它会对你正在尝试的事情做
来写。
这是因为您使用的是一流的模块,允许
对模块进行抽象,但不要具有依赖外观的类型,例如
返回类型取决于参数的模块值,或者至少
路径(此处为
M
)。考虑这个例子:
module type Type = sig
type t
end
let identity (module T : Type) (x : T.t) = x
这是错误的。错误消息指向
(x : T.t)
并说:Error: This pattern matches values of type T.t
but a pattern was expected which matches values of type T.t
The type constructor T.t would escape its scope
您可以做的是在对一流模块 T 进行抽象之前对所需类型进行抽象,以便不再有任何逃避。
let identity (type a) (module T : Type with type t = a) (x : a) = x
这依赖于显式抽象类型变量
a
的能力。不幸的是,这个特性还没有扩展到对高级变量的抽象。你目前不能写:let sequence (type 'a m) (module M : MonadSig with 'a t = 'a m) (foo : 'a m list) =
...
解决方案是使用仿函数:不是在值级别工作,而是在模块级别工作,它具有更丰富的语言。
module MonadOps (M : MonadSig) = struct
open M
let (>>=) = bind
let sequence foo =
List.fold_left (fun acc x ->
acc >>= fun acc' ->
x >>= fun x' ->
return (x' :: acc')
) (return []) foo;;
end
不是让每个 monadic 操作(
sequence
、 map
等)都对 monad 进行抽象,而是进行模块范围的抽象。关于OCaml:更高级的多态性(对模块进行抽象?),我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/15092139/