Files
why3/examples/decrease1.mlw

55 lines
1.6 KiB
Plaintext
Raw Normal View History

2011-05-15 22:41:28 +02:00
(*
We look for the first occurrence of zero in an array of integers.
The values have the following property: they never decrease by more than one.
The code makes use of that property to speed up the search.
*)
module Decrease1
use import int.Int
2012-10-13 00:23:29 +02:00
use import ref.Ref
use import array.Array
2011-05-15 22:41:28 +02:00
predicate decrease1 (a: array int) =
forall i: int. 0 <= i < length a - 1 -> a[i+1] >= a[i] - 1
2011-05-15 22:41:28 +02:00
2017-05-16 15:48:05 +02:00
let rec lemma decrease1_induction (a: array int) (i j: int) : unit
requires { decrease1 a }
requires { 0 <= i <= j < length a }
ensures { a[j] >= a[i] + i - j }
variant { j - i }
= if i < j then decrease1_induction a (i+1) j
2011-05-15 22:41:28 +02:00
2012-10-13 00:23:29 +02:00
let search (a: array int)
requires { decrease1 a }
ensures {
(result = -1 /\ forall j: int. 0 <= j < length a -> a[j] <> 0)
\/ (0 <= result < length a /\ a[result] = 0 /\
forall j: int. 0 <= j < result -> a[j] <> 0) }
= let i = ref 0 in
2017-06-06 02:13:01 +02:00
while !i < length a do
invariant { 0 <= !i }
invariant { forall j: int. 0 <= j < !i -> j < length a -> a[j] <> 0 }
variant { length a - !i }
if a[!i] = 0 then return !i;
if a[!i] > 0 then i := !i + a[!i] else i := !i + 1
done;
-1
2012-10-13 00:23:29 +02:00
let rec search_rec (a: array int) (i : int)
requires { decrease1 a /\ 0 <= i }
ensures {
2014-01-22 18:13:26 +01:00
(result = -1 /\ forall j: int. i <= j < length a -> a[j] <> 0)
\/ (i <= result < length a /\ a[result] = 0 /\
forall j: int. i <= j < result -> a[j] <> 0) }
variant { length a - i }
2012-10-13 00:23:29 +02:00
= if i < length a then
2011-05-16 15:59:52 +02:00
if a[i] = 0 then i
else if a[i] > 0 then search_rec a (i + a[i])
else search_rec a (i + 1)
else
-1
2011-05-15 22:41:28 +02:00
end