How do I reject pattern that does not match what I want?

I’m new to Elixir and stuck with this list pattern matching problem. I have a list like this [[1,2,3], [4,5,6],[7,8,9],[1]] and want to map it with the function [figure1] but got array because as you can see the last index is contain only [1]. This would be a piece of cake in other language :slight_smile:

figure1

def get_two(l) do
  [first, second | _] = l
end

Thank before hand

Mapping means transforming each element in a collection. If you filter out elements that’s no longer just a mapping operation. You could either use Enum.filter and Enum.map after each other or Enum.reduce / Enum.reduce_while / for to do what you want to do in one pass.

1 Like
case l do
  [first, second | _] -> {first, second}
  [first] -> {first}
end

https://hexdocs.pm/elixir/Kernel.SpecialForms.html#case/2

def get_two([first, second | _]), do: {first, second}
def get_two([first]), do: {first}

Alternatively:

Enum.take(l, 2)

https://hexdocs.pm/elixir/Enum.html#take/2

3 Likes