Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/vba/14.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Erlang 如何在Elixir中通过同时指定模块和方法名来动态调用方法?_Erlang_Metaprogramming_Elixir - Fatal编程技术网

Erlang 如何在Elixir中通过同时指定模块和方法名来动态调用方法?

Erlang 如何在Elixir中通过同时指定模块和方法名来动态调用方法?,erlang,metaprogramming,elixir,Erlang,Metaprogramming,Elixir,我想知道elixir中的方法名是什么: 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_na

我想知道elixir中的方法名是什么:

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

如何在elixir中实现这一点?

您可以使用
apply/3
,它只是
:erlang.apply/3
的包装。这很简单,因为您将参数作为模块和函数名传递,所以可以使用变量

apply(:lists, :nth, [1, [1,2,3]])
apply(module_name, method_name, [1, array])
如果您想进一步了解elixir如何处理函数调用(以及其他一切),您应该看看
quote
unquote

contents = quote do: unquote(module_name).unquote(method_name)(1, unquote(array))
返回函数调用的图标表示形式

{{:.,0,[:lists,:nth]},0,[1,[1,2,3]]}
您可以
unquote
使用

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

quoted_fetch = quote do: Enum.fetch([1,2,3], var!(item));             
{value, binding} = Code.eval_quoted(quoted_fetch, [item: 2])

好。所以方法名是一个原子。现在,我认为语法不允许我们用elixir编写
module.method
,对吧?我相信你是对的。我认为实现这一点的唯一方法是更改语法,以便在调用模块函数时使用原子(即
:list.:nth
)。我宁愿在这种情况下使用apply。谢谢。这个答案很有帮助。你能告诉我如何使用普通的长生不老药吗。类似于
Enum.fetch
?是否有变量或变量函数?quoted_fetch=quote do:Enum.fetch([1,2,3],var!(item));{value,binding}=Code.eval_quoted(quoted_fetch,[item:2])
quoted_fetch = quote do: Enum.fetch([1,2,3], var!(item));             
{value, binding} = Code.eval_quoted(quoted_fetch, [item: 2])