2 ms·
Elixir uses pattern matching for its functions. You can define multiple functions with the same name, and which function is used depends on which one "matches"
by jmcgough 9y ago
Elixir uses pattern matching for its functions. You can define multiple functions with the same name, and which function is used depends on which one "matches" first, based on the arguments.
E.g
############
# no args
def my_func() do: (something) end
# an array arg, assigning the first to "head and the rest to "tail"
def my_func([ head | tail ]) do: (something) end
# two args, so you'd call this my_func/2 instead of my_func/1.
def my_func([], %{key: val}) do: (something) end
# definition with a guard clause, so it checks the value of the arg when determining whether it matches
def my_func(val) when (val > 10) do: (something) end
# wildcard matcher for any single arg passed
def my_func(_) do: (something) end
############
Pattern matching was my gateway drug for getting into Elixir, and it's just the tip of the iceberg when it comes to what makes the language great to work with. It's particularly elegant when pattern matching responses from HTTP requests, using switch statements. No need to put try catch blocks around everything, just pattern match against a tuple with :ok and a tuple with :error