[Haskell-beginners] List Function

Brent Yorgey byorgey at seas.upenn.edu
Wed Apr 29 23:41:03 EDT 2009


On Wed, Apr 29, 2009 at 10:25:43PM -0400, Nathan Holden wrote:
> I don't know what you'd call it. Is there a function in any of the basic
> functions that does this something like this:
> 
> Sending two lists, [1,2,3] and [2,3,4] it would return
> [(1,4),(1,5),(1,6),(2,4),(2,5),(2,6),(3,4),(3,5),(3,6)]. I managed to code
> my way into returning a list of lists, which works. But it seemed like a
> very basic list/matrix function, so I honestly believe that the Haskell
> designers probably would've put it in.

Others' answers are probably more helpful for learning, but I also
wanted to point out that there is a Prelude function that does
something close to this (assuming you meant [4,5,6]), namely,
'sequence'.

  Prelude> sequence [ [1,2,3], [4,5,6] ]
  [[1,4],[1,5],[1,6],[2,4],[2,5],[2,6],[3,4],[3,5],[3,6]]
  Prelude> sequence [ [1,2], [3,4,5], [6,7] ]
  [[1,3,6],[1,3,7],[1,4,6],[1,4,7],[1,5,6],[1,5,7],[2,3,6],[2,3,7],[2,4,6],[2,4,7],[2,5,6],[2,5,7]]

However, explaining how/why sequence does this requires understanding
the list monad, which you may or may not want to tackle at this point.

If you import 'Control.Applicative' you can even do exactly what you
wanted, with pairs and all:

  Prelude Control.Applicative> liftA2 (,) [1,2,3] [4,5,6]
  [(1,4),(1,5),(1,6),(2,4),(2,5),(2,6),(3,4),(3,5),(3,6)]

Here, liftA2 is applying the function (,) to every possible pair of
values from the two lists.

-Brent


More information about the Beginners mailing list