当我正在处理haskell-exercises问题时。Constraint
我看到以下代码通过将每种类型应用于约束构造函数来创建聚合。在 GHC 中,深度嵌套的 s 元组似乎Constraint
仍然是一种类型Constraint
(可能是扁平化的?)。
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE PolyKinds #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE TypeOperators #-}
type family All (c :: Type -> Constraint) (xs :: [Type]) :: Constraint where
All c '[] = ()
All c (x ': xs) = (c x, All c xs)
-- >>> :kind! All
-- All :: (* -> Constraint) -> [*] -> Constraint
-- = All
-- >>> :kind! All Eq '[Int, Double, Float]
-- All Eq '[Int, Double, Float] :: Constraint
-- = (Eq Int, (Eq Double, (Eq Float, () :: Constraint)))
我尝试使用PolyKinds
以下扩展名对其进行概括。
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE PolyKinds #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE TypeOperators #-}
type family All' (c :: k -> r) (xs :: [k]) :: r where
All' c '[] = ()
All' c (x ': xs) = (c x, All' c xs)
-- >>> :kind! All'
-- All' :: (k -> r) -> [k] -> r
-- = All'
--- This one works. Tuples of Types is a Type.
-- >>> :kind! All' Maybe '[Int, Double, Float]
-- All' Maybe '[Int, Double, Float] :: *
-- = (Maybe Int, (Maybe Double, (Maybe Float, ())))
--- However this one gets stuck.
-- >>> :kind! All' Eq '[Int, Double, Float]
-- All' Eq '[Int, Double, Float] :: Constraint
-- = All' Eq '[Int, Double, Float]
是种'(,) (a :: k) (b :: k)
也是种k
。往下看,似乎并非如此,所以我想知道为什么All' c (x ': xs) = (c x, All' c xs)
首先接受类型族定义(考虑到类型族返回 kind 是r
)?
λ> :kind! '(,)
'(,) :: a -> b -> (a, b)
= '(,)
λ> :kind! '(,) ('True :: Bool) ('False :: Bool)
'(,) ('True :: Bool) ('False :: Bool) :: (Bool, Bool)
= '( 'True, 'False)
更新
正如@Daniel Wagner 下面已经提到的,(,)
这里使用的被认为是Type -> Type -> Type
,并且 kind 参数在上面的第二个等式中r
被实例化( )。事实上,如果我们使用了,它会正确地返回一个类型错误。我能够使用此博客文章中描述的技术进一步确认它,如下所示(使用 kind和实例化):Type
All' c (x ': xs) = (c x, All' c xs)
'(,)
All'
k
*
λ> :set -fprint-explicit-kinds
λ> :info All'
type All' :: forall k r. (k -> r) -> [k] -> r
type family All' @k @r c xs where
forall k (c :: k -> *). All' @k @(*) c ('[] @k) = ()
forall k (c :: k -> *) (x :: k) (xs :: [k]).
All' @k @(*) c ((':) @k x xs) = (c x, All' @k @(*) c xs)