Pattern matching for conciseness
Pattern matching can match and bind in a single step
So far we have seen the pattern matching logic in the match..with
expression, where it seems to be just a switch/case statement. But in fact pattern matching is much more general ? it can compare expressions in a number of ways, matching on values, conditions, and types, and then assign or extract values, all at the same time.
Pattern matching will be discussed in depth in later posts, but to start with, here is a little taster of one way that it aids conciseness. We'll look at the way pattern matching is used for binding values to expressions (the functional equivalent of assigning to variables).
In the following examples, we are binding to the internal members of tuples and lists directly:
You can also bind values to the inside of complex structures such as records. In the following example, we will create an "Address
" type, and then a "Customer
" type which contains an address. Next, we will create a customer value, and then match various properties against it.
In the last example, note how we could reach right into the Address
substructure and pull out the street as well as the customer name.
This ability to process a nested structure, extract only the fields you want, and assign them to values, all in a single step, is very useful. It removes quite a bit of coding drudgery, and is another factor in the conciseness of typical F# code.
Last updated
Was this helpful?