[Haskell-beginners] list monad question

Jan Jakubuv jakubuv at gmail.com
Fri Oct 30 08:23:27 EDT 2009

Hi Matthias,

On Fri, Oct 30, 2009 at 12:44:41PM +0100, Matthias Guedemann wrote:
> Hi,
> a friend of mine wanted to write function (in Perl) that creates all tuples of
> length 3 of the elements of a given list...
> all3 ls = do
>   a <- ls
>   b <- ls
>   c <- ls
>   return [a,b,c]
> Now I want to make it capable to create all combinations of length n instead of
> fixed length 3 (that's why list instead of tuple), but I don't really see how.

How about a recursive function like this:

    alln 1 ls = map (:[]) ls
    alln n ls = do
        a <- ls
        as <- alln (n-1) ls
        return (a:as)

Note that `ls :: [t]` and `all (n-1) ls :: [[t]]` has different types but
it's okay because both are in the list monad. 

Also, it can be done with list comprehensions:

    alln' 1 ls = [[a] | a<-ls] 
    alln' n ls = [a:as | a<-ls, as<-alln' (n-1) ls]


Heriot-Watt University is a Scottish charity
registered under charity number SC000278.

More information about the Beginners mailing list