<br><br><div class="gmail_quote">On Sun, Mar 9, 2008 at 7:27 PM, Philip Müller &lt;<a href="mailto:mail@philip.in-aachen.net">mail@philip.in-aachen.net</a>&gt; wrote:<br><blockquote class="gmail_quote" style="border-left: 1px solid rgb(204, 204, 204); margin: 0pt 0pt 0pt 0.8ex; padding-left: 1ex;">
Hi,<br>
<br>
I&#39;m just working through Hutton&#39;s &quot;Programming in Haskell&quot; and I found<br>
an exercise which I can&#39;t solve, although it looks simple. Maybe someone<br>
here could give me a hint?<br>
<br>
Exercise:<br>
Show how the single comprehension [(x,y) | x &lt;- [1,2,3], y &lt;- [4,5,6]]<br>
with two generators can be re-expressed using two comprehensions with<br>
single generators.<br>
Hint: make use of the library function _concat_.</blockquote><div><br>Another hint, list comprehensions are just values of type [ a ] (a would be Integer in this case). So in other words, in any place where you want a list, you can stick a list comprehension. In this case you want to take each x in xs, and then for each x you want to grab each y in ys, and return (x,y). Right, so we know how to do that first bit, the &quot;for each x in xs&quot; bit, right? Just do [ ... | x &lt;- xs ]. And now what do we want to do for each element of x? Well we want to do &quot;for each y in ys&quot;, right? So that&#39;s just another list comprehension [ ... | y &lt;- ys ].<br>
<br>Stick the two together and you get [ [ ... | y &lt;- ys] | x &lt;- xs ]. So what do we want to do to x and y? Well we want to pair them: [ [ (x,y) | y &lt;- ys] | x &lt;- xs ]. Now, this gives us a list of lists (because each element of x will yield a list of x,y pairs, where x is constant and y is each element in ys). To flatten this into a single list, you can use concat:<br>
concat [[ (x,y) | y &lt;- ys] | x &lt;- xs ]<br><br></div></div><br><br clear="all"><br>-- <br>Sebastian Sylvan<br>+44(0)7857-300802<br>UIN: 44640862