Jab*_*lad 10 haskell wildcard pattern-matching
出于学习目的,我正在尝试编写自己的zipWith函数实现.但是,我遇到了边缘情况下的模式匹配问题_.首先,我将描述好的情况,然后是坏的情况.希望有人能够解释他们为什么表现不同.谢谢
如果我zipWith按如下方式编写函数,它就可以工作(注意第2行和第3行匹配空列表的边缘情况的顺序): -
zipWith' :: (a -> b -> c) -> [a] -> [b] -> [c]
zipwith' _ [] _ = []
zipWith' _ _ [] = []
zipWith' f (x:xs) (y:ys) = f x y : zipWith' f xs ys
Run Code Online (Sandbox Code Playgroud)
编制GHCI: -
ghci> :l ZipWith.hs
[1 of 1] Compiling Main ( ZipWith.hs, interpreted )
Run Code Online (Sandbox Code Playgroud)
好的,上面的情况很好,但是如果我为GHCI周围的边缘情况交换模式匹配会引发第2行和第4行的"多次声明错误".
zipWith' :: (a -> b -> c) -> [a] -> [b] -> [c]
zipWith' _ _ [] = []
zipwith' _ [] _ = []
zipWith' f (x:xs) (y:ys) = f x y : zipWith' f xs ys
Run Code Online (Sandbox Code Playgroud)
编制GHCI: -
ZipWith.hs:4:0:
Multiple declarations of `Main.zipWith''
Declared at: ZipWith.hs:2:0
ZipWith.hs:4:0
Failed, modules loaded: none.
Run Code Online (Sandbox Code Playgroud)
我很难过......
sep*_*p2k 17
错误消息不是抱怨重叠模式(您的模式在两个空列表的情况下重叠,但这不是问题,也不是问题),而是zipWith函数的多个定义.
原因在于,在第二种情况下,您有一个定义zipWith后跟一个不相关的定义zipwith(注意小写w),然后是一个新的,相互冲突的定义zipWith.换句话说,这是一个简单的错字.(我花了一段时间才看到 - 相当鬼鬼祟祟的错字)