spacepaste

  1.  
  2. #!/usr/bin/env bash
  3. # -*- mode: scheme -*-
  4. exec guile $0
  5. # !#
  6. (import (ice-9 rdelim)
  7. (ice-9 hash-table))
  8. (define (count-or-unicode>? a b)
  9. (let ((Na (car a))(Nb (car b)))
  10. (or (> Na Nb)
  11. (and (= Na Nb)
  12. (string<? (cdr a) (cdr b))))))
  13. (define delimiters " \t\n")
  14. (define (count-words port)
  15. (define buf (make-string 10000))
  16. (define (read-word port)
  17. (let ((res (%read-delimited! delimiters buf #t port)))
  18. (or (and (eof-object? (car res))
  19. (car res))
  20. (substring buf 0 (cdr res)))))
  21. (define count (make-hash-table (inexact->exact 1e5)))
  22. (define (add-word next)
  23. (hash-set! count next
  24. (1+ (hash-ref count next 0))))
  25. (let loop ((next (read-word port)))
  26. (unless (eof-object? next)
  27. (add-word next)
  28. (loop (read-word port))))
  29. (sort! ;; destructive sort to save memory
  30. (hash-map->list (lambda (key val) (cons val key)) count)
  31. count-or-unicode>?))
  32. (for-each
  33. (lambda (x) (format #t "~a\t~a\n" (cdr x) (car x)))
  34. (count-words (current-input-port)))
  35.