[Haskell-cafe] Generalized list-comprehension

Koji Nakahara yu- at div.club.ne.jp
Sun Feb 1 15:22:01 EST 2004


Hi,

Another solution:

f m n = concat $ take m $ tail xs 
  where
    xs = [[]]:map (\x -> concatMap (\y -> map (y:) x) [1..n]) xs


f 3 4 gives your f 4.

Hope it helps,

Koji Nakahara


On Sat, 31 Jan 2004 07:35:38 -0800 (PST)
Ron de Bruijn <rondebruijn at yahoo.com> 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
> [[1],[2],[3],[4],[1,1],[1,2],[1,3],[1,4],[2,1],[2,2],[2,3],[2,4],[3,1],[3,2],[3,
> 3],[3,4],[4,1],[4,2],[4,3],[4,4],[1,1,1],[1,1,2],[1,1,3],[1,1,4],[1,2,1],[1,2,2]
> ,[1,2,3],[1,2,4],[1,3,1],[1,3,2],[1,3,3],[1,3,4],[1,4,1],[1,4,2],[1,4,3],[1,4,4]
> ,[2,1,1],[2,1,2],[2,1,3],[2,1,4],[2,2,1],[2,2,2],[2,2,3],[2,2,4],[2,3,1],[2,3,2]
> ,[2,3,3],[2,3,4],[2,4,1],[2,4,2],[2,4,3],[2,4,4],[3,1,1],[3,1,2],[3,1,3],[3,1,4]
> ,[3,2,1],[3,2,2],[3,2,3],[3,2,4],[3,3,1],[3,3,2],[3,3,3],[3,3,4],[3,4,1],[3,4,2]
> ,[3,4,3],[3,4,4],[4,1,1],[4,1,2],[4,1,3],[4,1,4],[4,2,1],[4,2,2],[4,2,3],[4,2,4]
> ,[4,3,1],[4,3,2],[4,3,3],[4,3,4],[4,4,1],[4,4,2],[4,4,3],[4,4,4]]
> *Mod>

<snip>


More information about the Haskell-Cafe mailing list