使用TypeFamilies派生实例

时间:2012-10-30 17:44:07

标签: haskell types type-families

我有一个类型类Foo,其关联类型为:

{-# LANGUAGE TypeFamilies #-}

class Foo a where
    type Bar a
    foo :: a -> Bar a

现在我想定义一个包含其中一个关联类型的数据类型,并为它派生一个Show实例:

data Baz a = Baz (Bar a) deriving (Show)

但这不会编译,因为您无法保证Show

Bar a个实例
No instance for (Show (Bar a))
  arising from the 'deriving' clause of a data type declaration

我可以通过启用FlexibleContextsUndecidableInstances并编写手动Show实例来解决问题,如下所示

{-# LANGUAGE FlexibleContexts, UndecidableInstances #-}

data Baz a = Bar a

instance (Show a, Show (Bar a)) => Show (Baz a) where
    showsPrec _ (Baz x) = showString "Baz " . shows x

但这并不是特别令人满意,特别是当Baz比一个值的简单包装更复杂,或者我还想要派生其他类型类的实例时。有出路吗?

1 个答案:

答案 0 :(得分:15)

您可以使用StandaloneDeriving要求GHC生成与以前相同的Show实例,但具有不同的上下文:

{-# LANGUAGE FlexibleContexts, StandaloneDeriving, TypeFamilies, UndecidableInstances #-}

class Foo a where
    type Bar a
    foo :: a -> Bar a

data Baz a = Baz (Bar a)
deriving instance Show (Bar a) => Show (Baz a)