相互引用的默认类型实例

时间:2012-08-30 14:34:10

标签: haskell typeclass type-families

有没有办法让默认类型实例相互定义?我想尝试这样的工作:

{-# LANGUAGE DataKinds, KindSignatures #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE UndecidableInstances #-}
data Tag = A | B | C

class Foo (a :: *) where
    type Bar a (b :: Tag)

    type Bar a A = ()
    type Bar a B = Bar a A
    type Bar a C = Bar a A

instance Foo Int where
    type Bar Int A = Bool

test :: Bar Int B
test = True

但这不起作用:

Couldn't match type `Bar Int 'B' with `Bool'
In the expression: True
In an equation for `test': test = True

请注意,这也不起作用:

test :: Bar Int B
test = ()

1 个答案:

答案 0 :(得分:3)

是的,默认类型实例可以相互定义(从您自己的示例中可以看出):

instance Foo Int where
--    So the default recursive definition will be used instead
--    type Bar Int A = Bool

test :: Bar Int B
test = ()

但是,当您在Int的实例定义中重新定义关联类型同义词时,替换整个默认的3行Bar定义(而不仅仅是type Bar a A = () })一行type Bar Int A = Bool,表示不再定义Bar Int BBar Int C

所以我认为使用递归默认值的方法之一就是重新定义特定的同义词(尽管它相当冗长):

class Foo (a :: *) where
    type Bar a (b :: Tag)
    type Bar a A = BarA a
    type Bar a B = BarB a

    type BarA a
    type BarA a = ()

    type BarB a
    type BarB a = Bar a A

-- This now works
instance Foo Int where
    type BarA Int = Bool

test :: Bar Int B
test = True

哪些可以回归默认值:

-- As well as this one
instance Foo Int where
--    type BarA Int = Bool

test :: Bar Int B
test = ()