Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Idiomatic elixir to execute if params is not nil?

Tags:

elixir

How to go about filtering out invalid params like nil or empty list before proceed to process the params?

The case use below seems to be common but it's not clear code -- I am pretty sure there is a simpler and idiomatic way to do this.

 def load(token) do

   case token do
     nil -> nil
     [] -> nil
     token -> process(token)
   end

 end
like image 858
Teo Choong Ping Avatar asked Jun 13 '16 02:06

Teo Choong Ping


1 Answers

If a function has several clauses, Elixir will try each clause until it finds one that matches. This allows you to "filter" on the basis of supplied arguments - particularly useful if the functions share no 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 clause illustrates the use of guards which permit more general matches, there are a number of predicates that are valid as guards all of which can be attached to (almost) any expression which are used to switch upon function-arguments, recursively or otherwise.

This convention holds across all of the existing BEAM languages and is useful to keep in mind when reading OTP documentation.

like image 138
ŹV - Avatar answered Oct 19 '22 02:10

ŹV -