Search code examples
ocamlgadtheterogeneous

Heterogeneous list of GADT in ocaml


I would like to create a heterogenous list of expression using the canonical example for GADT.

Given the following types:

type _ value =
| Bool : bool -> bool value
| Int : int -> int value

type _ expr =
| Value : 'a value -> 'a expr
| If : bool expr * 'a expr * 'a expr -> 'a expr
| Eq : 'a expr * 'a expr -> bool expr
| Lt : int expr * int expr -> bool expr

I tried to create the following list:

 let a = [Value (Bool true); Value (Int 1);]

It seems that is not possible since it returns the following error message:

Error: This expression has type int value
       but an expression was expected of type bool value
       Type int is not compatible with type bool

Is there a way to do it?

I looked at the ocaml documentation for GADT and either fail to find or understand how to do so.

Can someone point me toward something that would explain why you can't do with GADTs everything you can do with ADTs?


Solution

  • One solution would be to do:

    type any_expr = Any:'a expr -> any_expr
    let a = [Any (Value (Bool true)); Any (Value (Int 1));]
    

    but I don't understand why that works or why it is required. So if someone has reading to offer I am still interested.

    Ok so I found this is a duplicate, and the key word is:

    existential wrapper