In OCaml, how do I return values of different types in different branches of a pattern match?
Example code:
type t =
| Int of int
| Bool of bool
let f x =
match x with
| Int i -> i
| Bool b -> b
However, this will fail with Error: This expression has type bool but an expression was expected of type int.
I tried to fix the problem by using a locally abstract type:
type _ t =
| Int of int
| Bool of bool
let f (type a) (x : a t) : a =
match x with
| Int i -> i
| Bool b -> b
However, this does not work either. The error is Error: This expression has type int but an expression was expected of type a.
What did I do wrong? Is it even possible to return a value of a different type in each branch of a pattern match?