Pattern match a list of any size in Elixir

Viewed 13803

I'm new to Elixir. I want to define a function that accepts only lists, but that can be of any size.

I could define a function that accepts an empty list like this:

def doit(my_list = []) do
  IO.puts my_list
end

or just one item, like this:

def doit([first]) do
  IO.puts my_list
end

but how do I allow any size list? I know I can accept anything like this:

def doit(my_list) do
  IO.puts my_list
end

but wouldn't it be more correct to enforce that it is a list using pattern matching?

3 Answers

You can do it as below with pure pattern match and without the guards:

def any_list(list = [head | tail = []]) do IO.puts("Single Element") end

def any_list(list = [head | tail ]) do IO.puts("Any list") end

def any_list([]) do IO.puts("Empty list") end

Related