4

我有一个函数sum,它接受两个数组ab作为输入并b修改b[i] = a[0] + a[1] + ... + a[i]. 我写了这个函数,想用 Dafny 验证它。但是,Dafny 告诉我,循环可能不会维护我的循环不变量。这是代码:

function sumTo(a:array<int>, n:int) : int
  requires a != null;
  requires 0 <= n < a.Length;
  decreases n;
  reads a;
{
    if (n == 0) then a[0] else sumTo(a, n-1) + a[n]
}

method sum(a:array<int>, b:array<int>)
    requires a != null && b != null
    requires a.Length >= 1
    requires a.Length == b.Length
    modifies b
    ensures forall x | 0 <= x < b.Length :: b[x] == sumTo(a,x)
{
    b[0] := a[0];
    var i := 1;

    while i < b.Length
        invariant b[0] == sumTo(a,0)
        invariant 1 <= i <= b.Length

        //ERROR : invariant might not be maintained by the loop.
        invariant forall x | 1 <= x < i :: b[x] == sumTo(a,x)

        decreases b.Length - i
    {
        b[i] := a[i] + b[i-1];
        i := i + 1;
    }
}

我该如何解决这个错误?

4

1 回答 1

4

a如果和b引用相同的数组,您的程序将不正确。你需要前提条件a != b。(如果您添加它,Dafny 将验证您的程序。)

鲁斯坦

于 2017-05-31T20:47:58.113 回答