haskell

How to zip lists with different length?


How can I zip two lists like

["Line1","Line2","Line3"]
["Line4","Line5"]

without discarding rest elements in first list?

I'd like to zip extra elements with empty list, if it can be done.


Solution

  • zipWithPadding :: a -> b -> [a] -> [b] -> [(a,b)]
    zipWithPadding a b (x:xs) (y:ys) = (x,y) : zipWithPadding a b xs ys
    zipWithPadding a _ []     ys     = zip (repeat a) ys
    zipWithPadding _ b xs     []     = zip xs (repeat b)
    

    As long as there are elements, we can simply zip them. As soon as we run out of elements, we simply zip the remaining list with an infinite list of the padding element.

    In your case, you would use this as

    zipWithPadding "" "" ["Line1","Line2","Line3"] ["Line4","Line5"]
    -- result: [("Line1","Line4"),("Line2","Line5"),("Line3","")]