Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pattern matching: advantage over switch-case?

I'm learning Elixir, and can't see the advantage of pattern matching over good ol' switch case. What am I missing?

like image 808
tldr Avatar asked Sep 20 '26 08:09

tldr


1 Answers

In short, Elixir's pattern matching case will make you focus on the shape of your data. Instead of allowing just about any expressions in the language, and looking for a true condition, you show the reader what shapes in your data that are important to consider. It is more intention revealing.

Elixir has both case and cond. The former takes a value and runs different pattern matches on it. The latter doesn't take a value, but will instead evaluate some expressions until it finds one that's truthy. A cond works like if … elseif … else.

list = [3,2,1]
string = "abc"

case list do
  []        -> :empty             # won't match
  [1 | t]   -> :starts_with_one   # won't match
  [3, b, c] -> "3, #{b} and #{c}" # match!
  _         -> :fallback          # _ would match anything
end

cond do
  List.last(list) == 2     -> :two_at_the_end # false
  length(string) == 3      -> :three_letters  # true
  true                     -> :fallback
end

As you see, there's really nothing that connects the expression in cond. They don't have to act on the same data. You can also use expressions that are not allowed in pattern matching. Both these aspects make cond very flexible, but it also is kind of a code smell. There's no coherence to the block. Expressions can have side-effects. I need to look more carefully at a cond than a case.

In contrast, the case expression let's me very explicitly reason about the shape of my data. All the matching is done on the same data, so it has a natural cohesion. It tells a reader a lot about the author's expectations on some data. It's very intention revealing. It quickly shows the shapes the author expect the data to take, and any special cases that should be treated differently. When reading a case statement, you too can focus on the data.

Pattern matching also let you capture parts of the pattern. I capture the second and third list element in the matching pattern. They are only available inside the case block and won't "leak" out.

The restricted set of expressions allowed in a pattern match also means it's generally very fast.

like image 200
Martin Svalin Avatar answered Sep 22 '26 11:09

Martin Svalin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!