fork(1) download
  1. ; a dozen lines of code
  2.  
  3. (define (make-hash hash eql? size)
  4. (let ((hash-table (make-vector size (list))))
  5. (case-lambda
  6. ((lookup key)
  7. (let ((idx (modulo (hash key) size)))
  8. (let loop ((bucket (vector-ref hash-table idx)))
  9. (cond ((null? bucket) bucket)
  10. ((eql? (caar bucket) key) (car bucket))
  11. (else (loop (cdr bucket)))))))
  12. ((install key value)
  13. (let ((idx (modulo (hash key) size)))
  14. (let loop ((bucket (vector-ref hash-table idx)) (new-bucket (list)))
  15. (cond ((null? bucket)
  16. (vector-set! hash-table idx (cons (cons key value) new-bucket)))
  17. ((eql? (caar bucket) key)
  18. (vector-set! hash-table idx
  19. (append (cons (cons key value) (cdr bucket)) new-bucket)))
  20. (else (loop (cdr bucket) (cons (car bucket) new-bucket)))))))
  21. (else (error 'hash-table "unrecognized command")))))
  22.  
  23. (define (string-hash str)
  24. (do ((i 0 (+ i 1))
  25. (h 0 (+ (* h 31) (char->integer (string-ref str i)))))
  26. ((= (string-length str) i) h)))
  27.  
  28. (define h (make-hash string-hash string=? 17))
  29. (h 'put "alfa" 1)
  30. (h 'put "bravo" 2)
  31. (h 'put "charlie" 3)
  32. (display (h 'get "alfa")) (newline)
  33. (h 'put "alfa" 13)
  34. (display (h 'get "alfa")) (newline)
Success #stdin #stdout 0.04s 8744KB
stdin
Standard input is empty
stdout
(alfa . 1)
(alfa . 13)