I am curious when I should be using pattern matching vs guard clauses when defining functions.
For example with pattern matching:
defmodule Exponent do
def power(value, 0), do: 1
def power(value, n), do: value*power(value, n-1)
end
vs guard clause:
defmodule Exponent do
def power(value, n) when n==0, do: 1
def power(value, n), do: value*power(value, n-1)
end
I mean both produce the same result but is one solution preferred over the other? And if so why?
I'm new to Elixir, so the answer to this question is not readily apparent to me (yet). Thanks in advance.
Guards are more powerful than pattern matching, but they introduce a layer of complexity that might be unnecessary. For simple equality checks like in your example, they should be equivalent in terms of performance. I recommend trying to use pattern matching first in order to keep things simple. You can then fall back to a guard clause if absolutely necessary. Yet, it might occasionally make sense to do otherwise when it aids readability, e.g.
def sign(x) when x < 0, do: -1
def sign(x) when x == 0, do: 0
def sign(x) when x > 0, do: 1
I suppose the "proper" use case for the equality operator in guard clauses is when it is used as part of more complex expressions, e.g.
def divisible?(x, divisor) when rem(x, divisor) == 0, do: true
def divisible?(_x, _divisor), do: false
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With