Haskell中的封闭类型族和类型推断

问题描述 投票:16回答:1

在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"

错误是:

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
haskell types ghc type-inference type-families
1个回答
11
投票

封闭型家庭没有错。问题在于,并非所有类型的函数都是内射的。

说,您可以具有此封闭类型的功能:

data X = X
data Y = Y

type family GetTheType a where
    GetTheType X = X
    GetTheType Y = X

您无法从结果类型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"
© www.soinside.com 2019 - 2024. All rights reserved.