TL;DR
In the previous post, we explained how to pattern-match Elixir Bitstrings and Binaries. Today we move on to compound pattern matching. This post is part of the functional language series, and it is based on the remarkable book Elixir In Action by Sasa Juric.
What Is Compound
com·pound1
noun | ˈkämˌpound |
It is composed of two or more separate elements; a mixture: the air smelled like a compound of diesel and gasoline fumes.
So compound pattern matching is when we do several pattern matching at the same time. By doing that, you reduce the amount of boilerplate code.
Example
In the screenshot above, we first do a pattern match of the current time in the NaiveDateTime
Struct to current_date
variable, and after that, at the same time, we do a pattern match of current_time NaiveDateTime second
attribute to second
variable. Using one-liner, we pattern match the whole NaiveDateTime Struct and current time second value.
Remember
- the pattern matching is done from right to left. From expression to a pattern.
Comments are closed.