8 Patterns and unions

 

This chapter covers

  • Conditional logic with pattern matching
  • Discriminated unions
  • Summarizing the F# type system

This chapter finishes our look at the core F# language! It deals with two things: first, how we perform conditional logic, such as if/then and, second, the final kind of type supported in F#—the discriminated union—which provides a solution to parts of domain modeling that records and tuples can’t really address. When you finish this, you’ll have a rounded appreciation of the F# type system and understand when to use which component.

8.1 Introducing pattern matching

We’ve already seen if/then expressions in F#. As it turns out, in everyday F#, they are used only in a couple of specific scenarios because F# has a much more powerful mechanism for conditional logic: pattern matching.

I’ve heard pattern matching described as “switch/case on steroids” by some people. It’s basically a way of performing logic over different conditions (known as patterns) in a flexible expression-oriented construct.

8.1.1 Exhaustive matching

8.1.2 Tuple matching

8.1.3 Simplifying pattern matches: A worked example

8.1.4 Record matching

8.1.5 Type inference

8.1.6 When guards

8.2 More advanced pattern matching

8.2.1 Recursive matching

8.2.2 Nested or conditions

8.2.3 Binding symbols

8.2.4 Collection matching

8.2.5 Match vs. if/then

8.3 Discriminated unions

8.3.1 Basics of discriminated unions

8.3.2 Pattern matching