Reputation: 93
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?
Upvotes: 4
Views: 5876
Reputation: 3140
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.
Upvotes: 11
Reputation: 62818
To echo the other answers: Function names must start with a lowercase letter. This is not merely a coding convention; it is part of the actual language syntax. As in, it actually stops stuff compiling if you don't do this.
Other programming languages often have conventions on how you should use case, but the Haskell compiler actually uses this to decide what kind of name you're referring to. In this case, it thinks that Zipwith
is some sort of data type, which (naturally) doesn't actually exist, which is why the compiler is confused.
Upvotes: 4
Reputation: 91857
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
.
Upvotes: 11