Dafny,post 条件在循环后不成立

Dafny, post condition does not hold after loop

在以下方法中,Dafny 报告后置条件可能不成立,尽管我很确定它成立。

method toArrayConvert(s:seq<int>) returns (a:array<int>)
    requires |s| > 0
    ensures |s| == a.Length
    ensures forall i :: 0 <= i < a.Length ==> s[i] == a[i]  // This is the postcondition that might not hold.
{
    a := new int[|s|];
    var i:int := 0;
    while i < |s|
        decreases |s| - i
        invariant 0 <= i <= |s|
    {
        a[i] := s[i];
        i := i + 1;
    }

    return a;  // A postcondition might not hold on this return path.
}

确实,后置条件总是成立,但 Dafny 说不出来!

那是因为你缺少循环不变注释,例如

invariant forall j :: 0 <= j < i ==> s[j] == a[j]

将该行添加到循环后,该方法进行验证。

有关为什么 Dafny 有时会报告正确程序错误的更多解释,请参阅(全新)FAQ. For more about loop invariants, see the corresponding section in the rise4fun guide