2 ms·
The big advantage is that it saves two levels of indentation and a lot of repeated pattern matching. def equal?(x,y) when x == y do true end def equ
by OkayPhysicist 3y ago
The big advantage is that it saves two levels of indentation and a lot of repeated pattern matching.
def equal?(x,y) when x == y do
true
end
def equal?(_,_), do: false
would be equivalent to
def equal?(x,y) do
case {x,y} do
{x,y} when x == y ->
true
_ ->
false
end
end
It's also handy in places like GenServers, where from a reading perspective clustering the hooks and their helper functions together is far more readable than the alternative.
def handle_call(:msg1,_from,_state) do
helper1()
helper2()
etc...
end
def helper1(), do: 1
def helper2(), do: 2
def handle_call(:msg2,_from,_state), do: :err
Is a lot better than
def handle_call(msg,_from,_state) do
case {msg, _from, _state} do
{:msg1,_from,_state} ->
helper1()
helper2()
etc...
{:msg2,_from,_state} -> :err
end
end
def helper1(), do: 1
def helper2(), do: 2
Especially remembering that you'll likely have a lot more than 2 message callbacks.