Prashant Vaibhav
Prashant Vaibhav

Reputation: 83

Why does this F# / OCaml "match" expression compile?

This code compiles just fine in F# as well as OCaml:

let testmatch k =
    match k with
    | jqk3jtl23jtlk123 -> true

I've tested in both FSI and utop. It always returns true.

The jqk3jtl23jtlk123 is totally random, and its type is inferred as 'a. Even if I constrain k with a datatype (e.g. let testmatch (k: int) =) it compiles (though obviously constraining testmatch's type to int -> bool instead of 'a -> bool.

Could someone please explain what's going on? Specifically:

Upvotes: 8

Views: 232

Answers (2)

Honza Brestan
Honza Brestan

Reputation: 10957

In this case, the "literal" jqk3jtl23jtlk123 is a valid variable name, and so what the pattern to the left of -> describes is the same as if you wrote let jqk3jtl23jtlk123 = k. Since this accepts any value of k, and does not constrain its type because binding works for all types, the inferred type is 'a, the most generic value the type system can represent.

If you turn the literal into something that is not a valid identifier, for example beginning with a digit, it will fail to compile.

If you wrap the literal in quotes, it will be interpreted as a string value literal, you should get the inexhaustive match warning, and it will constrain k's type to string.

Upvotes: 15

Étienne Millon
Étienne Millon

Reputation: 3028

This is a wildcard pattern, which names whatever k is equal to. This is equivalent to

let testmatch k =
    let jqk3jtl23jtlk123 = k in
    true

Upvotes: 10

Related Questions