【发布时间】:2016-05-23 10:28:57
【问题描述】:
我正在尝试做一些高级类型级编程;该示例是我原始程序的简化版本。
我有(Haskell)类型的表示。在这个例子中,我只介绍了函数类型、基本类型和类型变量。
表示Type t 由一个类型变量t 参数化,以允许在类型级别上进行区分。为此,我主要使用 GADT。不同的类型和类型变量通过使用类型级文字来区分,因此KnownSymbol 约束和Proxys 的使用。
{-# LANGUAGE GADTs, TypeOperators, DataKinds, KindSignatures, TypeFamilies, PolyKinds #-}
import GHC.TypeLits
import Data.Proxy
import Data.Type.Equality
data Type :: TypeKind -> * where
TypeFun :: Type a -> Type b -> Type (a :-> b)
Type :: KnownSymbol t => Proxy t -> Type (Ty t)
TypeVar :: KnownSymbol t => Proxy t -> Type (TyVar t)
我还通过使用 DataKinds 和 KindSignatures 扩展并定义 TypeKind 数据类型将 t 类型限制为 TypeKind 类型:
data TypeKind =
Ty Symbol
| TyVar Symbol
| (:->) TypeKind TypeKind
现在我想实现类型变量的替换,即在类型 t 中替换每个等于类型变量 y 的变量 x,类型为 t'。替换必须在表示以及类型级别上实现。对于后者,我们需要 TypeFamilies:
type family Subst (t :: TypeKind) (y :: Symbol) (t' :: TypeKind) :: TypeKind where
Subst (Ty t) y t' = Ty t
Subst (a :-> b) y t' = Subst a y t' :-> Subst b y t'
Subst (TyVar x) y t' = IfThenElse (x == y) t' (TyVar x)
类型变量是有趣的部分,因为我们在类型级别检查符号x 和y 的相等性。为此,我们还需要一个(多类型)类型族,它允许我们在两个结果之间进行选择:
type family IfThenElse (b :: Bool) (x :: k) (y :: k) :: k where
IfThenElse True x y = x
IfThenElse False x y = y
不幸的是,这还没有编译,这可能是我的问题的第一个指标:
Nested type family application
in the type family application: IfThenElse (x == y) t' ('TyVar x)
(Use UndecidableInstances to permit this)
In the equations for closed type family ‘Subst’
In the type family declaration for ‘Subst’
不过,启用 UndecidableInstances 扩展是可行的,因此我们继续定义一个在值级别上工作的函数 subst:
subst :: (KnownSymbol y) => Type t -> Proxy (y :: Symbol) -> Type t' -> Type (Subst t y t')
subst (TypeFun a b) y t = TypeFun (subst a y t) (subst b y t)
subst t@(Type _) _ _ = t
subst t@(TypeVar x) y t'
| Just Refl <- sameSymbol x y = t'
| otherwise = t
这段代码运行良好,除了最后一行产生以下编译错误:
Could not deduce (IfThenElse
(GHC.TypeLits.EqSymbol t1 y) t' ('TyVar t1)
~ 'TyVar t1)
from the context (t ~ 'TyVar t1, KnownSymbol t1)
bound by a pattern with constructor
TypeVar :: forall (t :: Symbol).
KnownSymbol t =>
Proxy t -> Type ('TyVar t),
in an equation for ‘subst’
at Type.hs:29:10-18
Expected type: Type (Subst t y t')
Actual type: Type t
Relevant bindings include
t' :: Type t' (bound at Type.hs:29:23)
y :: Proxy y (bound at Type.hs:29:21)
x :: Proxy t1 (bound at Type.hs:29:18)
subst :: Type t -> Proxy y -> Type t' -> Type (Subst t y t')
(bound at Type.hs:27:1)
In the expression: t
In an equation for ‘subst’:
subst t@(TypeVar x) y t'
| Just Refl <- sameSymbol x y = t'
| otherwise = t
我想问题是我无法证明x 和y 这两个符号的类型的不等式,并且需要某种类型不等式的见证。这可能吗?还是有其他更好的方法来实现我的目标?
我不知道'idiomatic' Haskell type inequality 和Can GADTs be used to prove type inequalities in GHC? 的问题在多大程度上已经回答了我的问题。任何帮助将不胜感激。
【问题讨论】:
-
也许这个问题可以帮到你stackoverflow.com/questions/17749756/…
-
我猜你需要一个引理
Either ((x==y) :~: True) ((x==y) :~: False)。我不确定如何使用 GHCTypeLits证明这一点,也不确定如果没有unsafe的东西是否可以证明... -
仅供参考,
UndecidableInstances通常在您尝试使用类型族做重要的事情时是必要的。别担心。
标签: haskell types gadt type-level-computation data-kinds