通过派生与独立派生

时间:2018-11-20 23:21:44

标签: haskell deriving

我不太确定自己在做什么错:

data Vector2D u = Vector2D { 
    _x :: u, 
    _y :: u 
} deriving stock (Show, Eq, Functor, Foldable, Traversable)

{-# INLINE addVector2 #-}
addVector2 :: (Additive a) => Vector2D a -> Vector2D a -> Vector2D a 
addVector2 (Vector2D { _x = x1, _y = y1 }) (Vector2D { _x = x2, _y = y2 }) = 
    Vector2D { _x = x1 + x2, _y = y1 + y2 }

instance (Additive a) => Additive (Vector2D a) where
    (+) = addVector2

newtype Square a = Square {
    unpackSquare :: Vector2D a
} deriving stock (Show, Eq)

到目前为止,如此正常(在代数包中定义了加法,但很明显)。

但是,现在我想更聪明地使用DerivingVia和StandaloneDeriving,我什至无法得到下一行来编译

deriving instance (Additive a) => Additive (Square a) via (Vector2D a)

但是那让我

    * Expected kind `k0 -> * -> Constraint',
        but `Additive (Square a)' has kind `Constraint'
    * In the stand-alone deriving instance for
        `(Additive a) => Additive (Square a) via (Vector2D a)'

谁能告诉我我在做什么错?我正在运行GHC 8.6.2

1 个答案:

答案 0 :(得分:10)

deriving via (Vector2D a) instance (Additive a) => Additive (Square a)

via的书写方式看起来像类型变量

deriving instance (Additive a) => Additive (Square a) via (Vector2D a)
-- <==>
deriving instance forall a via. (Additive a) => Additive (Square a) (via) (Vector2D a)

这会产生种类不匹配的错误,因为Additive (Square a) :: Constraint已经饱和,但是您已将其应用于另外两个参数。

这是从简写形式倒过来的:

data T' = ...
  deriving Class via T