Search code examples
elixir

Pattern match a list of any size in Elixir


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?


Solution

  • As far as I know there's no single pattern to match any list. [] will match an empty list and [_ | _] will match any non-empty list, but there's no way to combine them using a pattern.

    You can do this with function guards though, using is_list/1:

    def doit(my_list) when is_list(my_list) do
      # my_list is guaranteed to be a list
    end