Show how the single comprehension [(x , y) | x ← [1, 2, 3], y ←
[4, 5, 6]] with two generators can be re-expressed using two comprehensions
with single generators. Hint: make use of the library function concat
and nest one comprehension within the other.
It's been easy up until now, but I can't figure out how to nest one comprehension within the other. Any ideas besides reading SICP?
Name:
Anonymous2010-03-28 10:20
Read JAVA TUTORIALS
Name:
Anonymous2010-03-28 10:29
Is there anything wrong with [(x,x+3)|x<-[1,2,3]]? Is it too obvious?
Name:
Anonymous2010-03-28 10:30
>>3
That just gives [(1,4),(2,5),(3,6)]. The original example gives [(1,4),(1,5)...(3,5),(3,6)]
>>1
IT tells you in the hint [Anonymous@/prog/ ~]$ ghci
GHCi, version 6.10.3: http://www.haskell.org/ghc/ :? for help
Loading package ghc-prim ... linking ... done.
Loading package integer ... linking ... done.
Loading package base ... linking ... done.
Prelude> :t concat
concat :: [[a]] -> [a]
Prelude> [(x,y) | x <- [1,2,3], y <- [4,5,6]]
[(1,4),(1,5),(1,6),(2,4),(2,5),(2,6),(3,4),(3,5),(3,6)]
Prelude> concat [ [(x,y)| y <- [4,5,6]] | x <- [1,2,3] ]
[(1,4),(1,5),(1,6),(2,4),(2,5),(2,6),(3,4),(3,5),(3,6)]
The problem is in that Haskell's (and python's) comprehension syntax the tightest loops are farthest away from the body, when IMO they should be together. [Anonymous@/prog/ ~]$ rlwrap ikarus
Ikarus Scheme version 0.0.4-rc1+ (revision 1870, build 2010-03-23)
Copyright (c) 2006-2009 Abdulaziz Ghuloum