Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Deriving Via With Standalone Deriving

I'm not really sure what I'm doing wrong here:

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)

So far, so normal (Additive is defined in the algebra package but is pretty self-explanatory).

However, now I want to be clever using DerivingVia and StandaloneDeriving and I can't even get the next line to compile

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

But that gets me

    * 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)'

Can anyone tell me what I'm doing wrong? I'm running GHC 8.6.2

like image 491
Julian Birch Avatar asked Nov 20 '18 23:11

Julian Birch


1 Answers

It's

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

The way you wrote it, via looks like a type variable

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

and this produces a kind-mismatch error, as Additive (Square a) :: Constraint is already saturated, but you have applied it to two more arguments.

This is backwards from the shorthand form:

data T' = ...
  deriving Class via T 
like image 62
HTNW Avatar answered Nov 06 '22 09:11

HTNW