An idiomatic elixir to perform if the parameters are not zero?

How to proceed to filtering invalid parameters, such as nil or an empty list, before proceeding with the processing of parameters?

Using the case below seems common, but this is not clear code - I'm sure there is a simpler and more idiomatic way to do this.

  def load(token) do case token do nil -> nil [] -> nil token -> process(token) end end 
+6
source share
2 answers

If a function has multiple sentences, Elixir will execute each sentence until it finds one that matches. This allows you to "filter" based on the arguments provided - especially useful if functions do not have common logic.

 def load([]), do: IO.puts("empty") def load(token) when token == nil, do: IO.puts("nil") # Matching `nil' is OK too. def load(token), do: process(token) 

The second paragraph illustrates the use of guards that allow more general matches, the number of predicates that are valid as guards , all of which can be attached to (almost) any expression that is used to switch functional arguments, recursively or otherwise.

This agreement applies to all existing BEAM languages ​​and is useful to keep in mind when reading the OTP documentation.

+6
source

I prefer

 def load(nil), do: nil def load([]), do: nil def load(token), do: process(token) 

You can also do:

 def load([]), do: nil def load(token) when not is_nil(token), do: process(token) def load(_), do: nil 

But I would not compare token == nil , because you will get a warning from the compiler.

+1
source

All Articles