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"
...
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"
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)
Nice post, I would prefer guard condition
Great! And well remembered! The guard condition approach made the code cleaner. Thank you!