Hashfun哈希表的函数模型

这个 C 程序 hash.c 实现了一个带 【链地址法|External Chaining】的【哈希表|Hash Table】。 关于哈希表的介绍见 https://www.cs.princeton.edu/~appel/HashTables.pdf
    /* First, access a few standard-library functions */
    #include <stddef.h>
    extern void * malloc (size_t n);
    extern void exit(int n);
    extern size_t strlen(const char *str);
    extern char *strcpy(char *dest, const char *src);
    extern int strcmp(const char *str1, const char *str2);

    /* A function to turn a character-string into an integer */
    unsigned int hash (char *s) {
      unsigned int n=0;
      unsigned int i=0;
      int c=s[i];
      while (c) {
        n = n*65599u+(unsigned)c;
        i++;
        c=s[i];
      }
      return n;
    }

    /* Each "bucket" is a linked list of these cells: */
    struct cell {
      char *key;
      unsigned int count;
      struct cell *next;
    };

    /* How many buckets in the hash table */
    enum {N = 109};

    /* A hash table is an array of buckets */
    struct hashtable {
      struct cell *buckets[N];
    };

    /* first malloc space for a new copy of a string, then copy it. */
    char *copy_string (char *s) {
      int i,n = strlen(s)+1;
      char *p = malloc(n);
      if (!p) exit(1);
      strcpy(p,s);
      return p;
    }

    /* create an empty table */
    struct hashtable *new_table (void) {
      int i;
      struct hashtable *p = 
           (struct hashtable * )malloc(sizeof(struct hashtable));
      if (!p) exit(1);
      for (i=0; i<N; i++) p->buckets[i]=NULL;
      return p;
    }  

    /* allocate and initialize a new linked-list cell */
    struct cell *new_cell (char *key, int count, struct cell *next) {
      struct cell *p = (struct cell * )malloc(sizeof(struct cell));
      if (!p) exit(1);
      p->key = copy_string(key);
      p->count = count;
      p->next = next;
      return p;
    }

    /* lookup up a string in the hash table, getting its occurrence count */
    unsigned int get (struct hashtable *table, char *s) {
      unsigned int h = hash(s);
      unsigned int b = h % N;
      struct cell *p = table->buckets[b];
      while (p) {
        if (strcmp(p->key, s)==0)
          return p->count;
        p=p->next;
      }
      return 0;
    }

    /* increment to the occurrence count of the string s in bucket *r0 */
    void incr_list (struct cell **r0, char *s) {
      struct cell *p, **r;
      for(r=r0; ; r=&p->next) {
        p = *r;
        if (!p) {
          *r = new_cell(s,1,NULL);
          return;
        }
        if (strcmp(p->key, s)==0) {
          p->count++;
          return;
        }
      }
    }  

    /* increment to the occurrence count of the string s the whole hash table */
    void incr (struct hashtable *table, char *s) {
      unsigned int h = hash(s);
      unsigned int b = h % N;
      incr_list (& table->buckets[b], s);
    }

一个函数模型

在证明 C 程序正确之前,先写一个函数程序, 尽量紧密地刻画它的行为。
这个函数程序没有 C 程序那么快:取列表第 n 个 元素要线性时间,每次访问并非(平均)常数时间; 而 C 程序能以常数时间下标访问数组。 不过我们并不在意函数程序的执行时间, 只把它当作 C 程序的模型。
Require Import VST.floyd.functional_base.

#[export] Instance EqDec_string: EqDec (list byte) := list_eq_dec Byte.eq_dec.

Fixpoint hashfun_aux (h: Z) (s: list byte) : Z :=
 match s with
 | nil ⇒ h
 | c :: s' ⇒
      hashfun_aux ((h × 65599 + Byte.signed c) mod Int.modulus) s'
end.

Definition hashfun (s: list byte) := hashfun_aux 0 s.

Definition hashtable_contents := list (list (list byte × Z)).

Definition N := 109.
Lemma N_eq : N = 109.
Proof. reflexivity. Qed.
#[export] Hint Rewrite N_eq : rep_lia.
Global Opaque N.

Definition empty_table : hashtable_contents :=
  Zrepeat nil N.

Fixpoint list_get (s: list byte) (al: list (list byte × Z)) : Z :=
  match al with
 | (k,i) :: al' ⇒ if eq_dec s k then i else list_get s al'
 | nil ⇒ 0
 end.

Fixpoint list_incr (s: list byte) (al: list (list byte × Z))
              : list (list byte × Z) :=
  match al with
 | (k,i) :: al' ⇒ if eq_dec s k
                      then (k, i +1)::al'
                      else (k,i)::list_incr s al'
 | nil ⇒ (s, 1)::nil
 end.

Definition hashtable_get (s: list byte) (contents: hashtable_contents) : Z :=
  list_get s (Znth (hashfun s mod (Zlength contents)) contents).

Definition hashtable_incr (s: list byte) (contents: hashtable_contents)
                      : hashtable_contents :=
  let h := hashfun s mod (Zlength contents)
  in let al := Znth h contents
  in upd_Znth h contents (list_incr s al).

练习: 2 stars,标准 (hashfun_inrange)

Lemma hashfun_inrange: ∀ s, 0 ≤ hashfun s ≤ Int.max_unsigned.
Proof.
(* 在这里填写 *) Admitted.
☐

练习: 1 star,标准 (hashfun_get_unfold)

Lemma hashtable_get_unfold:
 ∀ sigma (cts: list (list (list byte × Z) × val)),
 hashtable_get sigma (map fst cts) =
  list_get sigma (Znth (hashfun sigma mod (Zlength cts)) (map fst cts)).
Proof.
(* 在这里填写 *) Admitted.
☐

练习: 2 stars,标准 (Zlength_hashtable_incr)

Lemma Zlength_hashtable_incr:
 ∀ sigma cts,
      0 < Zlength cts →
      Zlength (hashtable_incr sigma cts) = Zlength cts.
Proof.
(* 在这里填写 *) Admitted.
#[export] Hint Rewrite Zlength_hashtable_incr using list_solve : sublist.
☐

练习: 3 stars,标准 (hashfun_snoc)

Lemma Int_repr_eq_mod:
   ∀ a, Int.repr (a mod Int.modulus) = Int.repr a.
Proof.
Print Int.eqm. (* 这是关于如何证明该引理的提示 *)
Search Int.eqm. (* 这是关于如何证明该引理的提示 *)
(* 在这里填写 *) Admitted.
在 hashfun_aux_snoc 的证明中使用 Int_repr_eq_mod。
Lemma hashfun_aux_snoc:
  ∀ sigma h lo i,
    0 ≤ lo →
    lo ≤ i < Zlength sigma →
  Int.repr (hashfun_aux h (sublist lo (i + 1) sigma)) =
  Int.repr (hashfun_aux h (sublist lo i sigma) × 65599
                                  + Byte.signed (Znth i sigma)).
Proof.
(* 在这里填写 *) Admitted.

Lemma hashfun_snoc:
  ∀ sigma i,
    0 ≤ i < Zlength sigma →
  Int.repr (hashfun (sublist 0 (i + 1) sigma)) =
  Int.repr (hashfun (sublist 0 i sigma) × 65599 + Byte.signed (Znth i sigma)).
Proof.
(* 在这里填写 *) Admitted.
☐

函数模型满足高层规约

哈希表要实现的,是一个从键到值的 【有限映射|Finite Mapping】(有限函数)。 我们声称,函数模型 (empty_table, hashtable_get, hashtable_incr) 正确实现了有限函数这个【抽象数据类型|Abstract Data Type】 上的相应运算。
下面用一个 Module Type 把这个断言形式化:
Module Type COUNT_TABLE.
 Parameter table: Type.
 Parameter key : Type.
 Parameter empty: table.
 Parameter get: key → table → Z.
 Parameter incr: key → table → table.
 Axiom gempty: ∀ k, (* get-empty *)
       get k empty = 0.
 Axiom gss: ∀ k t, (* get-set-same *)
      get k (incr k t) = 1+(get k t).
 Axiom gso: ∀ j k t, (* get-set-other *)
      j ≠ k → get j (incr k t) = get j t.
End COUNT_TABLE.
换言之:任何满足该 Module Type 的 Module 都有一个【计数表|Count Table】类型 table, 以及算子 empty、get、set, 它们满足公理 gempty、gss 与 gso。

COUNT_TABLE 的一个「参考」实现

练习: 2 stars,标准 (FunTable)

用函数实现一个慢速版 COUNT_TABLE 很容易。
Module FunTable <: COUNT_TABLE.
 Definition table: Type := nat → Z.
 Definition key : Type := nat.
 Definition empty: table := fun k ⇒ 0.
 Definition get (k: key) (t: table) : Z := t k.
 Definition incr (k: key) (t: table) : table :=
    fun k' ⇒ if Nat.eqb k' k then 1 + t k' else t k'.
 Lemma gempty: ∀ k, get k empty = 0.
(* 在这里填写 *) Admitted.
 Lemma gss: ∀ k t, get k (incr k t) = 1+(get k t).
(* 在这里填写 *) Admitted.
 Lemma gso: ∀ j k t, j ≠ k → get j (incr k t) = get j t.
(* 在这里填写 *) Admitted.
End FunTable.
☐

演示哈希表实现 COUNT_TABLE

练习: 3 stars,标准 (IntHashTable)

现在用哈希表做一个「快速」实现。 「快速」要打引号:与指令式实现不同, 纯函数式实现取第 i 个【桶|Bucket】是线性时间, 而非常数时间。Znth i al 的耗时与 i 成正比。 这没关系。我们并不把 hashtable_get 与 hashtable_incr 当成真正的实现; 它们只是 C 中快速实现的【函数模型】。
Module IntHashTable <: COUNT_TABLE.
 Definition hashtable_invariant (cts: hashtable_contents) : Prop :=
  Zlength cts = N ∧
  ∀ i, 0 ≤ i < N →
             list_norepet (map fst (Znth i cts))
             ∧ Forall (fun s ⇒ hashfun s mod N = i) (map fst (Znth i cts)).
 Definition table := sig hashtable_invariant.
 Definition key := list byte.

 Lemma empty_invariant: hashtable_invariant empty_table.
 Proof.
(* 在这里填写 *) Admitted.

Lemma incr_invariant: ∀ k cts,
      hashtable_invariant cts → hashtable_invariant (hashtable_incr k cts).
Proof.
(* 在这里填写 *) Admitted.

 Definition empty : table := exist _ _ empty_invariant.
 Definition get : key → table → Z :=
                  fun k tbl ⇒ hashtable_get k (proj1_sig tbl).
 Definition incr : key → table → table :=
       fun k tbl ⇒ exist _ _ (incr_invariant k _ (proj2_sig tbl)).

 Theorem gempty: ∀ k, get k empty = 0.
 Proof.
(* 在这里填写 *) Admitted.

 Theorem gss: ∀ k t, get k (incr k t) = 1 + (get k t).
 Proof.
(* 在这里填写 *) Admitted.

 Theorem gso: ∀ j k t, (* get-set-other *)
      j ≠ k → get j (incr k t) = get j t.
Proof.
(* 在这里填写 *) Admitted.
☐
End IntHashTable.

(* 2026-11-26 16:01 *)