Zip with default value instead of dropping values?

后端 未结 9 812
夕颜
夕颜 2020-12-01 18:30

I\'m looking for a function in haskell to zip two lists that may vary in length.
All zip functions I could find just drop all values of a lists that is longer than the o

9条回答
  •  独厮守ぢ
    2020-12-01 18:52

    Here is another solution, that does work on infinite lists and is a straightforward upgrade of Prelude's zip functions:

    zipDefault :: a ->  b -> [a] -> [b] -> [(a,b)]
    zipDefault _da _db []     []     = []
    zipDefault  da  db (a:as) []     = (a,db) : zipDefault da db as []
    zipDefault  da  db []     (b:bs) = (da,b) : zipDefault da db [] bs
    zipDefault  da  db (a:as) (b:bs) = (a,b)  : zipDefault da db as bs
    

    and

    zipDefaultWith :: a -> b -> (a->b->c) -> [a] -> [b] -> [c]
    zipDefaultWith _da _db _f []     []     = []
    zipDefaultWith  da  db  f (a:as) []     = f  a db : zipDefaultWith da db f as []
    zipDefaultWith  da  db  f []     (b:bs) = f da  b : zipDefaultWith da db f [] bs
    zipDefaultWith  da  db  f (a:as) (b:bs) = f  a  b : zipDefaultWith da db f as bs
    

    @pigworker, thank you for your enlightening solution!

提交回复
热议问题