我在Coq玩,试图创建一个排序列表。
我只是想要一个带有列表[1,2,3,2,4]
的函数,并返回类似Sorted [1,2,3,4]
的函数 - 即取出坏部分,但实际上并没有对整个列表进行排序。
我想我会先定义lesseq
类型的函数(m n : nat) -> option (m <= n)
,然后我可以非常轻松地模拟匹配。也许这是一个坏主意。
我现在遇到的问题的关键是(片段,底部的整个功能)
Fixpoint lesseq (m n : nat) : option (m <= n) :=
match m with
| 0 => match n with
| 0 => Some (le_n 0)
...
不是类型检查;它说它期待option (m <= n)
,但Some (le_n 0)
的类型为option (0 <= 0)
。我不明白,因为在这种情况下显然m
和n
都是零,但我不知道如何告诉Coq。
整个功能是:
Fixpoint lesseq (m n : nat) : option (m <= n) :=
match m with
| 0 => match n with
| 0 => Some (le_n 0)
| S n_ => None
end
| S m_ => match n with
| 0 => None
| S _ => match lesseq m_ n with
| Some x=> le_S m n x
| None => None
end
end
end.
也许我已经领先于自己,只需要在解决之前继续阅读。
答案 0 :(得分:7)
你可能想要定义以下函数(即使你正确地注释它[le_S m n x]没有你想要的类型):
Fixpoint lesseq (m n : nat) : option (m <= n) :=
match n with
| 0 =>
match m with
| 0 => Some (le_n 0)
| S m0 => None
end
| S p =>
match lesseq m p with
| Some l => Some (le_S m p l)
| None => None
end
end.
但正如你所注意到的那样,类型检查员并不聪明地猜测 当你破坏出现在类型中的变量时的新上下文 结果。您必须按以下方式注释匹配:
Fixpoint lesseq (m n : nat) : option (m <= n) :=
match n return (option (m <= n)) with
| 0 =>
match m return (option (m <= 0)) with
| 0 => Some (le_n 0)
| S m0 => None
end
| S p =>
match lesseq m p with
| Some l => Some (le_S m p l)
| None => None
end
end.
如果您真的想了解模式,请参阅参考手册 匹配与依赖类型一起使用。如果你不够勇敢 为此,你宁愿使用战术机制来建立你的证据 (“精炼”策略是一个很好的工具)。
Definition lesseq m n : option (m <= n).
refine (fix lesseq (m : nat) (n : nat) {struct n} := _).
destruct n.
destruct m.
apply Some; apply le_n.
apply None.
destruct (lesseq m n).
apply Some.
apply le_S.
assumption.
apply None.
Defined.
顺便说一句,我认为你的功能不会真正有用 (即使这是一个好主意),因为你需要证明 以下引理: 引理lesseq_complete: forall m n,lesseq m n&lt;&gt;无 - &gt; m> ñ。
这就是人们使用Coq.Arith.Compare_dec的原因。 玩得开心。
答案 1 :(得分:6)
你想把这个功能写成练习还是只是为了实现更大的目标?在后一种情况下,你应该看看标准库,它充满了可以在这里完成工作的决策函数,Coq.Arith.Compare_dec;例如,见le_gt_dec
。
另请注意,您建议的功能只会向您提供m <= n
的信息。对于模式匹配,总和类型{ ... } + { ... }
更有用,为您提供两种可能的处理方式。