Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Write Zipwith in Haskell

Tags:

haskell

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?

like image 822
R. Monks Avatar asked Nov 27 '22 20:11

R. Monks


2 Answers

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.

like image 150
J Atkin Avatar answered Dec 10 '22 11:12

J Atkin


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.

like image 40
amalloy Avatar answered Dec 10 '22 11:12

amalloy