没有因使用“+”而产生的 (Num p) 实例

No instance for (Num p) arising from a use of `+'

如果我从 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])

您已将 wtf 定义为适用于 任何 类型 p,而不仅仅是具有 Num 实例的类型。您需要在类型注释中包含约束。

wtf :: Num p => [p]
wtf = myZipWith (+) (Point [1,2,3]) (Point [4,5,6])

这是建议的可能修复方法所暗示的解决方案(即 "add[ing] Num p to the context of the type signature")。 myZipmyZipWith 不需要注解,因为它们没有 Num 特有的东西。只有使用 (+) :: Num a => a -> a -> awtf 的定义需要额外的约束。

如果您不使用类型注释,而只是写 wtf = myZipWith (+) (Point [1,2,3]) (Point [4,5,6]),那么 Haskell 会推断出列表的类型 Num a => [a]。您明确的、过于笼统的类型阻止了推理的发生。