Ocaml Option Types

The OCaml types always confuse me, no matter what tutorials / manuals I read. I need to determine the type of, say, a test that contains the following forms:

a type ('a,' b) a test that takes one of the forms: Empty, T t, N n, Seq [x1 ... xn]

I know how to make the first 3, but I have no idea how to determine the last form. This is what I have:

type ('nonterm, 'term) test = | Empty | T of 'term | N of 'nonterm | ???? 

For seq, I need to match instances of the subexpressions x1 and xn. If x = 0, then this is empty. Can anyone help me out? Thanks in advance.

+4
source share
2 answers

Seq subexpressions are also checked? If so, you can use a list:

 type ('nonterm, 'term) test = | Empty | T of 'term | N of 'nonterm | Seq of ('nonterm, 'term) test list 

Lists can, of course, be empty.

+10
source

This is the answer to your comment on Michael E:

OCaml variants consist of constructors with optional arguments. In the case of Michael's answer, the constructors are: Empty , T , N and Seq . Empty takes no arguments, T accepts a generic type called 'term , and N accepts a generic type called 'nonterm (in a second I will get Seq ). The variant is of type ('nonterm, 'term) test . Let's say you need a list of elements of type ('nonterm, 'term) test :

 # [Empty; Empty];; - : ('a, 'b) test list = [Empty; Empty] 

You will notice that type ('a, 'b) test list . (OCaml replaced nonterm with a and term with b , but you don't need to worry too much about it.)

Now we can see that | Seq of ('nonterm, 'term) test list | Seq of ('nonterm, 'term) test list is a constructor called Seq that takes as argument a list of elements of type ('nonterm, 'term) test . Now we can do it:

 # Seq [Empty;Empty];; - : ('a, 'b) test = Seq [Empty; Empty] 
+6
source

Source: https://habr.com/ru/post/1336725/


All Articles