类型族:顶级与关联

Type families: top level vs. associated

我刚开始学习类型家庭。 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)

这些看起来和我一模一样;为什么一个能编译,一个不能编译?

如果您注释种类,则第二个有效:

type family R (a :: * -> *)

我认为没有任何理由只能为关联的类型系列推断出正确的种类。