user3053042
user3053042

Reputation: 97

How to create a recursive zipWith function in Haskell?

So far I have:

miZipWith f [] [] = []
miZipWith f (x:xs) [] = []
miZipWith f [] (y:ys) = []
miZipWith f (x:xs) (y:ys) = f y: miZipWith f xs ys

----miZipWith f (x:xs) (y:ys) = f x : f y : miZipWith f xs ys

But this only "zips" the function f with the second list. How do I include the first list too?

*Main> miZipWith (*2) [1,2,3,4] [5,6,1]
[10,12,2]

Upvotes: 0

Views: 1205

Answers (1)

The Internet
The Internet

Reputation: 8123

The zipWith function goes like this:

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

Your assumption is that the function f takes only one argument, but it in fact takes two (the head of both lists).

Upvotes: 5

Related Questions