用一个简单的归纳定义A
类型:
Inductive A: Set := mkA : nat-> A.
(*get ID of A*)
Function getId (a: A) : nat := match a with mkA n => n end.
以及子类型定义:
(* filter that test ID of *A* is 0 *)
Function filter (a: A) : bool := if (beq_nat (getId a) 0) then true else false.
(* cast bool to Prop *)
Definition IstrueB (b : bool) : Prop := if b then True else False.
(* subtype of *A* that only interests those who pass the filter *)
Definition subsetA : Set := {a : A | IstrueB (filter a) }.
我尝试使用此代码将A
元素转换为filter
通过时subsetA
,但未能方便 Coq 它是"sig"类型元素的有效构造:
Definition cast (a: A) : option subsetA :=
match (filter a) with
| true => Some (exist _ a (IstrueB (filter a)))
| false => None
end.
错误:
In environment
a : A
The term "IstrueB (filter a)" has type "Prop"
while it is expected to have type "?P a"
(unable to find a well-typed instantiation for "?P": cannot ensure that
"A -> Type" is a subtype of "?X114@{__:=a} -> Prop").
因此,Coq期望获得(IstrueB (filter a))
型的实际证明,但我在那里提供的是Prop
型。
您能谈谈如何提供这种类型吗?谢谢。
首先,有标准的is_true
包装器。您可以像这样显式使用它:
Definition subsetA : Set := {a : A | is_true (filter a) }.
或隐式使用强制机制:
Coercion is_true : bool >-> Sortclass.
Definition subsetA : Set := { a : A | filter a }.
接下来,filter a
上的非依赖模式数学不会filter a = true
传播到true
分支中。您至少有三个选项:
使用策略来构建您的
cast
函数:Definition cast (a: A) : option subsetA. destruct (filter a) eqn:prf. - exact (Some (exist _ a prf)). - exact None. Defined.
显式使用依赖模式匹配(在 Stackoverflow 或 CDPT 中搜索"护航模式"(:
Definition cast' (a: A) : option subsetA := match (filter a) as fa return (filter a = fa -> option subsetA) with | true => fun prf => Some (exist _ a prf) | false => fun _ => None end eq_refl.
使用
Program
设施:Require Import Coq.Program.Program. Program Definition cast'' (a: A) : option subsetA := match filter a with | true => Some (exist _ a _) | false => None end.