43

我想知道长生不老药中的方法名称到底是什么:

array = [1,2,3]
module_name = :lists
method_name = :nth                  # this not working
module_name.method_name(1, array)   # error, undef function lists.method_name/2
module_name.nth(1, array)           # returns 1, module_name is OK. It's an atom

但我可以在 erlang 中做几乎相同的事情:

A = [1,2,3].
X = lists.
Y = nth.
X:Y(1,A).  #  returns 1

我怎么能在长生不老药中做到这一点?

4

1 回答 1

60

您可以使用apply/3which 只是:erlang.apply/3. 它只是简单地从 的数组中调用给定的. functionmodulearguments由于您将参数作为模块和函数名称传递,因此您可以使用变量。

apply(:lists, :nth, [1, [1,2,3]])
apply(module_name, method_name, [1, array])

如果您想了解更多有关 elixir 如何处理函数调用(以及其他所有内容)的信息,您应该查看quoteand unquote

contents = quote do: unquote(module_name).unquote(method_name)(1, unquote(array))

它返回函数调用的同音表示。

{{:.,0,[:lists,:nth]},0,[1,[1,2,3]]}

您可以unquote使用引用的函数调用Code.eval_quoted/3

{value, binding} = Code.eval_quoted(contents)

编辑:这是一个使用 Enum.fetch 和 var 的示例。

quoted_fetch = quote do: Enum.fetch([1,2,3], var!(item));             
{value, binding} = Code.eval_quoted(quoted_fetch, [item: 2])
于 2012-11-05T17:38:40.950 回答