dafny - 如何证明一段时间总是在 Dafny 中返回一个值?
问题描述
我正在使用:|
运算符并将其转换为 while,但现在我不知道如何证明循环将始终返回有效的x
. 我有以下代码:
method test(a : array<int>) returns (z : int)
requires exists x. 0 <= x < a.Length && P(a[x]);
ensures P(a[x]);
{
var x :| 0 <= x < a.Length && P(a[x]);
return x;
}
我将其更改为:
method test(a : array<int>) returns (z : int)
requires exists x. 0 <= x < a.Length && P(a[x]);
ensures P(a[x]);
{
var x := 0;
while (x < a.Length) {
if (P(a[x])) {
return x;
}
x := x + 1;
}
}
我该怎么证明?我在rise4fun 上做了一个PoC:https ://rise4fun.com/Dafny/LpRZA 。
非常感谢!
解决方案
似乎在循环中添加一个不变量就足够了:
method test(a : array<int>) returns (z : int)
requires exists x. 0 <= x < a.Length && P(a[x]);
ensures P(a[x]);
{
var x := 0;
while (x < a.Length)
invariant exists x' :: x <= x' < a.Length && P(a[x']);
{
if (P(a[x])) {
return x;
}
x := x + 1;
}
assert false; // be sure that it does not reach here
}
推荐阅读
- android - 以编程方式重新启动蓝牙
- python - 从字符串中提取单词,知道单词中一个字符的索引(python)
- haskell - 如何为 sum 类型编写镜头
- javascript - 使用 Ajax 在 Django 中发送表单数据
- robotframework - 如何在 Robot 框架中访问全局变量
- google-cloud-platform - NestedValueProvider 问题
- python-3.x - pandas - 基于交易数量和日期的日期总持有量
- php - Podio API:之前引用的项目有时会在引用列表中丢失
- php - 在 PHP 中使用调用自定义 powershell API 的正确方法
- java - 创建一个字段类型的可观察列表