比较固定大小的矢量

时间:2015-01-22 22:52:40

标签: haskell

我正在尝试像这样写一个固定大小的矢量:

{-# LANGUAGE GADTs, DataKinds, KindSignatures, TypeOperators #-}
import GHC.TypeLits

data NVector (n :: Nat) a where
    Nil :: NVector 0 a
    Cons :: a -> NVector n a -> NVector (n + 1) a

instance Eq a => Eq (NVector n a) where
    Nil == Nil = True
    (Cons x xs) == (Cons y ys) = x == y && xs == ys

但无法使用此消息进行编译:

 Could not deduce (n2 ~ n1)
from the context (Eq a)
  bound by the instance declaration at prog.hs:8:10-33
or from (n ~ (n1 + 1))
  bound by a pattern with constructor
             Cons :: forall a (n :: Nat). a -> NVector n a -> NVector (n + 1) a,
           in an equation for `=='
  at prog.hs:10:6-14
or from (n ~ (n2 + 1))
  bound by a pattern with constructor
             Cons :: forall a (n :: Nat). a -> NVector n a -> NVector (n + 1) a,
           in an equation for `=='
  at prog.hs:10:21-29

但如果我手动引入类型级自然,它会成功编译

{-# LANGUAGE GADTs, DataKinds, KindSignatures, TypeOperators, TypeFamilies #-}
data Nat = Z | S Nat

infixl 6 :+

type family   (n :: Nat) :+ (m :: Nat) :: Nat
type instance Z     :+ m = m
type instance (S n) :+ m = S (n :+ m) 

data NVector (n :: Nat) a where
    Nil :: NVector Z a
    Cons :: a -> NVector n a -> NVector (S n) a

instance (Eq a) => Eq (NVector n a) where
    Nil == Nil = True
    (Cons x xs) == (Cons y ys) = x == y && xs == ys

ghc版本7.8.3

1 个答案:

答案 0 :(得分:7)

ghc无法(尚未?)从n ~ n'推断出类型相等(n+1) ~ (n'+1)S n ~ S n'中推断它是没有问题的。 Append for type-level numbered lists with TypeLits有一个解释和一个可能的出路(即同时拥有Peano风格的自然,仍然可以使用像5这样的文字)

但是,如果您将Nvector的定义更改为

data NVector (n :: Nat) a where
    Nil :: NVector 0 a
    Cons :: a -> NVector (n -1) a -> NVector n a

它必须从n-1 ~ n'-1中推断n ~ n',这是一个更容易的推论!这编译,并仍然产生一个正确的类型,例如, Cons () Nil

*Main> :t Cons () Nil
Cons () Nil :: NVector 1 ()

请注意,这是无用的,因为我们仍然无法定义

append :: NVector n a -> NVector m a -> NVector (n + m) a -- won't work

2014年10月ghc {{1}}说:

  

Iavor Diatchki正致力于在GHC的约束求解器中使用现成的SMT求解器。目前,主要关注点是使用类型级自然数[...]

改进对推理的支持

所以你的例子可能适用于ghc 7.10或7.12!