I can write
unitlist |> Enum.filter(&(s in &1))
or I can write
for u <- unitlist, s in u, do: u
What is the difference in capabilities of the two constructs?
For this particular case they're identical no matter what the value of unitlist
is -- they both accept any Enumerable and run the s in &1
check on each item and return a new list for those returning a truthy value.
for
has many more features than what Enum.filter
can do alone: You can have iterate through multiple enumerables and generate a flat list of results. You can have a fallible pattern on the left of <-
and for
will silently skip over those items instead of throwing an error. You can modify the value returned after the check. The following code snippet demonstrates all this:
iex(1)> for a <- 1..3, b = 2 <- 1..3, a > 1, do: {a, b}
[{2, 2}, {3, 2}]
A for
can be desugared to a combination of Enum.map
, if
, and Enum.flat_map
. The above is the same as this:
Enum.flat_map(1..3, fn a ->
Enum.flat_map(1..3, fn
b = 2 ->
if(a > 1, do: [{a, b}], else: [])
_ ->
[]
end)
end)
|> IO.inspect
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With