2 ms·
There's only one situaton where I prefer a single function with a nested case: when there is a datatype guard check for an argument that applies to all invocati
by mikhailfranco 3y ago
There's only one situaton where I prefer a single function with a nested case: when there is a datatype guard check for an argument that applies to all invocations (precondition). This belongs on the function, then the case is pure discrimination within that type.
If multiple function heads were used, you might have to repeat the typecheck guard every time, which is ugly in code, but probably not inefficient (the Erlang pattern/guard compiler is insanely good).
- lkuty 3y agoIn Phoenix core_components.ex, you have an interesting way of dealing with common code and also keeping the valuable pattern matching with functions. This way of handling things may not be applicable to every situation. def input(%{field: %Phoenix.HTML.FormField{} = field} = assigns) do assigns |> assign(field: nil, id: assigns.id || field.id) # <-- ALLOWS TO AVOID RE-ENTERING THIS FUNCTION CLAUSE |> assign(:errors, Enum.map(field.errors, &translate_error(&1))) |> assign_new(:name, fn -> if assigns.multiple, do: field.name <> "[]", else: field.name end) |> assign_new(:value, fn -> field.value end) |> input() # <-- RECURSE WHICH ALLOWS TO CHOOSE THE RIGHT FUNCTION CLAUSE BELOW end def input(%{type: "checkbox", value: value} = assigns) do ... end def input(%{type: "select"} = assigns) do ... end ...