Zip with default value instead of dropping values?

后端 未结 9 827
夕颜
夕颜 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 19:09

    This should do the trick:

    import Data.Maybe (fromMaybe)
    
    myZip dx dy xl yl = 
      map (\(x,y) -> (fromMaybe dx x, fromMaybe dy y)) $ 
        takeWhile (/= (Nothing, Nothing)) $ 
        zip ((map Just xl) ++ (repeat Nothing)) ((map Just yl) ++ (repeat Nothing))
    
    main = print $ myZip 0 1 [1..10] [42,43,44]
    

    Basically, append an infinite list of Nothing to the end of both lists, then zip them, and drop the results when both are Nothing. Then replace the Nothings with the appropriate default value, dropping the no longer needed Justs while you're at it.

提交回复
热议问题