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