Search code examples
listhaskellziplist-comprehensionwinghci

Rewriting zipWith function using list comprehension


I've rewritten the zipWith function using recursion, and now I am trying to rewrite it using list comprehension. I have run into quite a few binding errors and I know that my second line is incorrect. This is the function I have that works like zipWith using recursion:

zipW :: (a -> b -> c) -> [a] -> [b] -> [c] 
zipW _ [] _ = []  
zipW _ _ [] = []  
zipW f (x:xs) (y:ys) = f x y : zipW f xs ys

And this is my attempt to rewrite it as list comprehension:

zipW2 :: (a -> b -> c) -> [a] -> [b] -> [c]
zipW2 f xs ys = [f x y | (x, y) <- zipW2 f xs ys]

I am not sure how to correct the second statement so that it works like zipWith and allows me to choose the operator.


Solution

  • You will need Parallel List Comprehensions extension:

    {-# LANGUAGE ParallelListComp #-}
    
    zipWith' :: (a -> b -> c) -> [a] -> [b] -> [c]
    zipWith' f xs ys = [f x y | x <- xs | y <- ys]