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?
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)> Enum.map([[1, 2], [3, 2], [4, 1]], fn [left, right] -> left < right end)
[true, false, false]
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):
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.