count.scm 547 B

1234567891011121314151617181920
  1. (define (insert-word word histogram)
  2. (let loop ((h histogram))
  3. (if (null? h)
  4. (cons (cons word 1) histogram)
  5. (let ((entry (car h)))
  6. (if (equal? word (car entry))
  7. (begin (set-cdr! entry (+ 1 (cdr entry)))
  8. histogram)
  9. (loop (cdr h)))))))
  10. (define (count-words p)
  11. (let loop ((word '()))
  12. (let ((char (read-char p)))
  13. (cond ((eof-object? char) '())
  14. ((whitespace? char)
  15. (if (null? word)
  16. (loop '())
  17. (insert-word (list->string (reverse word)) (loop '()))))
  18. (else (loop (cons char word)))))))