我有这个公认的人为的代码块
{-# LANGUAGE DataKinds, TypeFamilies #-}
data Foo = Foo
type family Id (n :: Foo) a where
Id 'Foo a = a
data Bar (n :: Foo) = Bar
class Dispatch (n :: Foo) where
consume :: Id n a -> Bar n -> a
consume' :: Dispatch n => Id n [Bool] -> Bar n -> [Bool]
consume' = consume
consume'' :: Dispatch n => Id n [Bool] -> Bar n -> Bool
consume'' g x = and (consume' g x)
这可以编译并正常工作。但是,如果我将最终consume''
定义替换为
consume'' :: Dispatch n => Id n [Bool] -> Bar n -> Bool
consume'' g x = and (consume g x)
(注意consume
而不是consume'
),然后我得到一个错误
noinject.hs:17:30: error:
• Couldn't match expected type ‘Id n (t0 Bool)’
with actual type ‘Id n [Bool]’
NB: ‘Id’ is a non-injective type family
The type variable ‘t0’ is ambiguous
• In the first argument of ‘consume’, namely ‘g’
In the first argument of ‘and’, namely ‘(consume g x)’
In the expression: and (consume g x)
• Relevant bindings include
x :: Bar n (bound at noinject.hs:17:13)
g :: Id n [Bool] (bound at noinject.hs:17:11)
consume'' :: Id n [Bool] -> Bar n -> Bool
(bound at noinject.hs:17:1)
|
17 | consume'' g x = and (consume g x)
| ^
Failed, no modules loaded.
如果我们假设Id
是非内射的,那么就会发生错误,因为consume
可能专门针对,对于一些不是consume :: Id n (t0 Bool) -> Bar n -> t0 Bool
的可折叠。我明白那么多。我的问题是:为什么实际上不是单射的。它需要两个参数:第一个参数只有一个有效值,并且在第二个参数中很明显是单射的,那么为什么 GHC 认为这是一个非单射族?t0
[]
Id
Id