Search code examples
ocaml

What's the use of this mutually recursive type definition in OCaml?


Below is a valid variant type definition in OCaml. (source)

type t = U of u and u = T of t

Is there a use for it?

And how to create a value of type t? Or type u?


Solution

  • The example you've shown does not make much sense. There's no way for the recursion to end.

    As Naïm Favier notes, you can actually create a value, but the cyclic nature of the values will be noted by OCaml.

    # let rec t = T u and u = U t;;
    val t : u = T (U <cycle>)
    val u : t = U (T <cycle>)
    

    But with that, mutually recursive types can be very useful. Consider the definition of Seq.t from the standard library.

    type 'a t = unit -> 'a node
    (** A sequence [xs] of type ['a t] is a delayed list of elements of
        type ['a]. Such a sequence is queried by performing a function
        application [xs()]. This function application returns a node,
        allowing the caller to determine whether the sequence is empty
        or nonempty, and in the latter case, to obtain its head and tail. *)
    
    and +'a node =
      | Nil
      | Cons of 'a * 'a t (**)
    (** A node is either [Nil], which means that the sequence is empty,
        or [Cons (x, xs)], which means that [x] is the first element
        of the sequence and that [xs] is the remainder of the sequence. *)
    

    Source