如何使用依赖类型在 Coq 中构建仅包含真实元素的列表?
我正在从数学角度阅读 Coq 书。我试图定义一个依赖类型的函数,它返回一个包含 n 个 true 的长度列表,具体取决于我们想要的 true 数量。 Coq 抱怨事物没有正确的类型,但是当我看到它时,如果它在进行类型比较时展开我的定义,它应该可以工作,但事实并非如此。为什么?
代码:
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 的错误:
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.
即 t ?n@{n1:=0}
是 Vector 0
...不是吗?
I was going through the Coq book from the maths perspective. I was trying to define a dependently typed function that returned a length list with n trues depending on the number trues we want.
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. 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:
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.
i.e. t ?n@{n1:=0}
is Vector 0
...no?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
在这种情况下,Coq 似乎无法推断
match
表达式的返回类型,因此最好的办法是显式给出它:注意添加的
return
条款。然后出现真正的错误消息:
这次确实是,一般来说
t n'
与Vector n'
不同,因为t n' 被卡住(它还不知道
n'
是0
还是某个S n''
)。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:Note the added
return
clause.Then the real error message appears:
And this time it is true that in general
t n'
is not the same asVector n'
becauset n'
is stuck (it does not know yet whethern'
is0
or someS n''
).