从属类型:向量的向量

Dependent types: Vector of vectors

我是依赖类型的新手(我正在尝试 Idris 和 Coq,尽管它们有很大的不同)。

我正在尝试表达以下类型:给定一个类型 T 和一个 k nats n1, n2, ... nk 序列,该类型由 k 个长度为 n1 的 T 序列组成, n2, ... nk 分别.

即k个向量的向量,其长度由参数给定。 这可能吗?

您可以使用异构列表执行此操作,如下所示。

Require Vector.
Require Import List.
Import ListNotations.

Inductive hlist {A : Type} (B : A -> Type) : list A -> Type :=
| hnil : hlist B []
| hcons : forall a l, B a -> hlist B l -> hlist B (a :: l).

Definition vector_of_vectors (T : Type) (l : list nat) : Type :=
  hlist (Vector.t T) l.

然后,如果 l 是您的长度列表,则类型 vector_of_vectors T l 将是您描述的类型。

比如我们可以构造一个元素vector_of_vectors bool [2; 0; 1]:

Section example.
  Definition ls : list nat := [2; 0; 1].

  Definition v : vector_of_vectors bool ls :=
    hcons [false; true]
          (hcons []
                 (hcons [true] hnil)).
End example.

此示例使用一些向量表示法,您可以像这样设置它们:

Arguments hnil {_ _}.
Arguments hcons {_ _ _ _} _ _.

Arguments Vector.nil {_}.
Arguments Vector.cons {_} _ {_} _.

Delimit Scope vector with vector.
Bind Scope vector with Vector.t.
Notation "[ ]" := (@Vector.nil _) : vector.
Notation "a :: v" := (@Vector.cons _ a _ v) : vector.
Notation " [ x ] " := (Vector.cons x Vector.nil) : vector.
Notation " [ x ; y ; .. ; z ] " :=  (Vector.cons x (Vector.cons y .. (Vector.cons z Vector.nil) ..)) : vector.

Open Scope vector.

为了完整起见,这里是 Idris 中的一个解决方案,灵感来自 James Wilcox 发布的解决方案:

module VecVec

import Data.Vect

data VecVec: {k: Nat} -> Vect k Nat -> (t: Type) -> Type where
    Nil : VecVec [] t
    (::): {k, n: Nat} -> {v: Vect k Nat} -> Vect n t -> VecVec v t -> VecVec (n :: v) t

val: VecVec [3, 2, 3] Bool
val = [[False, True, False], [False, True], [True, False, True]]

此示例将括号列表自动转换为定义它们的任何数据类型的基本构造函数 Nil::

在 Idris 中,除了创建自定义归纳类型外,我们还可以重用异构向量的标准类型 -- HVect:

import Data.HVect

VecVec : Vect k Nat -> Type -> Type
VecVec shape t = HVect $ map (flip Vect t) shape

val : VecVec [3, 2, 1] Bool
val = [[False, False, False], [False, False], [False]] -- the value is found automatically by Idris' proof-search facilities