DEV Community

Cover image for Pattern Matching With Functions
Diego Novais
Diego Novais

Posted on

Pattern Matching With Functions

Hey, dev!

Imagine a scenario where you need to compare 2 numbers and return which one is the biggest.

In Elixir, we can do it by using an ternary if statement:

defmodule CompareNumbers do
  def the_bigger_number_is(number_01, number_02) do
    bigger_number = if number_01 > number_02, do: number_01, else: number_02

    "The number #{number_01} is greater than #{number_02}"
  end
end

number_01 = 10
number_02 = 5

IO.inspect(CompareNumbers.the_bigger_number_is(number_01, number_02))

=> "The number 10 is greater than 5"
Enter fullscreen mode Exit fullscreen mode

...

We can also use Pattern Matching With Functions to control the flow:

defmodule CompareNumbers do
  def the_bigger_number_is(number_01, number_02) do
    compare(number_01 > number_02, number_01, number_02)
  end

  defp compare(true, number_01, number_02) do
    "The number #{number_01} is greater than #{number_02}"
  end

  defp compare(false, number_01, number_02) do
    "The number #{number_02} is greater than #{number_01}"
  end
end

number_01 = 10
number_02 = 5

IO.inspect(CompareNumbers.the_bigger_number_is(number_01, number_02))

=> "The number 10 is greater than 5"
Enter fullscreen mode Exit fullscreen mode

Here, we create 2 private functions with the same name compare, and then, with pattern matching, we check if the first argument is true or false.

So, which of the 2 approaches above do you think is the best? Which makes the most sense?

Or, how could be better? Let me know in the comments below =D

Contacts
Email: contato@diegonovais.com.br
Linkedin: https://www.linkedin.com/in/diegonovais/
Twitter: https://twitter.com/diegonovaistech

Top comments (2)

Collapse
 
yasir_asarudeen profile image
Yasir Asarudheen

Nice post, I would prefer guard condition

defmodule CompareNumbers do
  def the_bigger_number_is(number_01, number_02) when number_01 > number_02 do
    "The number #{number_01} is greater than #{number_02}"
  end

  defp compare(number_01, number_02) do
    "The number #{number_02} is greater than #{number_01}"
  end
end

number_01 = 10
number_02 = 5

IO.inspect(CompareNumbers.the_bigger_number_is(number_01, number_02))

=> "The number 10 is greater than 5"
Enter fullscreen mode Exit fullscreen mode
Collapse
 
dnovais profile image
Diego Novais

Great! And well remembered! The guard condition approach made the code cleaner. Thank you!