我正在学习Dafny。我完全被引理所困扰,我不知道如何使用它。该教程没有用。如果我想证明怎么办?
count(a) <= |a|
我该怎么办谢谢你的帮助。
function count(a: seq<bool>): nat
ensures count(a) <= |a|;
{
if |a| == 0 then 0 else
(if a[0] then 1 else 0) + count(a[1..])
}
答案 0 :(得分:2)
你已经证明了这一点!您编写了您想要的属性作为函数的后置条件,Dafny在没有投诉的情况下验证它。就是这样。
您还可以使用引理来证明该属性。这是一个例子:
function count(a: seq<bool>): nat
{
if |a| == 0 then 0 else
(if a[0] then 1 else 0) + count(a[1..])
}
lemma CountProperty(a: seq<bool>)
ensures count(a) <= |a|
{
}
再次,Dafny在没有发出任何投诉的情况下验证引理,所以你已经证明了这一点!
假设Dafny会自动为您证明一切是不正确的。因此,学习如何手动编写校样也是一个好主意。这是这个属性的手动证明。为了确保Dafny不会尝试自动进行归纳,我使用了一个指令将其关闭(从而使我们的生活比Dafny通常更难):
lemma {:induction false} CountProperty(a: seq<bool>)
ensures count(a) <= |a|
{
// Let's consider two cases, just like the definition of "count"
// considers two cases.
if |a| == 0 {
// In this case, we have:
assert count(a) == 0 && |a| == 0;
// so the postcondition follows easily.
} else {
// By the definition of "count", we have:
assert count(a) == (if a[0] then 1 else 0) + count(a[1..]);
// We know an upper bound on the first term of the addition:
assert (if a[0] then 1 else 0) <= 1;
// We can also obtain an upper bound on the second term by
// calling the lemma recursively. We do that here:
CountProperty(a[1..]);
// The call we just did gives us the following property:
assert count(a[1..]) <= |a[1..]|;
// Putting these two upper bounds together, we have:
assert count(a) <= 1 + |a[1..]|;
// We're almost done. We just need to relate |a[1..]| to |a|.
// This is easy:
assert |a[1..]| == |a| - 1;
// By the last two assertions, we now have:
assert count(a) <= 1 + |a| - 1;
// which is the postcondition we have to prove.
}
}
编写这样的证明的一种更好的方法是使用经验证的计算,Dafny称之为“calc语句”:
lemma {:induction false} CountProperty(a: seq<bool>)
ensures count(a) <= |a|
{
if |a| == 0 {
// trivial
} else {
calc {
count(a);
== // def. count
(if a[0] then 1 else 0) + count(a[1..]);
<= // left term is bounded by 1
1 + count(a[1..]);
<= { CountProperty(a[1..]); } // induction hypothesis gives a bound for the right term
1 + |a[1..]|;
== { assert |a[1..]| == |a| - 1; }
|a|;
}
}
}
我希望这能让你开始。
安全编程,
Rustan