gpt4 book ai didi

haskell - 为新类型重用 MArray 实例

转载 作者:行者123 更新时间:2023-12-04 12:26:20 25 4
gpt4 key购买 nike

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

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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com