Making Two Things Match
Learn about Elixir's pattern matching.
We'll cover the following...
Introduction to pattern matching
Controlling the program flow means controlling which functions and expressions will be executed. Imperative languages rely mainly on conditional constructors like if
, but here in the functional world, pattern matching plays the central role. However, pattern matching is often misunderstood and challenging for beginners to comprehend, which is why half of this chapter is dedicated to understanding it.
We’ll then use pattern matching to decide which function to dispatch to have a control flow mechanism. By the end of this chapter, we’ll see some Elixir control flow structures that use logical and pattern-matching expressions to simplify common expressions. Let’s take the first step and learn about pattern matching.
Elixir’s pattern matching shapes everything we program. It’s useful for assigning variables, unpacking values, and deciding which function to invoke. The basis of pattern matching is that it tries to make two things match, and it does something ...