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:


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

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 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}

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


Enum.take(l, 2)