Haskell cartesian product of infinite lists

前端 未结 4 1164
青春惊慌失措
青春惊慌失措 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:05

    Using the diagonal snippet from CodeCatalog:

    genFromPair (e1, e2) = diagonal [[x*e1 + y*e2 | x <- [0..]] | y <- [0..]]
    
    diagonal :: [[a]] -> [a]
    diagonal = concat . stripe
        where
        stripe [] = []
        stripe ([]:xss) = stripe xss
        stripe ((x:xs):xss) = [x] : zipCons xs (stripe xss)
    
        zipCons [] ys = ys
        zipCons xs [] = map (:[]) xs
        zipCons (x:xs) (y:ys) = (x:y) : zipCons xs ys
    

提交回复
热议问题