3 A classical example. Searches a sorted array for a given value v. *)
8 use int.ComputerDivision
12 (* the code and its specification *)
14 exception Break int (* raised to exit the loop *)
15 exception Not_found (* raised to signal a search failure *)
18 ensures { 2*result = x }
20 let binary_search [@bddinfer] [@infer](a : array int) (v : int)
21 requires { forall i1 i2 : int. 0 <= i1 <= i2 < length a -> a[i1] <= a[i2] }
22 ensures { 0 <= result < length a /\ a[result] = v }
23 raises { Not_found -> forall i:int. 0 <= i < length a -> a[i] <> v }
27 let u = ref (length a - 1) in
29 invariant { !u < length a }
31 forall i : int. 0 <= i < length a -> a[i] = v -> !l <= i <= !u }
33 let m = !l + mydiv (!u - !l) in
34 assert { !l <= m <= !u };
47 let binary_search2 [@bddinfer] [@infer:oct](a : array int) (v : int)
48 requires { forall i1 i2 : int. 0 <= i1 <= i2 < length a -> a[i1] <= a[i2] }
49 ensures { 0 <= result < length a /\ a[result] = v }
50 raises { Not_found -> forall i:int. 0 <= i < length a -> a[i] <> v }
54 let u = ref (length a - 1) in
56 invariant { !u < length a }
58 forall i : int. 0 <= i < length a -> a[i] = v -> !l <= i <= !u }
60 let m = !l + mydiv (!u - !l) in
61 assert { !l <= m <= !u };
74 let binary_search3 [@bddinfer] [@infer:box](a : array int) (v : int)
75 requires { forall i1 i2 : int. 0 <= i1 <= i2 < length a -> a[i1] <= a[i2] }
76 ensures { 0 <= result < length a /\ a[result] = v }
77 raises { Not_found -> forall i:int. 0 <= i < length a -> a[i] <> v }
81 let u = ref (length a - 1) in
83 invariant { !u < length a }
85 forall i : int. 0 <= i < length a -> a[i] = v -> !l <= i <= !u }
87 let m = !l + mydiv (!u - !l) in
88 assert { !l <= m <= !u };