how can we handle list of list in elixir?

I have a list of list which something look like this

[[a, b], [c, d], [e, f]]

I want to perform an operation on each of the list which is inside a list. It can return true or false.
but I want to know what is the best way to handle this?

Will enum.reduce will fit here?

Any Enum functions will work. It depends on whether you want to reduce it to a single value or if you want to map each pair to a boolean, or something else. The main technique you should be aware of is pattern matching in the anonymous function you pass to one of the Enum functions. That will make it clear you expect 2 element lists. For example:

iex(1)>[[1, 2], [3, 2], [4, 1]], fn [left, right] -> left < right end)
[true, false, false]

Thanks. How will reduce work here? For the same example. I didn’t understand when you’re saying we
want to reduce to a single value

yeah looks good. but maybe I don’t want list of boolean result. I think Enum.any? will also do the same thing right?

I’m not seeing the difficulty here. I have zero idea what your algorithm is. However, for the sake of example, if I wanted to see if the left value is less than the right value for all pairs in the list, (I’d actually use Enum.all? but for sake of learning):

iex(2)> Enum.reduce([[1, 2], [3, 2], [4, 1]],t rue,  fn [left, right], acc -> acc && (left < right) end)

The only difference is dealing with reduce – an initial value as the 2nd param to reduce plus an accumulator param for the anonymous function. There’s nothing different in dealing with the list of list as the original question asked.


Yes, I think Enum.any? will fit your requirement.
However, as I don’t know your algorithm. I assume that you want to check if have any value in nested list satisfy your specific requirement?
If it’s your intent, you can use List.flatten(your_list) |> Enum.any? to check with your condition.
It will flat your nested list and return TRUE when reach to a value fit your requirement. Otherwise it’ll travel all list and return FALSE.

iex(1)> List.flatten([[1, 2], [3, 4], [5, 6]]) |> Enum.any?(&(&1 == 3))