Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

List comprehension vs Enum.filter

Tags:

elixir

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?

like image 644
chx Avatar asked Mar 09 '23 02:03

chx


1 Answers

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
like image 200
Dogbert Avatar answered Apr 08 '23 05:04

Dogbert