vstte10_aqueue.mlw 1.53 KB
Newer Older
1 2 3 4
(*
   VSTTE'10 competition http://www.macs.hw.ac.uk/vstte10/Competition.html
   Problem 5: amortized queue

5 6
   Author: Jean-Christophe Filliatre (CNRS)
   Tool:   Why3 (see http://why3.lri.fr/)
7
*)
8

9 10
module AmortizedQueue

11
  use import int.Int
12 13
  use import option.Option
  use import list.ListRich
14

15 16
  type queue 'a = { front: list 'a; lenf: int;
                    rear : list 'a; lenr: int; }
17
    invariant { length self.front = self.lenf >= length self.rear = self.lenr }
18

Andrei Paskevich's avatar
Andrei Paskevich committed
19
  function sequence (q: queue 'a) : list 'a =
20 21
    q.front ++ reverse q.rear

22 23
  let empty () ensures { sequence result = Nil }
  = { front = Nil; lenf = 0; rear = Nil; lenr = 0 } : queue 'a
24

25 26 27 28
  let head (q: queue 'a)
    requires { sequence q <> Nil }
    ensures { hd (sequence q) = Some result }
  = match q.front with
29 30 31 32
      | Nil      -> absurd
      | Cons x _ -> x
    end

33 34 35 36 37
  let create (f: list 'a) (lf: int) (r: list 'a) (lr: int)
    requires { lf = length f /\ lr = length r }
    ensures { sequence result = f ++ reverse r }
  = if lf >= lr then
      { front = f; lenf = lf; rear = r; lenr = lr }
38 39
    else
      let f = f ++ reverse r in
40
      { front = f; lenf = lf + lr; rear = Nil; lenr = 0 }
41

42 43 44 45
  let tail (q: queue 'a)
    requires { sequence q <> Nil }
    ensures { tl (sequence q) = Some (sequence result) }
  = match q.front with
46 47 48 49
      | Nil      -> absurd
      | Cons _ r -> create r (q.lenf - 1) q.rear q.lenr
    end

50 51 52
  let enqueue (x: 'a) (q: queue 'a)
    ensures { sequence result = sequence q ++ Cons x Nil }
  = create q.front q.lenf (Cons x q.rear) (q.lenr + 1)
53

54
end