Woj*_*ilo 16 haskell types type-inference ghc type-families
在GHC-7.7(和7.8)中,介绍了封闭式家庭:
封闭类型族在一个地方定义了所有方程,不能扩展,而开放族可以在模块之间分布实例.封闭族的优点是按顺序尝试其方程,类似于术语级函数定义
我想问你,为什么下面的代码不能编译?GHC应该能够推断所有类型 - GetTheType仅针对类型定义X,如果我们注释掉标记的行,则代码编译.
这是GHC中的一个错误或封闭类型的家庭没有这样的优化吗?
码:
{-# LANGUAGE TypeFamilies #-}
data X = X
type family GetTheType a where
GetTheType X = X
class TC a where
tc :: GetTheType a -> Int
instance TC X where
tc X = 5
main = do
-- if we comment out the following line, the code compiles
let x = tc X
print "hello"
Run Code Online (Sandbox Code Playgroud)
错误是:
Couldn't match expected type ?GetTheType a0’ with actual type ?X’
The type variable ?a0’ is ambiguous
In the first argument of ?tc’, namely ?X’
In the expression: tc X
Run Code Online (Sandbox Code Playgroud)
mga*_*kay 11
封闭式家庭没有任何问题.问题是类型函数不是单射的.
说,你可以有这个封闭类型的功能:
data X = X
data Y = Y
type family GetTheType a where
GetTheType X = X
GetTheType Y = X
Run Code Online (Sandbox Code Playgroud)
您无法从结果类型推断出参数类型X.
数据系列是单射的,但不是封闭的:
{-# LANGUAGE TypeFamilies #-}
data X = X
data family GetTheType a
data instance GetTheType X = RX
class TC a where
tc :: (GetTheType a) -> Int
instance TC X where
tc RX = 5
main = do
let x = tc RX
print "hello"
Run Code Online (Sandbox Code Playgroud)