Haskell cartesian product of infinite lists

前端 未结 4 1167
青春惊慌失措
青春惊慌失措 2021-02-13 00:13

I want to generate a vectorspace from a basis pair, which looks something like:

genFromPair (e1, e2) = [x*e1 + y*e2 | x <- [0..], y <- [0..]]
4条回答
  •  不思量自难忘°
    2021-02-13 01:20

    Piggybacking on hammar's reply: His approach seems fairly easy to extend to higher dimensions:

    Prelude> import Data.List.Ordered
    Prelude Data.List.Ordered> import Data.Ord
    Prelude Data.List.Ordered Data.Ord> let norm (x,y,z) = sqrt (fromIntegral x^2+fromIntegral y^2+fromIntegral z^2)
    Prelude Data.List.Ordered Data.Ord> let mergeByNorm = mergeAllBy (comparing norm)
    Prelude Data.List.Ordered Data.Ord> let sorted = mergeByNorm (map mergeByNorm [[[(x,y,z)| x <- [0..]] | y <- [0..]] | z <- [0..]])
    Prelude Data.List.Ordered Data.Ord> take 20 sorted
    [(0,0,0),(1,0,0),(0,1,0),(0,0,1),(1,1,0),(1,0,1),(0,1,1),(1,1,1),(2,0,0),(0,2,0),(0,0,2),(2,1,0),(1,2,0),(2,0,1),(0,2,1),(1,0,2),(0,1,2),(2,1,1),(1,2,1),(1,1,2)]
    

提交回复
热议问题