(Dafny)将数组的元素添加到另一个 - 循环不变

时间:2017-05-27 13:07:56

标签: arrays loop-invariant dafny

我有一个函数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;
    }
}

如何解决此错误?

1 个答案:

答案 0 :(得分:4)

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

Rustan