I'm trying to write the Zipwith
function in Haskell.
If I run it with the following values, it should return this result:
Prelude> zipWith (+) [10,20,30] [33,44,94]
[43,64,124]
My code so far is:
Zipwith f [] [] = []
Zipwith f [] _ = []
Zipwith f _ [] = []
Zipwith f (x:xs) (y:ys) = (f x y) : (Zipwith f xs ys)
However, the compiler tells me that I have multiple functions, all Zipwith
, that don't have a data definition, but I thought having one wasn't necessary in Haskell.
Also, then it says that I have multiple declarations of f, but it is just an argument, I thought it wouldn't matter that there are multiple definitions of an argument.
Any thoughts?
Haskell functions must start with a lower case. Upper case names are reserved for other stuff, like data types. In this case it would be a good idea to name your function zipWith'
, because '
is often used to indicate that the function is almost the same, but with a small change.
P.S.
Small critique of your code: You can remove the line zipwith f [] [] = []
because the other lines catch this case already. If you want you can even write it like this:
zipwith f (x:xs) (y:ys) = f x y : zipwith f xs ys
zipwith _ _ _ = []
Since the first one is the only pattern you care about.
Function names must start with a lowercase letter (or symbol). Upper-case letters are reserved for new data types. Your definition would be perfectly correct if it were named zipWith
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With