Elixir: overloading functions with varying clarity

Is there any way to define overload functions with different clarity, for example, in C # I can just do:

foo(bar)

or

foo(bar, baz)

At Elixir, the only way to do this is to put them in separate modules, which will be pretty dirty. Is there any way around this?

Edit: I made the wrong assumption. Examples of overloaded functions that I saw turned out to be the same, so I (erroneously) suggested that this is a requirement. Functions are uniquely identified by their name and arity, so you can actually overload functions with different clarity.

+4
source share
2 answers

Erlang Elixir, ( #), arity, foo(bar) foo(bar, baz) . , "" Elixir, - sum:

defmodule Math do
  def sum(list),       do: sum(list, 0)
  def sum([], acc),    do: acc
  def sum([h|t], acc), do: sum(t, acc + h)
end
+12

. 8.3 . :

. , Elixir , , . , , :

defmodule Math do
  def zero?(0) do
    true
  end

  def zero?(x) when is_number(x) do
    false
  end
end

Math.zero?(0)  #=> true
Math.zero?(1)  #=> false

Math.zero?([1,2,3])
#=> ** (FunctionClauseError)

( clauses ) .

+1

Source: https://habr.com/ru/post/1540157/


All Articles