OCaml:更高种类的多态性(对模块进行抽象?)

标签 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。核心似乎使用仿函数来提供更高类型的效果,但我不清楚如何编写要在模块上抽象的函数。在 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    

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

最佳答案

首先,这是代码的独立版本(使用旧版 标准库的 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

您不需要对单子(monad)进行每个单子(monad)操作(序列映射等)抽象,而是进行模块范围的抽象。

关于OCaml:更高种类的多态性(对模块进行抽象?),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15092139/

相关文章:

types - OCaml 中模块包含的类型约束

string - 在 OCaml 中将字符转换为字符串

F#:有没有办法扩展 monad 关键字列表?

Haskell笛卡尔积,带过滤器的Monad

scala - Scala 中用于具有继承返回类型的集合的最小框架

types - 如何将 OCaml 整数类型限制为整数范围?

unit-testing - 在 OCaml 中制作测试替身

haskell - Haskell 中使用 IO Bool 进行列表理解

c++ - 使用 C++ 的高级类型

scala - 缺少更高类型的 list