[英]Can i import a function for any existing arity?
Let's say i have module with a function having heads with different arity. 假设我有一个模块,其功能具有不同的头部。 Is there a way to import this function in another module for all the available arities (without being explicit)?
是否有一种方法可以针对所有可用ar(未明确)将其导入到另一个模块中?
defmodule Math do
def plus(a, b) do
end
def plus(a, b, c) do
end
def plus(a, b, c, d) do
end
end
defmodule AdditiveCalculator do
# Explicit import
import Math, only: [plus: 2, plus: 3, plus: 4]
# What i'm hoping for
import Math, only: [plus: :all]
end
As far as I know, there is no such functionality in Elixir. 据我所知,Elixir中没有这样的功能。
See here for more details. 有关更多详细信息,请参见此处 。
EDIT: 编辑:
@tkowal brings up a great point in a comment above. @tkowal在上面的评论中提到了一个重点。 If you're trying to sum variable lists of integers the right approach is to pass the argument as a list of integers and then work with that.
如果要对整数的变量列表求和,正确的方法是将参数作为整数列表传递,然后使用该整数。 Like so:
像这样:
defmodule T do
def plus(l) when is_list(l), do: plus(l,0)
defp plus([], acc), do: acc
defp plus([item] = l, acc), do: acc + item
defp plus([head|tail] = l, acc), do: plus(tail, acc+head)
end
Then to use it, call it like this: 然后使用它,像这样调用它:
T.plus([1,2,3,4])
#=> 10
Your question makes an incorrect assumption about the nature of functions in Elixir. 您的问题对Elixir中函数的性质做出了错误的假设。 You say you have "a function having heads with different arity" and later "this function".
您说您具有“具有不同头的功能”,后来又具有“此功能”。
You don't have a single function with multiple heads. 您没有一个具有多个头的功能。 You actually have 3 different functions.
您实际上有3种不同的功能。 Functions are identified by both name and arity.
功能由名称和属性标识。
plus/2
, plus/3
and plus/4
may share a name, but they are not the same function. plus/2
, plus/3
和plus/4
可以共享一个名称,但是它们的功能不同。 See http://elixir-lang.org/crash-course.html#identifying-functions 参见http://elixir-lang.org/crash-course.html#identifying-functions
This is also why you need to explicitly list them out when specifying the only
option on an import
. 这也是为什么在指定
import
的only
选项时需要明确列出它们的原因。 You're importing those 3 distinct functions from the module. 您正在从模块中导入这3个不同的函数。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.