[Haskell-beginners] list monad question

David Virebayre dav.vire+haskell at gmail.com
Fri Oct 30 08:09:50 EDT 2009


On Fri, Oct 30, 2009 at 12:44 PM, Matthias Guedemann
<matthias.guedemann at ovgu.de> wrote:

> a friend of mine wanted to write function (in Perl) that creates all tuples of
> length 3 of the elements of a given list,
> e.g. [(0,0,0),(0,0,1),(0,0,2),...,(5,5,5)] for the list [0..5]. Trying to get
> better at Haskell, I wrote a small function using the list monad for this (tuples
> replaced with lists)
>
> all3 ls = do
>  a <- ls
>  b <- ls
>  c <- ls
>  return [a,b,c]

Almost there :

all3 ls = do
  a <- ls
  b <- ls
  c <- ls
  return (a,b,c)

For each element a of list ls , for each element b of the same list
ls, and for each element c of the same list ls, make a tuple of them.
return the list of tall the tuples.

You could also write it with a list comprehension :

all3 ls = [ (a,b,c) | a <- ls, b <- ls, c <- ls ]

David.


More information about the Beginners mailing list