GoodPixel Logo

Pattern Match Your Case Away

Ben Coppock
Ben Coppock

So you’ve discovered Elixir, and you’re smitten with pattern matching.

You pattern match to extract values from a map:

%{name: name} = %{name: "Ben", city: "Portland"}
# name = "Ben"

…or a list:

[first, second | _rest] = [10, 20, 30, 40]
# first = 10
# second = 20
# _rest = [30, 40]

You pattern match in function clauses to decide which one to use:

def favorites(%{favorites: []} = person) do
  "#{person.name} has no favorite things."
end

def favorites(%{favorites: favorites} = person) when is_list(favorites) do
  items = Enum.join(favorites, ", ")
  "#{person.name}'s favorite things are: #{items}"
end

And you pattern match in case clauses, too:

[
  {:person, "Allie"},
  {:dog, "Oliver"}
]
|> Enum.map(fn friend ->
  case friend do
    {:person, name} -> "#{name} is my friend."
    {:dog, name} -> "#{name} is my furry friend."
  end
end)
# ["Allie is my friend.", "Oliver is my furry friend."]

You’re matching like a pro! 🤓

But wait, we can simplify that… ☝️

Pattern matching can be used inside of anonymous functions, too—sometimes allowing us to avoid case statements like the one above:

[
  {:person, "Allie"},
  {:dog, "Oliver"}
]
|> Enum.map(fn
  {:person, name} -> "#{name} is my friend."
  {:dog, name} -> "#{name} is my furry friend."
end)
# ["Allie is my friend.", "Oliver is my furry friend."]

It’s nothing huge, but every little bit helps. The fewer and cleaner our lines of code, the better.

Subscribe!

Don’t miss my next post. Drop your email in the box below and get it straight in your inbox…