我想要做一些高级的类型级编程;这个例子是我的原始程序的简化版本。在Haskell的类型级编程中使用类型不等式
我有(Haskell)类型的表示形式。在这个例子中,我只涉及函数类型,基本类型和类型变量。
表示Type t
由一个类型变量t
参数化,以允许区分类型级别。为了达到这个目标,我主要使用GADT。不同的类型和类型变量通过使用类型级文字来区分,因此KnownSymbol
约束和使用Proxy
s。
{-# 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)
我也制约了那种t
要的那种TypeKind
使用DataKinds和KindSignatures扩展和定义TypeKind
数据类型:
data TypeKind =
Ty Symbol
| TyVar Symbol
| (:->) TypeKind TypeKind
现在我想要实现类型的换人变量,即在类型t
中,替换为类型变量y
,类型为t'
的每个变量x
。替代必须在表示上以及在类型级别上执行。对于后者,我们需要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
平等。对于这一点,我们还需要一个(聚kinded)型系列,可以让我们两个结果之间进行选择:
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 [email protected](Type _) _ _ = t
subst [email protected](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 [email protected](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?已经回答了我的问题。任何帮助,将不胜感激。
也许这个问题可以帮助你https://stackoverflow.com/questions/17749756/idiomatic-haskell-type-inequality – Carsten
我猜你需要一个引理'要么((x == Y): 〜:True)((x == y):〜:False)'。我不确定如何用GHC TypeLits来证明这一点,也不知道它是否可以在没有不安全的情况下被证明... – chi
仅供参考,当你试图做非平凡的事情时,'UndecidableInstances'通常是必需的与类型家庭。不要担心。 – dfeuer