[Haskell-cafe] Generalized list-comprehension

Graham Klyne GK at ninebynine.org
Sat Jan 31 16:58:04 EST 2004

There was an exchange about "powerset" here some time ago, before and after 
this message:
I think some of the ideas suggested there might be adaptable to this 
problem:  look for sample code with sub-functions for generating 
combinations of a given length.

Alternatively, here's something to conjure with:
    concat [sequence $ replicate n [1,2,3,4] | n <- [1..4]]

(noting that the [1,2,3,4] and [1..4] can be parameterized.)


At 07:35 31/01/04 -0800, Ron de Bruijn wrote:
>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!
>Haskell-Cafe mailing list
>Haskell-Cafe at haskell.org

Graham Klyne
For email:

More information about the Haskell-Cafe mailing list