clarification on F# match syntax

Viewed 44

I am trying to clarify something that's a bit fuzzy for me:

let a, b = true, 3
match a, b with
| true, x -> sprintf "true %i" x
| false, _ -> "false"

in the first match case, true is matched and the value of b is assigned to x. the first part I have trouble 'accepting' is that 'true' is read for the comparison, but x is assigned

but then does that mean:

match a, b with
| c, x -> sprintf "true %b %i" c x
| false, _ -> "false"

will always match the first statement?

2 Answers

Yes.

Match expressions always try to match values against a pattern. There are many different types of patterns that can be matched. What you have here are constant patterns (in the case of matching against true or false) and variable patterns (in the case of matching against c, x). A constant pattern will match if the value being compared equals that constant - a variable pattern will match any input and assign the value of the input to the variable.

Matching a, b against the pattern c, x is basically matching it against any unconstrained tuple of size 2 and simultaneously assigning the values of a and b to new names c and x. In effect, what you have is the same as:

match a, b with
| _, _ -> sprintf "true %b %i" a b

Your assumption is correct. Using variables in the match expression is similar to using the underscore (in the latter case you just don't intend to use it). A variable is always a 100% match, as it just catches whatever is in that position of the match.

Your second example will raise a warning that the last line never matches.

Your first example can also be written like this:

let a, b = true, 3
match a with
| true -> sprintf "true %i" b
| false -> "false"
Related