muller.mlw 875 Bytes
Newer Older
1

Jean-Christophe Filliatre's avatar
Jean-Christophe Filliatre committed
2 3 4 5 6 7
(* A small verification challenge proposed by Peter Müller.

   Given an array of integers, we first count how many non-zero values
   it contains. Then we allocate a new array with exactly this size and
   we fill it with the non-zero values. *)

8 9 10
module Muller

  use import int.Int
11 12
  use import ref.Refint
  use import array.Array
13

14 15
  type param = array int
  predicate pr (a: param) (n: int) = a[n] <> 0
Andrei Paskevich's avatar
Andrei Paskevich committed
16
  clone import int.NumOfParam with type param = param, predicate pr = pr
17

Jean-Christophe Filliatre's avatar
Jean-Christophe Filliatre committed
18
  let compact (a: array int) =
19
    let count = ref 0 in
20
    for i = 0 to length a - 1 do
21
      invariant { 0 <= !count = num_of a 0 i <= i}
22 23 24 25 26
      if a[i] <> 0 then incr count
    done;
    let u = make !count 0 in
    count := 0;
    for i = 0 to length a - 1 do
27
      invariant { 0 <= !count = num_of a 0 i <= i }
28
      if a[i] <> 0 then begin u[!count] <- a[i]; incr count end
29
    done
30 31

end