Best Recommendations for Arity Elixir Variable Functions?

What are the best methods for handling the arity variable in Elixir without causing unnecessary complexity and matching events along the line?

Python example:

def function_with_optional_param(param1, param2, param3=None): if not param3: param3 = "Whatever" return 

What is the best way to handle param3 in Elixir?

+5
source share
2 answers

This is a very common sample in Elixir. The last argument must be a list (a specific list of keywords) and have a default value of [] . In Elixir, if the last argument is a list of keywords, you do not need to add [] to the list. For instance:

 def do_lots(arg1, arg2, opts \\ []) do one = opts[:one] || :default two = opts[:two] # default to nil if it not passed # do something with arg1, arg2, one, and two end def my_func do arg1 |> do_lots(2) |> do_lots(49, one: :question) |> do_lots(99, two: :agent) |> do_lots(-1, one: 3, two: 4) end 

Another option for handling variable-sized arguments is to pass them all in a list. This makes the arity 1 function, and you can process them as needed.

Finally, you can pass some or all of the arguments as a map. This gives you the opportunity to match the template on the map and create several functional sentences based on the keys transmitted on the map.

Keep in mind that you cannot easily stroke a match in a list of keywords, because they are order dependent.

+7
source

The best way is to use the default options:

 def function_with_optional_param(param1, param2, param3 \\ "Whatever") do # something end 

But he actually creates two functions: one with two parameters, and the other with three.

+2
source

Source: https://habr.com/ru/post/1266898/


All Articles