简体   繁体   English

如何使用依赖类型在 Coq 中构建仅包含真实元素的列表?

[英]How does one build the list of only true elements in Coq using dependent types?

I was going through the Coq book from the maths perspective .从数学的角度看Coq 的书。 I was trying to define a dependently typed function that returned a length list with n trues depending on the number trues we want.我试图定义一个依赖类型的 function,它返回一个长度列表,其中包含 n 个 true,具体取决于我们想要的 true 数。 Coq complains that things don't have the right type but when I see it if it were to unfold my definitions when doing the type comparison it should have worked but it doesn't. Coq 抱怨说事情没有正确的类型,但是当我看到它时,如果它在进行类型比较时展开我的定义,它应该可以工作,但没有。 Why?为什么?

Code:代码:

Module playing_with_types2.
  Inductive Vector {A: Type} : nat -> Type :=
  | vnil: Vector 0
  | vcons: forall n : nat, A -> Vector n -> Vector (S n).

  Definition t {A: Type} (n : nat) : Type :=
    match n with
    | 0 => @Vector A 0
    | S n' => @Vector A (S n')
    end.
  Check t. (* nat -> Type *)
  Check @t. (* Type -> nat -> Type *)

  (* meant to mimic Definition g : forall n: nat, t n. *)
  Fixpoint g (n : nat) : t n :=
    match n with
    | 0 => vnil
    | S n' => vcons n' true (g n')
    end.
End playing_with_types2.

Coq's error: Coq 的错误:

In environment
g : forall n : nat, t n
n : nat
The term "vnil" has type "Vector 0" while it is expected to have type
 "t ?n@{n1:=0}".
Not in proof mode.

ie t?n@{n1:=0} is Vector 0 ...no?t?n@{n1:=0}Vector 0 ...不是吗?

In this case, it looks like Coq does not manage to infer the return type of the match expression, so the best thing to do is to give it explicitly:在这种情况下,Coq 似乎无法推断出match表达式的返回类型,所以最好的办法是显式地给出它:

Fixpoint g (n : nat) : t n :=
  match n return t n with
  | 0 => vnil
  | S n' => vcons n' true (g n')
  end.

Note the added return clause.请注意添加的return子句。

Then the real error message appears:然后出现真正的错误信息:

In environment
g : forall n : nat, t n
n : nat
n' : nat
The term "g n'" has type "t n'" while it is expected to have type "Vector n'".

And this time it is true that in general t n' is not the same as Vector n' because t n' is stuck (it does not know yet whether n' is 0 or some S n'' ).而这一次,一般来说t n'确实与Vector n'不同,因为t n'被卡住了(它还不知道n'0还是某个S n'' )。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM