【发布时间】:2015-01-31 11:42:23
【问题描述】:
我刚刚开始学习类型族。 GHC 文档指出顶级和关联类型系列具有相同的功能,但我正在编写的代码在顶级中的行为与关联系列时的行为不同。这编译并运行良好:
{-# LANGUAGE TypeFamilies #-}
module Test where
-- type family R a
-- type instance R Maybe = Int
class C' a where
type R a
getInt' :: a Int
getBool' :: R a -> a Bool
instance C' Maybe where
type R Maybe = Int
getInt' = Just 3
getBool' i = Just $ i < 10
printer :: IO ()
printer = print $ (getBool' 5 :: Maybe Bool)
但这给了我一个类型错误:
{-# LANGUAGE TypeFamilies #-}
module Test where
type family R a
type instance R Maybe = Int
class C' a where
-- type R a
getInt' :: a Int
getBool' :: R a -> a Bool
instance C' Maybe where
-- type R Maybe = Int
getInt' = Just 3
getBool' i = Just $ i < 10
printer :: IO ()
printer = print $ (getBool' 5 :: Maybe Bool)
这些和我一模一样;为什么一个编译另一个不编译?
【问题讨论】:
-
关联类型族的不同之处仅在于编译器期望每个类实例中有 1 个或多个类型实例。当文档说“相同的功能”时,这意味着相同声明的语义相同,但您仍然必须将声明放在正确的位置。 “关联”类型族的目的是提醒实现者他们必须定义该类型实例。