Hey there peeps!

In my last post I explained briefly how pattern matching in Elixir works and why it is such a powerful tool, but it was a pretty basic intro to the concept. I realized I need to expand that post a bit.

Goal of this post is not gonna be to make you a pattern matching expert but rather to show you how you might use it in some more real world example. Also we're gonna introduce the concept of a guard clause.

defmodule WeightCheck do
  def check(%{name: name, weight: weight}) when weight > 80 do
    IO.puts "You should go and workout #{name}"

  def check(%{name: name, weight: weight}) when weight < 65 do
    IO.puts "Eat more #{name}"

Lot's of things going on here but first line defines a module and the second line (def check) defines a function in Elixir. Also functions can have same names in Elixir as long as they check for different things. It's outside of scope of this post to explain this in more details, let's save that for another post.

%{name: name, weight: weight} part of a function definition means that when ever this function is called it will do a pattern match and only accept a map that has keys name and weight, otherwise it will raise an error. You just protected your function from a lot of situations out of the box.

Now for when part of the function syntax. That's something called a guard clause. I like to think of it as a second layer of protection on top of pattern matching. Because pattern matching comes in first and then right after that we have a guard clause which can start checking the condition only if pattern matching passes. It's pretty simple, in our example it checks if the weight is greater or less then a certain number. That's all there is to it. It's similar to a normal if statement but only within a function definition.

Let's see this in action ( ignore the name of the module it's not the same as in the post ):


These two combined make a powerful combo. They can save you from writing conditionals and simplify functions.

Hopefully this was helpful and you learned something new today. I would love to hear your feedback on this post via twitterz and redditz :)