The real issue to understand here is immutability. Enum.each always returns :ok and it has no access to variables outside of its scope, so there is no use in assigning to a var within a function passed to Enum.each. As you gain more experience in functional style programming, you’ll start thinking in higher-order functions. Those are great building blocks that can be combined in many ways to make your exercise clear and concise (to those familiar with functional style). Here’s two ways I’d solve it:
iex(63)> list1 = [
...(63)> [1 ,2,3,4,"nil"],
...(63)> [6,7,8,9,10,],
...(63)> [11,"nil",13,"nil",15],
...(63)> [16,17,"nil",19,20] ]
[
[1, 2, 3, 4, "nil"],
[6, 7, 8, 9, 10],
[11, "nil", 13, "nil", 15],
[16, 17, "nil", 19, 20]
]
iex(64)> Enum.flat_map(list1, fn row -> Enum.filter(row, &(&1 in 10..20)) end)
[10, 11, 13, 15, 16, 17, 19, 20]
iex(65)> for row <- list1, elt <- row, elt in 10..20, do: elt
[10, 11, 13, 15, 16, 17, 19, 20]
In the first example, I’ve combined two higher-order functions (flat_map and filter) with an anonymous function (invoking the in operator). The second is a for comprehension, which is more advanced. It should not be confused with a for loop. Comprehensions are much more powerful.


















