Ocaml:在模块之间传递构造函数类型

Haj*_*hem 4 ocaml types module abstract

我有这个模块类型:

module type MOD =    
  sig   
    type operand
    type op
    val print : op -> string
  end;;
Run Code Online (Sandbox Code Playgroud)

MOD的实现是:

module M1:MOD =
  struct
    type operand = Mem of int | Reg of int | Const of int
    type op = Add of operand * operand| Sub of operand * operand
    let print op = match op with
      | Add _ -> "Add"
      | Sub _ -> "Sub"
  end;;
Run Code Online (Sandbox Code Playgroud)

我想创建一个参数化模块,op从第一个模块获取类型,并在该类型的变量上实现函数.像这样:

module  ARCHI = functor (M : MOD) ->
  struct
    type op = M.op

    let execute o = match o with
      | Add (x,y) -> x + y
      | Sub (x,y) -> x - y
  end;;
Run Code Online (Sandbox Code Playgroud)

我收到错误: Unbound constructor Add.我该怎么办呢?

Ash*_*wal 7

你已经op在MOD中声明了类型是抽象的,然后你已经定义了你的函子来获取MOD类型的模块M. 因此,您正确无法访问op的实现.否则,您的仿函数不会执行它所声称的MOD类型的任何模块,而不仅仅是您定义的特定M1.

您可以通过在签名中写出类型的完整定义来公开MOD中的op实现.但是,目前还不清楚你真的需要一个仿函数.