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?
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 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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With