I'm learning Elixir and a little confused as to why we must branch using multiple definitions of the same function, instead of using the case statement. Here is an example from Elixir in Action, first edition page 81, for counting the lines in a file:
defmodule LinesCounter do
def count(path) do
File.read(path)
|> lines_num
end
defp lines_num({:ok, contents}) do
contents
|> String.split("\n")
|> length
end
defp lines_num({:error, _}), do: "error"
end
So we have two defp lines_num instances to handle the cases of :ok and :error. But doesn't the following do the same thing, arguably in a cleaner, and more concise way, and using only one function instead of three?
defmodule LinesCounterCase do
def count(file) do
case File.read(file) do
{:ok, contents} -> contents |> String.split("\n") |> length
{:error, _} -> "error"
end
end
end
Both work identically.
I don't want to learn incorrect idioms as I start out my journey on Elixir so clarifying the downsides of using the case statement in this way, is what I am looking for.