Search code examples
syntaxocamlvariant

How to use a defined type inside a class as a val in Ocaml?


I am writing a class which stores an array of defined types. I am having problem -i think- with the syntax of my code. I want to get a defined type inside of array but my code keeps giving error.

I have already created a class, write down the array i need. i have tried already writing it these ways;


[|(Rook, Black, (Alive of (A, 1)))]
[|(Rook, Black, (Alive of A, 1))]
[|(Rook, Black, Alive of (A,1))]
[|(Rook, Black, Alive of A,1)]
[|(Rook, Black, (A,1))

but sadly, it shows my array as chess_piece * chess_colour * (chess_letter * int) or it gives operating error.

this is my defined type

type chess_letter = A | B | C | D | E | F | G | H
and chess_piece = King | Queen | Rook | Bishop | Knight | Pawn
and chess_colour = Black | White 
and chess_position = Alive of chess_letter * int | Dead

array should include [|(chess_piece, chess_colour, chess_position)|]


Solution

  • The syntax for constructing a value of the variant Alive is:

    Alive (A, 1)
    

    of is only used in the type definition. And it dosn't make a difference whether it's inside or outside an array.

    Also, none of your arrays are syntactically correct. The first four are missing a | before the terminating ], and the last is missing both.