我有一个类型类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
我可以通过启用FlexibleContexts
和UndecidableInstances
并编写手动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
比一个值的简单包装更复杂,或者我还想要派生其他类型类的实例时。有出路吗?
答案 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)