Polymorphic variants - automatically deducing lower bound when composing functions

Compiling

let f e = match e with 
    | `A -> "a"
let g e = match e with 
    | `B -> "b"
    | _ as e -> f e

I get an error:

Error: This expression has type [> `B ] but an expression was expected of type
         [< `A ]
       The second variant type does not allow tag(s) `B

but this compiles fine

let g e = match e with 
    | `B -> "b"
    | `A as e -> f e

Is there any way to tell the compiler to deduce the type of _ in the first fragment?

The type of e is the same in every branch of the pattern matching, thus in

let g e = match e with 
    | `B -> "b"
    | e2 -> f e2

The type of e2 is [>B]due to the first branch andf e2` is ill-typed. This one of the limitation of polymorphic variants. Contrarily, in your second example,

let g e = match e with 
    | `B -> "b"
    | `A as e2 -> f e2

the variable e2 as the same type than `A and f e2 is well-typed.
Note that this solution scales (partially) if you use #-types:

type first = [`A | `B | `C ]
type second = [ `D | `E | `F ]
let f = function
  | #first -> 1

let g = function
  | #second -> 2
  | #first as x -> f x
2 Likes