spacepaste

  1.  
  2. (import (ice-9 rdelim)
  3. (ice-9 hash-table))
  4. (define (count-or-unicode>? a b)
  5. (let ((Na (car a))(Nb (car b)))
  6. (if (> Na Nb)
  7. #t
  8. (if (= Na Nb)
  9. (string<? (cdr a) (cdr b))
  10. #f))))
  11. (define (skip-whitespace port)
  12. (let ([ch (peek-char port)])
  13. (when (and (not (eof-object? ch)) (char-whitespace? ch))
  14. (read-char port)
  15. (skip-whitespace port))))
  16. (define (count-words port)
  17. (define (read-word port)
  18. (skip-whitespace port)
  19. (let ((line (read-delimited "\t" port)))
  20. (if (eof-object? line)
  21. #f
  22. (map (λ (x) (string-split x #\space))
  23. (string-split line #\newline)))))
  24. (define count (make-hash-table 100000))
  25. (define (add-word next)
  26. (unless (string-null? next)
  27. (hash-set! count next
  28. (1+ (hash-ref count next 0)))))
  29. (let loop ((next (read-word port)))
  30. (when next
  31. (for-each (lambda (wl)
  32. (for-each (lambda (w) (add-word w)) wl))
  33. next)
  34. (loop (read-word port))))
  35. (sort! ;; destructive sort to save memory
  36. (hash-map->list (lambda (key val) (cons val key)) count)
  37. count-or-unicode>?))
  38. (for-each
  39. (lambda (x) (format #t "~a\t~a\n" (cdr x) (car x)))
  40. (count-words (current-input-port)))
  41.