[plt-scheme] help on how to write a frequency-counting function in a more functional way

From: Matthias Felleisen (matthias at ccs.neu.edu)
Date: Tue Apr 28 07:34:57 EDT 2009

Oops, I failed to follow the design recipe ... and that's what I get.



On Apr 28, 2009, at 4:59 AM, David Van Horn wrote:

> 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
>



Posted on the users mailing list.