Haskell :: 如何创建任意长度的向量?

Haskell :: How do I create a Vector of arbitrary length?

想要在 Haskell 中实现类型安全的矩阵乘法。 定义如下:

{-# LANGUAGE TypeFamilies, DataKinds, GADTs  #-}
module Vector where

data Nat = Succ Nat | Zero

data Vector (n :: Nat) a where
    Nil :: Vector 'Zero a
    (:::) :: a -> Vector n a -> Vector (Succ n) a
type Matrix n m a = Vector m (Vector n a)

instance Foldable (Vector n) where
    foldr f b (a ::: as) = f a (foldr f b as)
    foldr _ b Nil = b

instance Functor (Vector n) where
    fmap f (x ::: xs) = f x ::: fmap f xs
    fmap _ Nil = Nil

zipV :: (a -> b -> c) -> Vector n a -> Vector n b -> Vector n c
zipV f (a ::: as) (b ::: bs) = f a b ::: zipV f as bs
zipV f Nil Nil = Nil

最终有实施的需要

transpose :: Matrix n m a -> Matrix m n a

但我在 Haskell 能做的最好的事情是:

transpose :: Matrix n (Succ m) a -> Matrix (Succ m) n a
transpose (h ::: rest@(_ ::: _)) = zipV (:::) h (transpose rest)
transpose (h ::: Nil) = fmap (::: Nil) h

限制为 m > 0 因为我无法实现

nils :: {n :: Nat} -> Vector n (Vector Zero a)

切换到 Idris 只是为了练习并且做得更好:

matrix : Nat -> Nat -> Type -> Type
matrix n m a = Vector n (Vector m a)

nils : {n: Nat} -> Vector n (Vector Z a)
nils {n = Z}   = Nil
nils {n = S k} = Nil ::: nils

transpose : matrix n m a -> matrix m n a
transpose (h ::: rest) = zipV (:::) h (transpose rest)
transpose Nil = nils

有想实现nils的冲动,但是Haskell类型级编程很别扭。我还必须在 Haskell 中对 rest@(_ ::: _) 进行模式匹配,但我没有在 Idris 中进行。我如何实施“nils”?

这基本上就是 singletons 的用途。这是类型类的 value-level 见证,使您可以访问此(概念上冗余的)信息,每个数字实际上都可以用标准形式描述。最小实现:

data NatSing n where
  ZeroSing :: NatSing Zero
  SuccSing :: KnownNat n => NatSing (Succ n)

class KnownNat n where
  natSing :: NatSing n
instance KnownNat Zero where natSing = ZeroSing
instance KnownNat n => KnownNat (Succ n) where natSing = SuccSing

现在可以写

{-# LANGUAGE ScopedTypeVariables, UnicodeSyntax, TypeApplications #-}
nils :: ∀ n a . KnownNat n => Vector n (Vector Zero a)
nils = case natSing @n of
  ZeroSing ->     Nil
  SuccSing -> Nil ::: nils