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

From: keydana at gmx.de (keydana at gmx.de)
Date: Sat Apr 18 16:18:53 EDT 2009


today on one of the extremely rare occasions where I can use scheme at  
work, I had to get at the frequencies for a list of ids extracted from  
a logfile. E.g., I had a list like

'(1234 1234 5678 1234)

and wanted to, on the one hand, remove the duplicates and, on the  
other hand, store how many instances there were of each id.
For example, if represented as an alist, the result might have looked  
like this:

'((1234 3) (5678 1))

However, I could not imagine a "purely functional" way to do this, and  
so I used a box to update the frequencies, like so:

(define count
  (lambda (lst)
    (let count-accum ((lst lst) (frequencies '()))
      (if (null? lst)
          (let ((first (car lst)))
            (cond ((assoc first frequencies)
                   (let ((count-box (cdr (assoc first frequencies))))
                     (begin (set-box! count-box (+ 1 (unbox count-box)))
                            (count-accum (cdr lst) frequencies))))
                  (else (count-accum (cdr lst) (cons (cons first (box  
1)) frequencies)))))))))

(I also considered a hashtable, which would have been equally "impure"  
and less practical, because the next processing step again required a  

I suppose there must be "more functional" (if I may say so) and more  
elegant ways to perform this task. I'd be glad to learn and thankful  
for any suggestions :-)


-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.racket-lang.org/users/archive/attachments/20090418/a0049874/attachment.html>

Posted on the users mailing list.