OCaml:更高的kinded多态性(抽象模块?)

时间:2013-02-26 14:53:25

标签: ocaml monads higher-kinded-types

假设我有一个选项列表:

let opts = [Some 1; None; Some 4]

我想将这些转换为列表选项,例如:

  • 如果列表包含None,则结果为None
  • 否则,会收集各种整数。

为此特定情况编写此内容相对简单(使用CoreMonad模块):

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中,我使用隐式上下文绑定来要求某些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    

错误的第一部分似乎令人困惑,因为它们匹配,所以我猜测问题是第二个 - 这里的问题似乎是返回类型似乎没有确定?我想它依赖于传入的模块 - 这是一个问题吗?有没有办法解决这个实现?

1 个答案:

答案 0 :(得分:19)

首先,这是代码的自包含版本(使用遗留代码) 对于没有的人来说,标准库的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操作(sequencemap等)抽象出monad,而是进行模块范围的抽象。