fork download
  1. ; duplicate items in an array
  2.  
  3. (define (identity x) x)
  4.  
  5. (define (make-hash hash eql? size)
  6. (let ((hash-table (make-vector size (list))))
  7. (case-lambda
  8. ((lookup key)
  9. (let ((idx (modulo (hash key) size)))
  10. (let loop ((bucket (vector-ref hash-table idx)))
  11. (cond ((null? bucket) bucket)
  12. ((eql? (caar bucket) key) (car bucket))
  13. (else (loop (cdr bucket)))))))
  14. ((install key value)
  15. (let ((idx (modulo (hash key) size)))
  16. (let loop ((bucket (vector-ref hash-table idx)) (new-bucket (list)))
  17. (cond ((null? bucket)
  18. (vector-set! hash-table idx (cons (cons key value) new-bucket)))
  19. ((eql? (caar bucket) key)
  20. (vector-set! hash-table idx
  21. (append (cons (cons key value) (cdr bucket)) new-bucket)))
  22. (else (loop (cdr bucket) (cons (car bucket) new-bucket)))))))
  23. (else (error 'hash-table "unrecognized command")))))
  24.  
  25. (define (dup-hash xs)
  26. (let ((h (make-hash identity = 97))
  27. (dups (list)))
  28. (do ((xs xs (cdr xs)))
  29. ((null? xs) dups)
  30. (when (pair? (h 'get (car xs)))
  31. (set! dups (cons (car xs) dups)))
  32. (h 'put (car xs) (car xs)))))
  33.  
  34. (define (dup-sort xs)
  35. (let ((xs (sort xs <)))
  36. (let loop ((prev (car xs)) (xs (cdr xs)) (dups (list)))
  37. (if (null? xs) dups
  38. (if (= prev (car xs))
  39. (loop prev (cdr xs) (cons (car xs) dups))
  40. (loop (car xs) (cdr xs) dups))))))
  41.  
  42. (define xs '(1 2 3 1 4))
  43. (define ys '(1 2 3 1 2 4 1))
  44.  
  45. (display (dup-hash xs)) (newline)
  46. (display (dup-sort xs)) (newline)
  47. (display (dup-hash ys)) (newline)
  48. (display (dup-hash ys)) (newline)
Success #stdin #stdout 0.04s 8744KB
stdin
Standard input is empty
stdout
(1)
(1)
(1 2 1)
(1 2 1)