4 Exercise proposed by Rustan Leino at Dagstuhl seminar 16131, March 2016
6 You are given two sequences of integers, sorted in increasing
7 order and without duplicate elements, and you count the number of
8 elements that appear in both sequences (in linear time and constant
11 See also coincidence_count.mlw for a version using arrays.
13 Authors: Jean-Christophe FilliĆ¢tre (CNRS)
16 module CoincidenceCount
24 clone export list.Sorted
25 with type t = int, predicate le = (<), goal Transitive.Trans
27 let rec coincidence_count (a b: list int) : set
30 ensures { result == inter (elements a) (elements b) }
34 | Cons ha ta, Cons hb tb ->
36 add ha (coincidence_count ta tb)
38 coincidence_count ta b
40 coincidence_count a tb
47 (* the same, with elements of any type *)
49 module CoincidenceCountAnyType
58 val predicate eq (x y : t)
59 ensures { result <-> x = y }
61 clone set.SetApp with type elt = t, val eq = eq
63 val predicate rel (x y : t)
65 clone relations.TotalStrictOrder with type t, predicate rel, axiom .
67 clone export list.Sorted
68 with type t = t, predicate le = rel, goal Transitive.Trans
70 let rec coincidence_count (a b: list t) : set
73 ensures { result == inter (elements a) (elements b) }
77 | Cons ha ta, Cons hb tb ->
79 add ha (coincidence_count ta tb)
80 else if rel ha hb then
81 coincidence_count ta b
83 coincidence_count a tb
90 (* the same, using only lists *)
92 module CoincidenceCountList
98 clone export list.Sorted
99 with type t = int, predicate le = (<), goal Transitive.Trans
101 let rec coincidence_count (a b: list int) : list int
102 requires { sorted a }
103 requires { sorted b }
104 ensures { forall x. mem x result <-> mem x a /\ mem x b }
108 | Cons ha ta, Cons hb tb ->
110 Cons ha (coincidence_count ta tb)
112 coincidence_count ta b
114 coincidence_count a tb