【发布时间】:2012-10-20 03:09:42
【问题描述】:
我有一个类型类 Foo 与关联类型:
{-# LANGUAGE TypeFamilies #-}
class Foo a where
type Bar a
foo :: a -> Bar a
现在我想定义一个数据类型来保存其中一种关联类型,并为其派生一个Show 实例:
data Baz a = Baz (Bar a) deriving (Show)
不过,这并不能编译,因为您不能保证 Bar a 有一个 Show 实例
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 比一个值的简单包装器更复杂时,或者当我还想派生其他类型类的实例时。有出路吗?
【问题讨论】:
标签: haskell types type-families