hash-tables.sls 2.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. #!chezscheme
  2. (library (mit hash-tables)
  3. (export make-key-weak-eqv-hash-table
  4. make-key-weak-eq-hash-table
  5. make-weak-eq-hash-table
  6. make-eq-hash-table
  7. hash-table/get
  8. hash-table/put!
  9. eqv-hash-mod
  10. equal-hash-mod
  11. weak-hash-table/constructor
  12. strong-hash-table/constructor
  13. hash-table/intern!
  14. hash-table/key-list
  15. hash
  16. hash-table->alist)
  17. (import (except (chezscheme) error assert sort)
  18. (mit core)
  19. (mit curry)
  20. )
  21. (define make-key-weak-eqv-hash-table make-weak-eqv-hashtable)
  22. (define make-key-weak-eq-hash-table make-weak-eq-hashtable)
  23. (define make-weak-eq-hash-table make-key-weak-eq-hash-table)
  24. (define make-eq-hash-table make-key-weak-eq-hash-table)
  25. ;;(define make-eq-hash-table make-eq-hashtable)
  26. (define hash-table/get hashtable-ref)
  27. (define hash-table/put! hashtable-set!)
  28. (define (hash-table/intern! table key get-default)
  29. (let ((default (get-default)))
  30. (unless (hashtable-contains? table key)
  31. (hashtable-set! table key default))
  32. (hashtable-ref table key default)))
  33. ;; from schez-scheme s/newhash.ss
  34. (define eqv-generic?
  35. (lambda (x)
  36. ;; all numbers except fixnums must go through generic hashtable
  37. (and (number? x)
  38. (or (flonum? x) (bignum? x) (ratnum? x) (exact? x) (inexact? x)))))
  39. (define (eqv-hash key)
  40. (equal-hash key)
  41. ;; (if (eqv-generic? key)
  42. ;; ;; equal-hash passes numbers to number-hash, as the internal eqv-hash
  43. ;; (equal-hash key)
  44. ;; (symbol-hash key))
  45. )
  46. ;; from MIT-Scheme
  47. ;; (define (eqv-hash-mod key modulus)
  48. ;; (remainder (eqv-hash key) modulus))
  49. (define* (eqv-hash-mod key #:optional modulus) (eqv-hash key))
  50. ;; (define (equal-hash-mod key modulus)
  51. ;; (remainder (equal-hash key) modulus))
  52. (define* (equal-hash-mod key #:optional modulus) (equal-hash key))
  53. (define* (hash key #:optional modulus)
  54. (if (default-object? modulus)
  55. (equal-hash key)
  56. (equal-hash-mod key modulus)))
  57. ;; XXX: since we do not have a generic weak hashtable constructor,
  58. ;; we make weak-pairs in generic/weak.scm normal pairs.
  59. (define weak-hash-table/constructor
  60. (lambda* (key-hash key=? #:optional rehash-after-gc?)
  61. (lambda () (make-hashtable key-hash key=?))))
  62. (define strong-hash-table/constructor
  63. (lambda* (key-hash key=? #:optional rehash-after-gc?)
  64. (lambda () (make-hashtable key-hash key=?))))
  65. (define hash-table/key-list hashtable-keys)
  66. (define (hash-table->alist ht)
  67. (let-values (((keys vals) (hashtable-entries ht)))
  68. (vector->list
  69. (vector-map (lambda (k v) (cons k v)) keys vals))))
  70. )