键入系列:顶级与关联

Oma*_*man 4 haskell types

我刚刚开始学习类型系列.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)
Run Code Online (Sandbox Code Playgroud)

但这给了我一个类型错误:

{-# 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)
Run Code Online (Sandbox Code Playgroud)

这些看起来和我一模一样; 为什么一个编译而另一个没编译?

aav*_*ogt 5

如果你注释这种类型,第二个工作:

type family R (a :: * -> *)
Run Code Online (Sandbox Code Playgroud)

我认为没有任何理由为什么只为相关类型系列推断出正确的类型.

  • 对于相关类型族推断出正确的类型,因为它具有在使用类型族的函数中存在的附加类型信息,以及来自类声明的类型"a".例如,它看到`一个Int`必须是一种有效的类型`*`,你可以从中推断出`a ::* - >*`.如果类型族没有关联,编译器显然无法访问该信息,因此它为类型族提供了默认类型:`* - >*`. (3认同)