For vs While #6209
For vs While
#6209
-
|
I am trying to prove a simple property of linear search. Below are the two implementations using for and loop. However, the while version is verified but the for version is not proved. method LinearSearch(a: array<int>, l: int, u: int, e: int) returns (b: bool)
requires 0 <= l <= u < a.Length
ensures b == (exists i: int :: l <= i <= u && a[i] == e)
{
for i := l to u
invariant l <= i <= u + 1
invariant (forall j :: l <= j < i ==> a[j] != e)
{
if (a[i] == e) {
return true;
}
}
return false;
}method LinearSearch(a: array<int>, l: int, u: int, e: int) returns (b: bool)
requires 0 <= l <= u < a.Length
ensures b == (exists i: int :: l <= i <= u && a[i] == e)
{
var i := l;
while i <= u
invariant l <= i <= u + 1
invariant (forall j :: l <= j < i ==> a[j] != e)
{
if (a[i] == e) {
return true;
}
i := i + 1;
}
return false;
} |
Beta Was this translation helpful? Give feedback.
Answered by
keyboardDrummer
May 1, 2025
Replies: 1 comment 1 reply
-
|
|
Beta Was this translation helpful? Give feedback.
1 reply
Answer selected by
KihongHeo
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
for i := l to uexcludes the end, souis excluded. In your while loop though,uis included. If you changefor i := l to utofor i := l to u + 1, it'll verify. You can find the precise meaning of the for statement in the documentation: https://dafny.org/dafny/DafnyRef/DafnyRef#g-for-statement