Jheel rathod
Jheel rathod

Reputation: 13

ocaml recursive type record with constructors

I wanted to make a recursive type for linked list in ocaml for which i defined a type for the elements of the list. I wrote the following code

  type elem=
  |Nil
  |Elem of {content:int;mutable next:elem};;

But i am getting syntax error. How to correct the error?

Upvotes: 1

Views: 312

Answers (1)

Isabelle Newbie
Isabelle Newbie

Reputation: 9378

This syntax ("inline records as arguments to datatype constructors") was introduced with OCaml 4.03 in April 2016: http://ocaml.org/releases/4.03.html

Some systems, like my Ubuntu, include older versions of OCaml, which don't support this:

$ /usr/bin/ocaml
        OCaml version 4.02.3

# type elem=
    |Nil
    |Elem of {content:int;mutable next:elem};;  
Error: Syntax error

The best way to fix this would be to install a newer version of OCaml and to keep it updated, ideally using OPAM: https://opam.ocaml.org/doc/Install.html

If that's not an option, you can work around it by declaring the algebraic data type and the record type and the same time, using a single mutually recursive definition (type t1 = ... and t2 = ...):

# type elem = Nil | Elem of elem_record
  and  elem_record = { content: int; mutable next: elem };;
type elem = Nil | Elem of elem_record
and elem_record = { content : int; mutable next : elem; }

Upvotes: 6

Related Questions