Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best Practices For Variable Arity Elixir Functions?

Tags:

elixir

What are the best practices for handling variable arity in Elixir without causing unnecessary complexity & case matching down the line?

Python example:

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

    return

How is param3 best handled in Elixir?

like image 781
Emily Avatar asked Apr 19 '17 08:04

Emily


2 Answers

This is a very common pattern in Elixir. The last argument should be a list (Keyword list to be specific) and have a default of []. In Elixir, if the last argument is a keyword list, you don't need to add the []s around the list. For example:

def do_lots(arg1, arg2, opts \\ []) do
  one = opts[:one] || :default
  two = opts[:two] # default to nil if it's 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

The other option to handle a variable sized arguments is to pass them all as a list. This makes the function arity 1 and you can process them as needed.

Finally, you can pass some or all of the args as a map. This has the benefit of allowing you to pattern match on the map and create multiple function clauses based on the keys passed in the map.

Keep in mind that you can't easily patten match on Keyword list because they are order dependent.

like image 156
Steve Pallen Avatar answered Nov 12 '22 13:11

Steve Pallen


The best way is to use default parameters:

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

But it actually creates two functions - one with two parameters and another one with three.

like image 26
PatNowak Avatar answered Nov 12 '22 13:11

PatNowak