Why do i get errors when I write this kind of pattern matching :
type t = A of int | B of float
let f = function
| (A i | B f) -> true
| _ -> false
or
let f = function
| A i | B f -> true
| _ -> false
Error: Variable f must occur on both sides of this | pattern
let f = function
| (A i | B i) -> true
| _ -> false
or
let f = function
| A i | B i -> true
| _ -> false
Error: This pattern matches values of type ints of type float
but a pattern was expected which matches value
If you provide a single right-hand side for multiple patterns (as you do), OCaml requires that the patterns consistently bind to pattern variables.
In the first situation,
the patterns don’t agree on the variables they bind to: the first pattern binds to
i, while the second binds tof.In the second situation,
the patterns don’t agree on the type of values to bind to their variables: the first pattern binds a value of type
inttoi, while the second binds a value of typefloattoi.The only way in which these two pattern can consistently bind to variables is not to bind to any variables at all:
The complete example then becomes
(But note that the last arm of the pattern match is superfluous as the first two pattern already exhaustively match all values of your type
t. Hence, we get:This of course is equivalent to writing
let f _ = true.)