Idiomatic Elixir - Function Parameter Style
-
26-12-2019 - |
Question
draw and hand variables are lists. I want to move the top card off the draw and add it to the hand. This is the function:
def pick_up_card(draw, hand) do
[new_card | new_draw ] = draw
{hand ++ [new_card], new_draw}
end
I could rewrite it to a line shorter by including the [head | tail] part in the parameter list:
def pick_up_card([new_card | new_draw], hand) do
{hand ++ [new_card], new_draw}
end
Would that be more idiomatic Elixir? Would it be harming readability? I would imagine the code would be easier to read later if the function definition had the name of the incoming list rather than a Head|Tail call.
Is it a matter of personal taste, or am I better saving that line of code and sticking the Head|Tail call in the function definition?
Solution
In my opinion it's better to put it in the parameter list. You would probably like to write another clause
def pick_up_card([], _), do: raise "Nothing to pickup"
in the near future, don't you? :) Or care for other special cases - so it's better to put it in the header from the very beginning.