用Haskell写Zipwith [英] Write Zipwith in Haskell
问题描述
我正在尝试在Haskell中编写 Zipwith
函数.
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)
但是,编译器告诉我,我有多个函数,所有 Zipwith
,都没有数据定义,但是我认为在Haskell中并不需要一个.而且,然后它说我有f的多个声明,但这只是一个参数,我认为参数的多个定义无关紧要.
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.
有什么想法吗?
推荐答案
Haskell函数 必须 以小写字母开头.大写名称保留给其他内容,例如数据类型.在这种情况下,最好将函数命名为 zipWith'
,因为'
通常用于表示该函数几乎相同,但是变化很小
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.
对代码的小批判:您可以删除行 zipwith f [] [] = []
,因为其他行已经捕获了这种情况.如果您愿意,甚至可以这样写:
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.
这篇关于用Haskell写Zipwith的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!