Erlang中函数参数列表的可变长度 [英] Variable length of function argument list in Erlang
问题描述
我知道我可以写:
function() - >功能([])。
函数(X)当不是is_list(X) - >函数([X]);
函数(X) - > do_something_with_arguments(X)。
但是我想避免这种技巧。
一种方法是传递列表中的所有参数:
function(ListOfParameters )
然后你可以迭代上述 ListOfParameters
。这样,您可以让您的函数声明能够接受任何数量的参数,只需向声明添加更多条款即可,但我不确定这是您希望的。您是否沿着C vararg
参数列表的方向思考?在正面的情况下,请阅读下一段。
你必须记住,Erlang是基于模式匹配的。函数声明中的参数在调用函数时用作匹配模式。您必须留下您的程序设计心态,才能充分利用埃尔朗的力量。
Is it possible to define function with argument list of variable length?
I know I can write just:
function() -> function([]).
function(X) when not is_list(X) -> function([X]);
function(X) -> do_something_with_arguments(X).
But I want to avoid this technique.
One way to do it is to pass all arguments in a list:
function(ListOfParameters)
and then you can iterate over the said ListOfParameters
. This way, you can have your function declaration be able to accept any number of "parameters", just add more terms to the declaration... but I am not sure that's what you were hoping. Are you thinking along the lines of a C vararg
parameter list? In the positive case, read the next paragraph.
You have to remember that Erlang is based on pattern matching. The arguments in the function "declaration" serve as matching pattern when a function is invoked. You'll have to leave aside your "procedural programming" mindset in order to fully harness Erlang's power.
这篇关于Erlang中函数参数列表的可变长度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!