Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/haskell/9.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Haskell 比较固定大小的向量_Haskell - Fatal编程技术网

Haskell 比较固定大小的向量

Haskell 比较固定大小的向量,haskell,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

我试图写一个固定大小的向量,如下所示:

{-# 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

ghc
无法(尚未?)从
(n+1)~(n'+1)
虽然从
sn~sn'
中推断出它并不困难,但请参见,例如,以获取解释和可能的解决方法(即,既使用Peano风格的自然语言,又能够使用
5
等文字)

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

data NVector (n :: Nat) a where
    Nil :: NVector 0 a
    Cons :: a -> NVector (n -1) a -> NVector n a
它必须从
n~n'
中推断出
n-1~n'-1
,这是一个更容易的推断!这会编译,并且仍然会生成正确的类型,例如
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声明:

Iavor Diatchki正在GHC的约束解算器中使用现成的SMT解算器。目前,这方面的主要重点是改进对类型级自然数推理的支持[…]

因此,您的示例可能适用于ghc 7.10或7.12