为 newtype 重用 MArray 实例

osh*_*hko 9 haskell typeclass deriving newtype

我有十几种这样的新类型:

newtype MyBool = MyBool Bool
newtype MyInt  = MyInt  Int
Run Code Online (Sandbox Code Playgroud)

我想重用现有实例:

instance MArray IOUArray Int IO         where ...
instance MArray (STUArray s) Int (ST s) where ...
Run Code Online (Sandbox Code Playgroud)

实现这些实例并拥有所有样板代码是我最不想要的。

我发现了一些看起来非常接近我想要实现的目标:

{-# LANGUAGE GeneralizedNewtypeDeriving, StandaloneDeriving #-}

deriving instance MArray IOUArray MyInt IO      
deriving instance MArray (STUArray s) MyInt (ST s)  
Run Code Online (Sandbox Code Playgroud)

但是,它失败了:

Can't make a derived instance of ‘MArray IOUArray MyInt IO’
    (even with cunning GeneralizedNewtypeDeriving):
    cannot eta-reduce the representation type enough
In the stand-alone deriving instance for ‘MArray IOUArray MyInt IO’
Run Code Online (Sandbox Code Playgroud)

如何使这项工作?

如果不可能,获得这些实例的最不痛苦的方法是什么?

Jos*_*ica 3

文档中:

\n\n
\n

我们甚至可以派生多参数类的实例,只要 newtype 是最后一个类参数。

\n
\n\n\n\n
\n

还要注意,类参数的顺序变得很重要,因为我们只能派生最后一个参数的实例。如果StateMonad上面的类被定义为

\n\n
class StateMonad m s | m -> s where ...\n
Run Code Online (Sandbox Code Playgroud)\n\n

那么我们就无法导出一个实例Parser上述类型的实例。我们假设多参数类通常有一个 \xe2\x80\x9cmain\xe2\x80\x9d 参数,对于该参数派生新实例是最有趣的。

\n
\n\n

由于您的情况中的最后一个类参数不是 / IntMyInt而是IO/ ST s,所以不幸的是GeneralizedNewtypeDeriving,您运气不好。

\n