[Haskell-cafe] Generalized list-comprehension

Ron de Bruijn rondebruijn at yahoo.com
Sat Jan 31 07:35:38 EST 2004

Hi there,

I have written this little function:

f :: (Num a, Enum a) => a -> [[a]]
f n =  [[a]|a<-fu n] ++ [a:[b]|a<-fu n,b<-fu n] ++
[a:b:[c]|a<-fu n,b<-fu n,c<-fu n]
fu n = [1..n]

This is an example of the function in action:

*Mod> f 4

This is ofcourse nice and all, but I need a function
that does this same trick, but then doesn't only
generate listelements
of the maximum hard-coded length of three, but to
length m, where m is an extra parameter.
It's important that the elements are precisely in this

I tried rewriting the listcomprehension to map, concat
and filter, but that only complicated things.

There is a possibility where I can write a function
that gives the next of a list. So the next of [1,1,1]
would be [1,1,2], but that would be somewhat
inefficient when the list becomes large.
Then I just call this function with (replicate n (head
$ fu n)) and (last $ fu n).
Then I just apply this function next to the rest,
until I reach a state where all elements of the list
equal the last value of the inputlist, so I have the
required list of length n.
Then to simply get the complete list as in function f.
I need to map(\x->otherFunction x) [1..], but this
"next"-function is almost identical to what the
built-in listcomprehension does.
I just don't like my solution.

Then I can probably use Template Haskell(which I have
never used), but that seems overkill.

So does anyone has a better solution?

Greets Ron

Do you Yahoo!?
Yahoo! SiteBuilder - Free web site building tool. Try it!

More information about the Haskell-Cafe mailing list