Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ocaml : Passing constructor type between modules

I have this module type :

module type MOD =    
  sig   
    type operand
    type op
    val print : op -> string
  end;;

An implementation of MOD is :

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;;

I want to create a parametrized module witch take op type from the first module and implement function on variables of that type. like this:

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;;

I get error : Unbound constructor Add. How can I manage this?

like image 502
Hajer Herbegue Bouhachem Avatar asked Jan 04 '12 14:01

Hajer Herbegue Bouhachem


People also ask

What does :: mean in OCaml?

Regarding the :: symbol - as already mentioned, it is used to create lists from a single element and a list ( 1::[2;3] creates a list [1;2;3] ). It is however worth noting that the symbol can be used in two different ways and it is also interpreted in two different ways by the compiler.

What is a functor in OCaml?

What are functors and why do we need them? A functor is a module that is parametrized by another module, just like a function is a value which is parametrized by other values, the arguments. It allows one to parametrize a type by a value, which is not possible directly in OCaml without functors.

What does type A mean in OCaml?

The type 'a is a type variable, and stands for any given type. The reason why sort can apply to lists of any type is that the comparisons (=, <=, etc.) are polymorphic in OCaml: they operate between any two values of the same type. This makes sort itself polymorphic over all list types.

What keyword is used to declare variables and functions in OCaml?

At its simplest, a variable is an identifier whose meaning is bound to a particular value. In OCaml these bindings are often introduced using the let keyword.


1 Answers

You have declared type op to be abstract in MOD, and then you have defined your functor to take module M of type MOD. Thus, you correctly cannot have access to the implementation of op. Otherwise, your functor doesn't do what it claims to which is take any module of type MOD, not just the specific M1 you've defined.

You can expose the implementation of op in MOD by writing out the full definition of the type in the signature. However, it's not clear that you actually need a functor at all here.

like image 177
Ashish Agarwal Avatar answered Sep 18 '22 11:09

Ashish Agarwal