Imp*_*ive 13 monads ocaml higher-kinded-types
假设我有一个选项列表:
let opts = [Some 1; None; Some 4]
Run Code Online (Sandbox Code Playgroud)
我想将这些转换成列表选项,这样:
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;;
Run Code Online (Sandbox Code Playgroud)
但是,正如问题标题所暗示的那样,我真的想抽象出类型构造函数而不是专门的Option
.Core似乎使用仿函数来提供更高级别的类型的效果,但我不清楚如何编写要在模块上抽象的函数.在Scala中,我使用隐式上下文绑定来要求某些内容的可用性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;;
Run Code Online (Sandbox Code Playgroud)
这是可以通过一流模块完成的吗?
编辑:好的,所以我尝试使用那个特定的代码实际上并没有发生,而且它似乎比我预期的更接近工作!似乎语法实际上是有效的,但我得到了这个结果:
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
Run Code Online (Sandbox Code Playgroud)
错误的第一部分似乎令人困惑,因为它们匹配,所以我猜测问题是第二个 - 这里的问题是返回类型似乎没有确定?我想它依赖于传入的模块 - 这是一个问题吗?有没有办法解决这个实现?
gas*_*che 19
首先,这里是一个自包含的代码版本(使用List.fold_left
标准库的遗留
),对于那些没有Core的人,仍然想尝试编译你的例子.
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;;
Run Code Online (Sandbox Code Playgroud)
您获得的错误消息意味着(令人困惑的第一行可以忽略)Mt定义是M
模块的本地定义,并且不得超出其范围,这与您尝试编写的内容有关.
这是因为您使用的是一流模块,允许在模块上进行抽象,但不具有依赖于外观的类型,例如返回类型取决于参数的模块值,或至少取决于
路径(此处M
).
考虑这个例子:
module type Type = sig
type t
end
let identity (module T : Type) (x : T.t) = x
Run Code Online (Sandbox Code Playgroud)
这是错的.错误消息指出(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
Run Code Online (Sandbox Code Playgroud)
在抽象出第一类模块T之前,你可以做的就是在所需的类型上抽象,这样就不再有逃避了.
let identity (type a) (module T : Type with type t = a) (x : a) = x
Run Code Online (Sandbox Code Playgroud)
这依赖于显式抽象类型变量的能力a
.不幸的是,这个特征还没有扩展到对更高级别变量的抽象.你目前不能写:
let sequence (type 'a m) (module M : MonadSig with 'a t = 'a m) (foo : 'a m list) =
...
Run Code Online (Sandbox Code Playgroud)
解决方案是使用仿函数:您可以在模块级别工作,而不是在价值级别工作,该级别具有更丰富的语言.
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
Run Code Online (Sandbox Code Playgroud)
不是让每个monadic操作(sequence
,map
等等)都在monad上进行抽象,而是在模块范围内进行抽象.