(Dafny) Adding array elements to another - cyclic invariant

I have a function sum

that takes two arrays a

and b

both inputs and changes b

so that b[i] = a[0] + a[1] + ... + a[i]

. I wrote this function and want to test it with Daphne. However, Daphne tells me that my loop invariant may not be supported by the loop. Here is the code:

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;
    }
}

      

How can I fix this error?

+3


source to share


1 answer


Your program will be wrong if a

both b

refer to the same array. You need a precondition a != b

. (If you add it, Dafny will check your program.)



Rustan

+3


source







All Articles