Parametrized types in OCaml

269 Views Asked by At

I have searched for some time and I can't find a solution. It's probably a simple syntax issue that I can't figure out.

I have a type:

# type ('a, 'b) mytype = 'a * 'b;;

And I want to create a variable of type string string sum.

# let (x:string string mytype) = ("v", "m");;
Error: The type constructor mytype expects 2 argument(s),
   but is here applied to 1 argument(s)

I've tried different way of putting parenthesis around type parameters, I get pretty much the same error.

It works, however, with single parameter types so I guess there's some syntax I don't know.

# type 'a mytype2 = string * 'a;;
# let (x:string mytype2) = ("hola", "hello");;
val x : string mytype2 = ("hola", "hello")

Can someone, please, tell me how to do this with two parameters?

2

There are 2 best solutions below

0
On BEST ANSWER

You should write

let (x: (string, string) mytype) = ("v", "m");;

That is mytype parameter is a couple. You can even remove unneeded parentheses:

let x: (string, string) mytype = "v", "m";;
1
On

It's worth noting that your type mytype is just a synonym for a pair, since it doesn't have any constructors. So you can just say let x = ("v", "m").

$ ocaml
        OCaml version 4.01.0

# type ('a, 'b) mytype = 'a * 'b;;
type ('a, 'b) mytype = 'a * 'b
# let x = ("v", "m");;
val x : string * string = ("v", "m")
# (x : (string, string) mytype);;
- : (string, string) mytype = ("v", "m")

The point is that the two types string * string and (string, string) mytype are the same type.