haskell - 为新类型重用 MArray 实例

标签 haskell typeclass newtype deriving

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

newtype MyBool = MyBool Bool
newtype MyInt  = MyInt  Int

我想重用现有实例:
instance MArray IOUArray Int IO         where ...
instance MArray (STUArray s) Int (ST s) where ...

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

我发现一些看起来非常接近我想要实现的东西:
{-# LANGUAGE GeneralizedNewtypeDeriving, StandaloneDeriving #-}

deriving instance MArray IOUArray MyInt IO      
deriving instance MArray (STUArray s) MyInt (ST s)  

但是,它失败了:
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’

如何使这项工作?

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

最佳答案

来自 the documentation :

We can even derive instances of multi-parameter classes, provided the newtype is the last class parameter.



Notice also that the order of class parameters becomes important, since we can only derive instances for the last one. If the StateMonad class above were instead defined as

class StateMonad m s | m -> s where ...

then we would not have been able to derive an instance for the Parser type above. We hypothesise that multi-parameter classes usually have one “main” parameter for which deriving new instances is most interesting.



由于您的案例中的最后一个类参数不是 Int/MyInt ,而是IO/ST s ,你不走运 GeneralizedNewtypeDeriving , 很遗憾。

关于haskell - 为新类型重用 MArray 实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59550212/

相关文章:

haskell - “Unable to load package ` 正则表达式 posix ` … unknown symbol ‘regerror’”

haskell - Haskell 应用变压器的例子

haskell - 来自同一域的函数的应用实例到 Applicative

haskell - 如何访问haskell中的新类型命名元组字段

haskell - 组合两个单子(monad)变压器堆栈时无法派生 Applicative

haskell - haskell中多个类型变量的顺序规则是什么?

haskell cabal : "package indirectly depends on multiple versions of the same package"

haskell - 在 Haskell 中,我如何获取一个 m 元谓词和一个 n 元谓词并构造一个 (m+n) 元谓词?

haskell - Haskell 中数字的解释

haskell - 使用 yesod 坚持执行 "join"的正确方法