// In the next two classes, we consider programs with loops that // read arrays. The programs are search algorithms that find elements // or properties of the given arrays. We'll see common ways of // forming loop invariants from the postconditions the programs // are to establish. // Arrays are similar to the sequences we've already seen. The main // difference is that arrays are _mutable_, that is, we can change // the elements of an array. We won't be mutating arrays for another // couple of classes, but nevertheless start using arrays now. // The following method shows some differences between arrays and sequences. method ArrayVsSeq(a: array, b: array, s: seq, t: seq, i: nat, j: nat, x: X) returns (y: X) requires i <= j // The (fixed) size of an array `a` is given by `a.Length`, whereas the // (fixed) size of a sequence `s` is given by `|s|`. requires j < a.Length && j < |s| { // The elements of arrays and sequences are accessed in the same way. y := a[i]; y := s[i]; // A sequence is entirely characterized by its length and its elements. if |s| == |t| && forall k :: 0 <= k < |s| ==> s[k] == t[k] { assert s == t; } // But that's not true for arrays. Each array has an identity (like the // objects we'll see in a few weeks). In other words, an array is a _reference_ // to a sequence of elements. if a.Length == b.Length && forall k :: 0 <= k < a.Length ==> a[k] == b[k] { // assert a == b; // true for sequences, but not necessarily for arrays } // One can construct a sequence from a range of array elements. The general // form is `a[i..j]`, which says to take the first `j` elements of the array // and then drop the first `i` elements. If `i` is omitted, if defaults to 0, // and if `j` is omitted, it defaults to `a.Length`. Omitting both, the // expression `a[..]` is the sequence of all elements of the array. var u: seq; u := a[i..j]; u := a[0..j]; assert u == a[..j]; u := a[i..a.Length]; assert u == a[i..]; u := a[0..a.Length]; assert u == a[..]; // To obtain a new array, you must use a `new` assignment. It is a statement, so it can // only be used in method bodies, not in function bodies. The new array's elements are // initialized according to a given function from indices to elements, just like in a // sequence constructor. This initialization can be omitted if (the requested array // size is 0 or if) the element type is a so-called "auto-init" type that the compiler // knows to create values for. u := seq(100, i => x); var c: array := new X[100](i => x); var iarr: array := new int[100]; // `int` is an auto-init type, so no initializer is needed // Unlike sequences, arrays can be multidimensional. Here is an example of a 2-dimensional // array (that is, a matrix). var m: array2 := new real[20, 30]; var z := m[12, 22]; assert m.Length0 == 20 && m.Length1 == 30; } // Our first algorithm is a staple in computer science, binary search. It gets // its name from the fact that it cuts the search space in half with every iteration. // Consequencely, its running time is logarithmic in the length of the array. // In order for this to work, the given array must be sorted. datatype Option = None | Some(value: X) method BinarySearch(a: array, key: int) returns (r: Option) requires forall i, j :: 0 <= i < j < a.Length ==> a[i] <= a[j] ensures r.Some? ==> 0 <= r.value < a.Length && a[r.value] == key ensures r == None ==> key !in a[..] { // For a diagrammatic view of the invariant of binary search, see the reading & slides. var lo, hi := 0, a.Length; while lo < hi invariant 0 <= lo <= hi <= a.Length invariant key !in a[..lo] && key !in a[hi..] // Termination of the loop is proved by the termination metric `hi - lo`. // This is Dafny's default `decreases` clause for the loop, so we don't have // to write `decreases hi - lo` explicitly. Dafny comes up with a default // `decreases` clause for a loop simply by looking at the loop guard. If the // loop guard happens to be a comparison, like `lo < hi` or `lo != hi`, then // the default `decreases` clause is the absolute difference between the two // things being compared. { var m := (lo + hi) / 2; if key < a[m] { hi := m; } else if a[m] < key { lo := m + 1; } else { return Some(m); } } return None; } // Our next program is a straightforward linear scan to find the minimum // value of an array. We'll gradually build up the specification and program. method Min0(a: array) returns (m: int) // Our first specification just says that the out-parameter `m` should be // no greater than any array element. ensures forall i :: 0 <= i < a.Length ==> m <= a[i] { // We have to initialize `m`, so let's just set it to the arbitrary value 0. m := 0; var n := 0; while n < a.Length invariant 0 <= n <= a.Length invariant forall i :: 0 <= i < n ==> m <= a[i] // "what's been done so far" invariant { // We can follow a systematic process for coming up with the loop body of // this program. From the decision to use a loop index `n`, starting from 0 // and going up to `a.Length`, several parts of the loop are already determined: // - We use `n := 0` to initialize `n` before the loop // - We use the loop invariant `0 <= n <= a.Length` // - We use the loop guard `n < a.Length` (or `n != a.Length` works equally well) // - We use the termination metric `a.Length - n`, which is the default `decreases` clause // - We use `n := n + 1` in the loop body to increment the loop index // We formed the second loop invariant by replacing the constant `a.Length` in // the postcondition with the variable `n`. This loop invariant speaks of "what we've // computed so far", which is one of many common forms of loop invariants (we'll see // others in the rest of this class and the next). // // From the assignment `n := n + 1`, we can "compute backwards" (as we've seen earlier // in the class) to get a strong hint of how to fill in the loop body. To see // how that's done, read the rest of this loop body bottom up. // 6: The verifier complains that (5) might not hold. This prompts us to add a statement // that tests for (5). If condition (5) does not hold, we'll use `m := a[n]` to establish (5). if a[n] < m { m := a[n]; } // 5: Condition 4a is known to hold just inside the loop body, because the invariant (which // we get to assume on entry to the loop body) tells us so. // Condition 4b can be simplified using the "one-point rule" of on quantifiers, which says that // forall i :: i == e ==> C // is the same as `C` with `i` replaced by expression `e` (provided `e` does not mention `i`). assert m <= a[n]; // 5 // 4a and 4b: We get these by splitting the quantifier (3) according to the following rule: // forall i :: A ==> C // forall i :: B ==> C // == // forall i :: A || B ==> C assert forall i :: 0 <= i < n ==> m <= a[i]; // 4a assert forall i :: i == n ==> m <= a[i]; // 4b assert forall i :: 0 <= i < n || i == n ==> m <= a[i]; // 3: Like (2), but splitting the range `0 <= i < n + 1` into two assert forall i :: 0 <= i < n + 1 ==> m <= a[i]; // 2: This line is obtained by replacing `n` by `n + 1` in (1) n := n + 1; // 0: This is the loop body we start with assert forall i :: 0 <= i < n ==> m <= a[i]; // 1: Copy the loop invariant here } } // In the last step of the loop-body development above, we chose the statement `m := a[n]` // to establish condition (5). This is just one of many possible choices. For example, // `m := a[n] - 19` would also have worked, since all we needed to ensure was `m <= a[n]`. // Similarly, the initializing assignment `m := 0` was also arbitrary. The reason we could // get away with such assignments is that the specification of `Min0` doesn't say everything // we want of a method for computing the minimum of an array. In this next version, we add // another postcondition. method Min1(a: array) returns (m: int) // 3: The initialization (2) of `m` only works if the array is nonempty. Indeed, there // is no way to establish postcondition (0) for an empty array. So, we add the following // precondition. requires a.Length != 0 ensures forall i :: 0 <= i < a.Length ==> m <= a[i] ensures exists i :: 0 <= i < a.Length && m == a[i] // 0: the new postcondition { // 2: Invariant (1) forces us to rethink the initialization of `m`. Any element // of `a` would work; we'll just pick `a[0]`. m := a[0]; // 4: Optionally, we can make the program skip the iteration where `n` is 0, // since that iteration only increments `n` from 0 to 1 anyhow. So, we might // as well start `n` at 1. (If you'd like, you can then also change the first // loop invariant to `1 <= n <= a.Length`.) var n := 0; while n < a.Length invariant 0 <= n <= a.Length invariant forall i :: 0 <= i < n ==> m <= a[i] // 1: To establish our goal (0), we add that condition as a loop invariant. // (An alternative would be to replace the constant `a.Length` with the variable `n`, // but choosing (0) itself is simpler.) invariant exists i :: 0 <= i < a.Length && m == a[i] // "always holds" invariant { if a[n] < m { // 5: With our new loop invariant, there is only one way to do the assignment on // the next line. m := a[n]; } n := n + 1; } } // Coincidence Count is the problem of computing how many elements are // shared between two arrays. The arrays are given to be strictly increasing, // which makes it unambiguous to specify what "number of shared elements" // means. We'll use a function that returns the set of common elements // of two given sequences. The coincidence count is thus the cardinality // of the set `InBoth(a[..], b[..])`. ghost function InBoth(s: seq, t: seq): set { set x | x in s && x in t } method CoincidenceCount0(a: array, b: array) returns (c: nat) requires forall i, j :: 0 <= i < j < a.Length ==> a[i] < a[j] requires forall i, j :: 0 <= i < j < b.Length ==> b[i] < b[j] ensures c == |InBoth(a[..], b[..])| { var m, n := 0, 0; c := 0; while m < a.Length || n < b.Length invariant 0 <= m <= a.Length && 0 <= n <= b.Length invariant c == |InBoth(a[..m], b[..n])| // The following assert lets Dafny prove the postcondition from the // loop specification above. That gives us some confidence that the loop // specification will be useful. However, as the class slides (and // the book) try to explain, it is difficult to work with a "what's been // done so far" invariant for this problem. assert a[..a.Length] == a[..] && b[..b.Length] == b[..]; } method CoincidenceCount1(a: array, b: array) returns (c: nat) requires forall i, j :: 0 <= i < j < a.Length ==> a[i] < a[j] requires forall i, j :: 0 <= i < j < b.Length ==> b[i] < b[j] ensures c == |InBoth(a[..], b[..])| { var m, n := 0, 0; c := 0; while m < a.Length && n < b.Length invariant 0 <= m <= a.Length && 0 <= n <= b.Length // Instead, we'll choose a "what's left to be done" invariant. We've // seen examples of such invariants before, like in the variety of // programs that compute the sum of list elements. Note that we're now // able to use an `&&` instead of an `||` in the loop guard, which gives // the loop an opportunity to end its iterations earlier. invariant |InBoth(a[..], b[..])| == c + |InBoth(a[m..], b[n..])| // What about termination? Here are three possible termination metrics: // decreases a.Length - m + b.Length - n // decreases a.Length - m, b.Length - n // decreases a.Length - m, if m < a.Length then b.Length - n else -1 // Dafny chooses the third of these as the default `decreases` clause. { // It's not so difficult to guess good assignments in the following three cases. // But proving that they maintain the invariant requires some effort. if a[m] == b[n] { // 3: Condition (2) has the form // |X| == 1 + |Y| // where `X` and `Y` are sets. The set cardinality operator `|_|` is a function that // is applied to these sets. To reason about functions applied to sets, it is // often necessary and fruitful to explicitly write down conditions that relate the // sets directly. For our situation here, we have // X == {a[m]} + Y // and that turns out to be the hint the verifier needs. You can derive the necessary hints // for the other cases below using similar steps. assert InBoth(a[m..], b[n..]) == {a[m]} + InBoth(a[m + 1..], b[n + 1..]); assert |InBoth(a[m..], b[n..])| == 1 + |InBoth(a[m + 1..], b[n + 1..])|; // 2: simplify (1) according to the invariant on entry to the loop body assert |InBoth(a[..], b[..])| == c + 1 + |InBoth(a[m + 1..], b[n + 1..])|; // 1: work backwards from (0) c, m, n := c + 1, m + 1, n + 1; assert |InBoth(a[..], b[..])| == c + |InBoth(a[m..], b[n..])|; // 0: the invariant condition we want to establish } else if a[m] < b[n] { assert InBoth(a[m..], b[n..]) == InBoth(a[m + 1..], b[n..]); m := m + 1; } else { assert InBoth(a[m..], b[n..]) == InBoth(a[m..], b[n + 1..]); n := n + 1; } } }