Much Ado About Verada

A cheerful guide to programs that keep their promises.

8 · A Midsummer Night's Proof

How do I keep a tally within bounds as I walk the row?

Puck has walked the row calling out free seat numbers. “Three! Five! Seven!” The clerk would like one number for the sign above the window. This seems to Puck a terrible waste of perfectly good numbers.

He'll go down the same row again, making one mark per free seat. To see why the tally fits in a theatre of eight seats, stop partway down the row. What's the largest it could be at that point?

Bring with you. A loop that visits each offset and a chart where True means taken.

Stop before the next seat

Keep the row from chapter 7. Seats 3, 5, and 7 are free. Start a tally at zero. Each time you see a free seat, add one. At a taken seat, leave the tally alone.

Freeze the walk just before inspecting seat 4. How many seats have you inspected? What should the tally say? How high could it be if any of those three seats were free?

Before seat 1, zero seats inspected and zero free. Before seat 4, three inspected and one free. After seat 8, eight inspected and three free.

The lit part of the row is the part Puck has inspected. The candle has a stricter sense of time than he does.

At the start of each visit, the tally is at most the number of seats already inspected. That part of the row is the prefix. At the checkpoint before seat 4, the next offset is 3 and the prefix contains seats 1, 2, and 3. The tally is 1 free seat. The next offset also counts the seats inspected because we started at offset 0 and visited the slots in order.

A loop invariant is a fact that holds every time execution reaches its checkpoint. Put the checkpoint before the lookup, where the count of inspected seats is exactly offset. Here the fact is free <= offset. The count's type already supplies the lower bound of zero.

Puck takes a candle along the aisle.

Carry the fact through one visit

  1. Arrive. Before offset 0, the tally is 0. Zero is at most zero.
  2. Continue. A taken seat leaves the tally alone. A free seat adds one. The number inspected increases by one either way, so the tally still fits under the new limit.
  3. Finish. At the last checkpoint the offset is 7. The tally is at most 7, so even the last possible increment fits in a Seat_Count from 0 through 8.

The proof can reason about one visit at a time. The checkpoint gives it a fact about earlier visits that it can use on the next one.

Example 8-1 · Count the free seats

Copy your example project. Read the loop in Count_Free or count_free first. The type declarations and the printing at the end give the tally its bounds and show its result.

Vada · Ada · Example 8-1

main.vadb · Link to this version

with Ada.Text_IO;

procedure Main is
   subtype Row_Offset is Natural range 0 .. 7;
   subtype Seat_Count is Natural range 0 .. 8;
   type Seat_Row is array (Row_Offset) of Boolean;

   function Count_Free (Taken : Seat_Row) return Seat_Count is
      Free : Seat_Count := 0;
   begin
      for Offset in Row_Offset loop
         pragma Loop_Invariant (Free <= Offset);
         if not Taken (Offset) then
            Free := Free + 1;
         end if;
      end loop;
      return Free;
   end Count_Free;

   Taken : constant Seat_Row :=
     [True, True, False, True, False, True, False, True];
begin
   Ada.Text_IO.Put_Line ("Free seats:" & Seat_Count'Image (Count_Free (Taken)));
end Main;
Varc · C-family · Example 8-1

main.va · Link to this version

import Ada.Text_IO;

fn Main() {
    subtype Row_Offset = Natural range 0...7;
    subtype Seat_Count = Natural range 0...8;
    type Seat_Row = [Row_Offset]Boolean;

    fn count_free(taken: Seat_Row) -> Seat_Count {
        var free: Seat_Count = 0;
        for offset in Row_Offset {
            invariant free <= offset;
            if !taken[offset] {
                free = free + 1;
            }
        }
        return free;
    }

    let taken: Seat_Row = [True, True, False, True, False, True, False, True];
    Ada.Text_IO.Put_Line("Free seats:" ++ Seat_Count::Image(count_free(taken)));
}
Vibe · Python · Example 8-1

main.vb · Link to this version

from verada import Annotated, Array, Interval, invariant

type Seat_Count = Annotated[int, Interval(ge=0, le=8)]


class Seat_Row(Array[bool], size=8):
    pass


def count_free(taken: Seat_Row) -> Seat_Count:
    free: Seat_Count = 0
    for offset in range(8):
        invariant(free <= offset)
        if not taken[offset]:
            free = free + 1
    return free


def main() -> None:
    taken = Seat_Row([True, True, False, True, False, True, False, True])
    print("Free seats:", count_free(taken))


if __name__ == "__main__":
    main()

Syntax note. Vada uses pragma Loop_Invariant, Varc uses invariant …;, and Vibe imports invariant(…) from verada. All three place the annotation before the lookup. Vibe's range(8) visits offsets 0 through 7, the same offsets named by Row_Offset in the other two routes.

Run veradic prove and then veradic run. For this row the program prints:

Free seats: 3

The invariant explains why the count fits. The run tells us that this particular row produces 3. Recall chapter 4's weak promise. Returning zero would fit the range too. How much a proof tells us depends on what we asked Verada to establish.

A slate with three chalk marks.

Your cue

  1. Try an all-taken row, then an all-free row. For each row, predict the tally just before the last seat (seat 8, offset 7) and again at the end.
  2. Keep the all-free row. In the free-seat branch, add 2 when the offset is 0 and add 1 at every other offset. Run veradic prove. At which visit would the next checkpoint first be false?
  3. Restore the original loop and mixed row. Change the function's final return to return 0. Prove and run it. Which promise does this version keep, and which expectation does it miss?
Prompter's notes

The all-taken row stays at 0. The all-free row has a tally of 7 before the last visit and 8 after it. In both cases the final increment, if taken, fits the count type.

Counting the first free seat twice makes the tally 2 before offset 1, after just one inspection. Verada reports B5104 because one iteration breaks the invariant at the next checkpoint.

The zero return fits Seat_Count and the loop still satisfies its own checks. It prints Free seats: 0 for a row with three free seats. Restore the original return.

Puck can count the whole row. The next customer asks a question he might answer sooner. Is there a free seat anywhere?

← Previous: All the World's an Array · Contents · Next: Is There Room in the House? →