htab.clu 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. % HTAB CLU
  2. %
  3. % A simple hash table mapping strings to objects of type 't'.
  4. table = cluster [t: type] is create, % -> table[t]
  5. lookup, % table[t], str -> t => not_found
  6. enter, % table[t], str, t => already_exists
  7. alter, % table[t], str, t ->
  8. remove; % table[t], str => not_found
  9. rep = array[bucket];
  10. bucket = array[entry];
  11. entry = record[key: str,
  12. value: t];
  13. size = 521;
  14. create = proc () returns (cvt);
  15. tab: rep := rep$predict(1, size);
  16. for i: int in int$from_to(1, size) do
  17. rep$addh(tab, bucket$create(1));
  18. end;
  19. return(tab);
  20. end create;
  21. lookup = proc (tab: cvt, key: str) returns (t) signals (not_found);
  22. for ent: entry in bucket$elements(tab[hash(key, size)]) do
  23. if key = ent.key
  24. then return(ent.value); end;
  25. end;
  26. signal not_found;
  27. end lookup;
  28. enter = proc (tab: cvt, key: str, value: t) signals (already_exists);
  29. buck: bucket := tab[hash(key, size)];
  30. for ent: entry in bucket$elements(buck) do
  31. if key = ent.key
  32. then signal already_exists; end;
  33. end;
  34. bucket$addh(buck, entry${key: key,
  35. value: value});
  36. end enter;
  37. alter = proc (tab: cvt, key: str, value: t);
  38. buck: bucket := tab[hash(key, size)];
  39. for ent: entry in bucket$elements(buck) do
  40. if key = ent.key
  41. then ent.value := value;
  42. return;
  43. end;
  44. end;
  45. bucket$addh(buck, entry${key: key,
  46. value: value});
  47. end alter;
  48. remove = proc (tab: cvt, key: str) signals (not_found);
  49. buck: bucket := tab[hash(key, size)];
  50. for i: int in bucket$indexes(buck) do
  51. if key = buck[i].key
  52. then h: int := bucket$high(buck);
  53. if i < h
  54. then buck[i] := buck[h]; end;
  55. bucket$remh(buck);
  56. return;
  57. end;
  58. end;
  59. signal not_found;
  60. end remove;
  61. end table;