jschepmans
Creating sublists in a for comprehension
Hello all,
I’m going through the open source beta version of the Dockyard Academy curriculum (GitHub - DockYard-Academy/curriculum · GitHub) and I’m doing some exercises about for comprehensions.
In one of these exercises I have to convert the following nested Enum.map into a comprehension with three generators:
Enum.map(1..3, fn a -> Enum.map(1..3, fn b -> {a, b} end) end)
# Result:
[[{1, 1}, {1, 2}, {1, 3}], [{2, 1}, {2, 2}, {2, 3}], [{3, 1}, {3, 2}, {3, 3}]]
My best guess has only two generators and results in one list without sublists:
for a <- 1..3, b <- 1..3, do: {a, b}
# Result:
[{1, 1}, {1, 2}, {1, 3}, {2, 1}, {2, 2}, {2, 3}, {3, 1}, {3, 2}, {3, 3}]
I assume the third generator (the one I am still missing) will create the 3 sublists. But I have no clue how this generator would look like. Any ideas?
Most Liked
stevensonmt
I believe you need multiple comprehensions.
for a <- 1..3 do a end
|> IO.inspect
# [1,2,3]
for a <- 1..3, b <-1..3 do {a,b} end
|> IO.inspect
#[{1,1}, {1,2}, {1,3}, {2,1}, {2,2}, {2,3}, {3,1}, {3,2}, {3,3}]
for a <-1..3 do
for b <- 1..3 do {a,b} end
end
|> IO.inspect
# [[{1,1}, {1,2}, {1,3}], [{2,1}, {2,2}, {2,3}], [{3,1}, {3,2}, {3,3}]]
gregvaughn
I’m not sure whether to be proud or ashamed of myself ![]()
iex(40)> for x <- 1..3, row = (for y <- 1..3, do: {x,y}), z <- 1..3, x == z, do: row
[[{1, 1}, {1, 2}, {1, 3}], [{2, 1}, {2, 2}, {2, 3}], [{3, 1}, {3, 2}, {3, 3}]]
jschepmans
The wording was indeed incorrect - no specific amount of generators is needed to solve the exercise. It will be changed with a PR. Thanks everyone for your help!
Popular in Questions
Other popular topics
Categories:
Sub Categories:
Forums
Popular Tags
- #ecto
- #liveview
- #troubleshooting
- #learning-elixir
- #deployment
- #library
- #erlang
- #testing
- #genserver
- #mix
- #absinthe
- #remote-other
- #otp
- #plug
- #how-to-question
- #macros
- #postgres
- #channels
- #elixirconf
- #exunit
- #discussion
- #code-sync
- #javascript
- #podcasts
- #onsite
- #dialyzer
- #docker
- #authentication
- #umbrella
- #full-time-contract
- #podcasts-by-brainlid
- #ecto-query
- #elixir-ls
- #phoenix_html
- #iex
- #blog-post
- #graphql
- #genstage
- #ai
- #websockets
- #supervisor
- #elixirconf-us
- #advent-of-code
- #distillery
- #processes
- #api
- #forms
- #metaprogramming
- #security
- #hex









