hashtbl.mlw 1.86 KB
Newer Older
1

MARCHE Claude's avatar
MARCHE Claude committed
2 3
(** {1 Hash tables}

Jean-Christophe Filliatre's avatar
Jean-Christophe Filliatre committed
4 5 6 7
  This module provides Hash tables à la OCaml.
  Each key is mapped to a {h <b>stack</b>} of values,
  with [add h k v] pushing a new value [v] for key [k],
  and [remove h k] popping a value for key [k].
MARCHE Claude's avatar
MARCHE Claude committed
8 9

*)
10

11 12
module Hashtbl

13 14
  use list.List
  use map.Map
15 16 17

  type key

18
  type t 'a = abstract { mutable contents: map key (list 'a) }
19

20
  function ([]) (h: t 'a) (k: key) : list 'a = Map.([]) h.contents k
21

22
  val create (n:int) : t 'a ensures { forall k: key. result[k] = Nil }
23

24
  val clear (h: t 'a) : unit writes {h} ensures { forall k: key. h[k] = Nil }
25

26 27 28
  val add (h: t 'a) (k: key) (v: 'a) : unit writes {h}
    ensures { h[k] = Cons v (old h)[k] }
    ensures { forall k': key. k' <> k -> h[k'] = (old h)[k'] }
29

30
  val mem (h: t 'a) (k: key) : bool
31
    ensures { result=True <-> h[k] <> Nil }
32

33
  val find (h: t 'a) (k: key) : 'a
34 35
    requires { h[k] <> Nil }
    ensures  { match h[k] with Nil -> false | Cons v _ -> result = v end }
36

37
  val find_all (h: t 'a) (k: key) : list 'a
38
    ensures { result = h[k] }
39

40
  exception NotFound
41

42
  val defensive_find (h: t 'a) (k: key) : 'a
43 44
    ensures { match h[k] with Nil -> false | Cons v _ -> result = v end }
    raises  { NotFound -> h[k] = Nil }
45

46
  val copy (h: t 'a) : t 'a
47 48 49 50 51 52 53 54 55 56
    ensures { forall k: key. result[k] = h[k] }

  val remove (h: t 'a) (k: key) : unit writes {h}
    ensures { h[k] = match (old h)[k] with Nil -> Nil | Cons _ l -> l end }
    ensures { forall k': key. k' <> k -> h[k'] = (old h)[k'] }

  val replace (h: t 'a) (k: key) (v: 'a) : unit writes {h}
    ensures {
      h[k] = Cons v (match (old h)[k] with Nil -> Nil | Cons _ l -> l end) }
    ensures { forall k': key. k' <> k -> h[k'] = (old h)[k'] }
57

MARCHE Claude's avatar
MARCHE Claude committed
58
  (*** TODO
Jean-Christophe Filliatre's avatar
Jean-Christophe Filliatre committed
59
     - val length: t 'a -> int (the number of distinct key)
60 61 62 63 64
     - val iter : ('a -> 'b -> unit) -> ('a, 'b) t -> unit
     - val fold : ('a -> 'b -> 'c -> 'c) -> ('a, 'b) t -> 'c -> 'c
  *)

end