Hello everyone,
One of the most attractive features of list comprehensions is their ability
to avoid nested loops
for i <- [:a, :b, :c], j <- [1, 2], do: {i, j} # Happy dev :)
flat_map([:a, :b, :c],
fn i ->
map([1,2],
fn j ->
{i, j}
end)
end) # Sad dev :(
Something that I have wanted for a long time is a way to do the same thing
as list comprehensions, but with the Enum syntax.
Enum.product([ [:a,:b,:c], [1,2] ])
|> Enum.map( {i, j} -> ... end) # Same tuple syntax as zip
This *could* be extended further by adding nested access like *get_in/2*
carts = [
products: [
%{name: "shirt",
coupons: 101, 202
},%{name: "pants",
coupons: 303, 404
}]
}, %{
products: [
%{name: "T-shirt",
coupons: 101, 202
},%{name: "shorts",
coupons: 303, 404
}]
}
]
Enum.product(carts, [:products, :coupons])
|> Enum.map( {cart, product, coupon} -> ... end) # Every Layer of nesteing
is kept available via tuple syntax
# Alternative syntax where Enum.product/2 :: left, right ->
Enum.product([left, right]) would work
Enum.product(carts, :products)
|> Enum.product(:coupons)
|> Enum.map( {{cart, product}, coupon} -> ... end)
This is cool and all, but what about Stream.product? Unfortunately, Streams
are not quite as simple. Streams don't always have a finite length.
natural_numbers = Stream.unfold(1, fn n -> n + 1 end)
for i <- natural_numbers, j <- natural_numbers, do: {i, j} # ????????
I don't want to get into too much depth on Stream.product here because
making it work safely with Streams of unknown length requires a somewhat
math heavy explanation. If we get the green light on Enum.product I will
make the suggestion for Stream.product. The only thing that's important is
that it is possible via some higher dimensional pairing function magic :)
--
You received this message because you are subscribed to the Google Groups
"elixir-lang-core" group.
To unsubscribe from this group and stop receiving emails from it, send an email
to [email protected].
To view this discussion on the web visit
https://groups.google.com/d/msgid/elixir-lang-core/9039f6dd-dbfa-48fb-b95c-3c1e2353986b%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.