Haskell generalizing problem (involving list compr

2019-04-27 00:47发布

问题:

Let's say I want to know all the points on a (x, y) plane that are in the rectangle has.

I can calculate that using List Comprehensions, this way:

let myFun2D = [(x, y) | x <- [0..2], y <- [0..2]]

Now, if I want to accomplish the same for a (x, y, z) space, I can go the same way and do:

let myFun3D = [(x, y, z) | x <- [0..2], y <- [0..2], z <- [0..2]]

Is there a way to generalize this for any number of dimensions? If yes, how?

let myFunGeneralized = ?

Thanks

回答1:

Unfortunately, because [(a,a)] and [(a,a,a)] etc are of different types, you can't write one function to represent all of them.

Anyway, in general you could use

Prelude> let x = [0..2]
Prelude> import Control.Applicative 
Prelude Control.Applicative> (,,) <$> x <*> x <*> x
[(0,0,0),(0,0,1),(0,0,2),(0,1,0),(0,1,1),(0,1,2),(0,2,0),(0,2,1),(0,2,2),(1,0,0),(1,0,1),(1,0,2),(1,1,0),(1,1,1),(1,1,2),(1,2,0),(1,2,1),(1,2,2),(2,0,0),(2,0,1),(2,0,2),(2,1,0),(2,1,1),(2,1,2),(2,2,0),(2,2,1),(2,2,2)]

If you want an [[a]] instead, there is a very simple function for this:

Prelude> sequence (replicate 3 x)
[[0,0,0],[0,0,1],[0,0,2],[0,1,0],[0,1,1],[0,1,2],[0,2,0],[0,2,1],[0,2,2],[1,0,0],[1,0,1],[1,0,2],[1,1,0],[1,1,1],[1,1,2],[1,2,0],[1,2,1],[1,2,2],[2,0,0],[2,0,1],[2,0,2],[2,1,0],[2,1,1],[2,1,2],[2,2,0],[2,2,1],[2,2,2]]

or (thanks sdcvvc)

Prelude> import Control.Monad
Prelude Control.Monad> replicateM 3 x
[[0,0,0],[0,0,1],[0,0,2],[0,1,0],[0,1,1],[0,1,2],[0,2,0],[0,2,1],[0,2,2],[1,0,0],[1,0,1],[1,0,2],[1,1,0],[1,1,1],[1,1,2],[1,2,0],[1,2,1],[1,2,2],[2,0,0],[2,0,1],[2,0,2],[2,1,0],[2,1,1],[2,1,2],[2,2,0],[2,2,1],[2,2,2]]


回答2:

The list to tuple problem could be handled with Template Haskell like this (running ghci -XTemplateHaskell):

> import Language.Haskell.TH
> let x = [0..2]
> let tt n l = listE [tupE [[|l!!i|] | i <- [0..(n-1)]] | l <- sequence $ replicate n l ]
> $(tt 2 x)
[(0,0),(0,1),(0,2),(1,0),(1,1),(1,2),(2,0),(2,1),(2,2)]
> $(tt 3 x)
[(0,0,0),(0,0,1),(0,0,2),(0,1,0),(0,1,1),(0,1,2),(0,2,0),(0,2,1),(0,2,2),(1,0,0),(1,0,1),(1,0,2),(1,1,0),(1,1,1),(1,1,2),(1,2,0),(1,2,1),(1,2,2),(2,0,0),(2,0,1),(2,0,2),(2,1,0),(2,1,1),(2,1,2),(2,2,0),(2,2,1),(2,2,2)]


回答3:

You could use something like this:

myFun :: Integer -> [[Integer]] -- Param: number of dimensions
myFun dim = snd $
  until ((== 0) . fst) --recursive build your tuple
  (\(d,lst) -> (pred d,[x:l|x <- [0..2],l <- lst]))
  (dim,[[]])

This will give you a list of point lists, you can assume that all these sublists have the same length. It should work like this:

> myFun 0
  []
> myFun 1
  [[0],[1],[2]]
> myFun 2
  [[0,0],[0,1],[0,2],[1,0],[1,1],[1,2],[2,0],[2,1],[2,2]]