Skip to content

Deriving of unboxed vector for newtypes #315

@Shimuuar

Description

@Shimuuar

Problem is very simple. Newtype deriving doesn't work since roles were introduced to GHC.

{-# LANGUAGE DerivingStrategies         #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# LANGUAGE MultiParamTypeClasses      #-}
{-# LANGUAGE StandaloneDeriving         #-}
{-# LANGUAGE TypeFamilies               #-}
import qualified Data.Vector.Unboxed         as U
import qualified Data.Vector.Unboxed.Mutable as MU
import qualified Data.Vector.Generic         as G
import qualified Data.Vector.Generic.Mutable as GM
newtype X = X Int

newtype instance U.Vector     X = V_X (U.Vector Int)
newtype instance MU.MVector s X = M_X (MU.MVector s Int)

deriving newtype instance G.Vector   U.Vector   X
deriving newtype instance GM.MVector MU.MVector X 

So this simple program fails with:

    • Couldn't match representation of type ‘m1 (MU.MVector
                                                   (PrimState m1) Int)’
                               with that of ‘m1 (MU.MVector
                                                   (PrimState m1) X)’
        arising from a use of ‘GHC.Prim.coerce’
    ...

Reason for that are very obvious. Methods of type class has type ∀m. PrimMonad m => ... -> m a and GHC can't coerce m Int to m X because it can't assume that Int has representational/phantom role.

This problem could be fixed by changing ∀m. PrimMonad ⇒ m type parameter to ∀s. ST s. Since m only appears in positive positions both approaches are equivalent and every instance that could be written in one style could be written in another.

This is of course breaking change but breakage should be relatively limited. Type class methods are not meant to be used directly and custom instances should continue to compile

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions