Advertisement
Guest User

Untitled

a guest
May 8th, 2017
51
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Scheme 1.23 KB | None | 0 0
  1.  
  2. (import (ice-9 rdelim)
  3.         (ice-9 hash-table))
  4.  
  5. (define (count-or-unicode>? a b)
  6.   (let ((Na (car a))(Nb (car b)))
  7.     (or (> Na Nb)
  8.         (and (= Na Nb)
  9.              (string<? (cdr a) (cdr b))))))
  10.  
  11. (define (skip-whitespace port)
  12.   (let ([ch (peek-char port)])
  13.     (unless (or (eof-object? ch) (char-whitespace? ch))
  14.       (read-char port)
  15.       (skip-whitespace port))))
  16.  
  17. (define (count-words port)
  18.   (define delimiters " \t\n")
  19.   (define buf (make-string 10000))
  20.   (define (read-word port)
  21.     (skip-whitespace port)
  22.     (let ((res (%read-delimited! delimiters buf #t port)))
  23.       (or (and (eof-object? (car res))
  24.                (car res))
  25.           (substring buf 0 (cdr res)))))
  26.   (define count (make-hash-table 100000))
  27.   (define (add-word next)
  28.     (hash-set! count next
  29.                (1+ (hash-ref count next 0))))
  30.   (let loop ((next (read-word port)))
  31.     (unless (eof-object? next)
  32.       (unless (string-null? next)
  33.         (add-word 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.  
  39. (for-each
  40.  (lambda (x) (format #t "~a\t~a\n" (cdr x) (car x)))
  41.  (count-words (current-input-port)))
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement