{-
Ex: 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.
This exercise took me a little longer to solve...
I found that I am not the only one who "stuck" with this problem.
Here is the link (http://www.oreillynet.com/onlamp/blog/2007/04/list_incomprehensions.html)
of chromatic's blog about this exercise.< His solution is:
concat [ zip [x, x, x] [y | y <- [4..6] | x <- [1,2,3] ]
I don't like his "hack" solution.
Because of the hard coded [x,x,x], it seems not good for me.
I would like to find more generic solution.
Finaly, I solve this exercise like:
-}
result = [(x,y) | x <- [1,2,3], y <- [4,5,6]]
result' = concat [ [ (x,y) | y <- [4,5,6] ] | x <- [1,2,3] ]
{-
I think my solution is more "generic".
In fact, it could express like:
[ (x,y) | x <- [x1, x2 .. xn], y <- [y1, y2 .. yn] ]
==
concat [ [ (x,y) | y <- [y1, y2 .. yn] ] | x <- [x1, x2 .. xn] ]
It can also generalization to n generators.
Below shows 3 generators case:
[ (x,y,z) | x <- xList, y <- yList, z <- zList ]
==
(concat.concat) [ [ [ (x,y,z) | z <- zList ] | y <- yList ] | x <- xList ]
n generators case:
[(x1,x2, .. ,xn) | x1<-x1List, x2<-x2List, .. , xn<-xnList]
==
(concat.concat... .concat) [[..[[ (x1,x2,..xn) | xn<-xnList] | xn-1<-xn-1List] .. ] | x1<-x1List ]
note: There are (n-1) concat functions composition.
-}
This entry was posted
on Friday, January 4th, 2008 at 5:12 pm and is filed under Haskell - PIH.
You can follow any responses to this entry through the RSS 2.0 feed.
You can leave a response, or trackback from your own site.