如果我从GHCi终端执行myZipWith (+) (Point [1,2,3]) (Point [4,5,6])
,一切正常,但是如果我尝试从一个简单的函数执行它,就会给我错误。
为什么即使代码相同,直接从终端执行的内容也不同?
这是我的代码:
data Point p = Point [p]
deriving (Show)
wtf :: [p]
wtf = myZipWith (+) (Point [1,2,3]) (Point [4,5,6])
myZip :: Point p -> Point p -> [(p, p)]
myZip (Point []) _ = []
myZip _ (Point []) = []
myZip (Point (a:as)) (Point (b:bs)) = (a, b) : myZip (Point as) (Point bs)
myZipWith :: (p -> p -> p) -> Point p -> Point p -> [p]
myZipWith f (Point p1) (Point p2) = [ f (fst x) (snd x) | x <- (myZip (Point p1) (Point p2)) ]
错误代码:
No instance for (Num p) arising from a use of `+'
Possible fix:
add (Num p) to the context of
the type signature for:
wtf :: forall p. [p]
* In the first argument of `myZipWith', namely `(+)'
In the expression:
myZipWith (+) (Point [1, 2, 3]) (Point [4, 5, 6])
In an equation for `wtf':
wtf = myZipWith (+) (Point [1, 2, 3]) (Point [4, 5, 6])
答案 0 :(得分:3)
您已定义wtf
适用于任何类型的p
,而不仅仅是具有Num
实例的类型。您需要在类型注释中包含约束。
wtf :: Num p => [p]
wtf = myZipWith (+) (Point [1,2,3]) (Point [4,5,6])
这是建议的可能解决方法所暗示的解决方案(即“将类型Num p
添加到类型签名的上下文中”)。 myZip
和myZipWith
不需要注释,因为它们与Num
无关。仅使用wtf
的{{1}}的定义需要附加约束。
如果您放弃类型注释,只写了(+) :: Num a => a -> a -> a
,那么Haskell就会为列表推断类型wtf = myZipWith (+) (Point [1,2,3]) (Point [4,5,6])
。您明确的,过于笼统的类型阻止了推理的发生。