药剂:功能与不同的arity重载 [英] Elixir: function overloading with different arity
问题描述
有没有什么办法可以用不同的arity来定义重载函数,例如在C#中我可以这样做:
foo(bar )
或
foo(bar,baz)
在Elixir中,唯一的方法是应该把它们放在单独的模块中,这会很快得到混乱。有没有办法解决它?
编辑:我做了一个错误的假设。我看到的重载函数的例子碰巧具有相同的参数,所以我(错误地)认为这是一个要求。函数是由它们的名称和参数唯一标识的,所以实际上可以用不同的函数重载函数。在许多其他语言(如C#)中,在Erlang和Elixir中,函数是由它们的名称和参数唯一标识的。 ,所以在技术上 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
is there any way to define overload functions with different arity, e.g in C# I can just do:
foo(bar)
or
foo(bar, baz)
In Elixir, the only way to do that would be to put them in separate modules, which will get messy pretty quickly. Is there any way around it?
Edit: I had made a wrong assumption. The examples of overloaded functions I saw happened to have the same arity, so I (wrongly) assumed that this was a requirement. Functions are uniquely identified by their name and arity, so you can in fact overload functions with different arity.
In Erlang and Elixir, and unlike many other languages (such as C#), functions are uniquely identified by their name and arity, so technically foo(bar)
and foo(bar, baz)
are totally different functions. But that's really just a technicality, to write an 'overloaded' function in Elixir, you would write something like the following definition of 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
这篇关于药剂:功能与不同的arity重载的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!