[plt-scheme] help on how to write a frequency-counting function in a more functional way
Matthias Felleisen wrote:
> ;; String -> Void
> ;; sort, then create association list via [Listof [List Nat Nat]]
> (define (cnt-alst f g)
> (define l:in
> (with-input-from-file f
> (rec L
> (lambda ()
> (define nxt (read))
> (if (eof-object? nxt) '() (cons nxt (L)))))))
> (define l:st (sort l:in <))
> (define res
> (let L ([l (cdr l:st)][p (car l:st)][c 1])
> (if (null? l) '()
> (let ([a (car l)])
> (if (= a p)
> (L (cdr l) p (+ c 1))
> (cons (list p c) (L (cdr l) (car l) 1)))))))
> (out-al g res))
There's a bug in this code that causes the most frequent word to be
omitted from the result. The body of the second L should be changed to:
(if (null? l) '() ...)
(if (null? l) (list (list p c)) ...)
David