Hello! I’m Scott. I’m new to Elixir, and to the forums.
I have a question I’ve searching here and on StackOverflow, and haven’t managed to find anything on this.
I’m wondering what’s the best/most idiomatic location/method for pattern matching: using multiple pattern-matched function definitions, or using a single function with a
case statement? To take an example from my solution to the exercism.io Elixir stream’s Rotational Cipher problem:
defp shift_by(char, amount) when char in @lower_case do char |> shift_from_base(?a, amount) end defp shift_by(char, amount) when char in @upper_case do char |> shift_from_base(?A, amount) end defp shift_by(char, _), do: char
But this could just as easily be written:
defp shift_by(char, amount) do case char do char when char in @lower_case -> char |> shift_from_base(?a, amount) char when char in @upper_case -> char |> shift_from_base(?A, amount) _ -> char end end
Ignoring any infelicities or good abstractions I’ve failed to muster (and the actual details of the implementation), I’m wondering which is the more idiomatic way of writing this? Are there advantages to using pattern matching in function definitions instead of
case statements, or vice versa?
To my eye, multiple function definitions reads better, but I’ve noticed that on exercism, people tend to put their pattern matching in a
case. Maybe my preference for putting pattern matching in function
switch blocks showing?