Hello,
Is there a standard Lisp function that will take a list and return an
associative list representing the symbol frequency in the original list?
For example, (frequency '(a (a (b) a))) => ((a . 3) (b . 1)). Any help
would be greatly appreciated.
Thank you.
"Evan Klinger" <········@uci.edu> wrote in message ·················@news.service.uci.edu...
> Hello,
>
> Is there a standard Lisp function that will take a list and return an
> associative list representing the symbol frequency in the original list?
> For example, (frequency '(a (a (b) a))) => ((a . 3) (b . 1)). Any help
> would be greatly appreciated.
>
> Thank you.
Coincidentally, someone else asked the same question earlier today.
(defun occurrences (list &key (test #'eql))
(if (consp list)
(let (alist)
(labels ((occurrences-aux (object)
(cond ((null object))
((consp object)
(occurrences-aux (first object))
(occurrences-aux (rest object)))
(t
(let ((count (assoc object alist :test test)))
(if (null count)
(setf alist (acons object 1 alist))
(incf (rest count))))))))
(occurrences-aux (first list))
(occurrences-aux (rest list)))
alist)))
> (occurrences '(a (a (a b c) b c) b . c))
((C . 3) (B . 3) (A . 3))
Regards,
jag
In article <············@news.service.uci.edu>,
Evan Klinger <········@uci.edu> wrote:
>Is there a standard Lisp function that will take a list and return an
>associative list representing the symbol frequency in the original list?
>For example, (frequency '(a (a (b) a))) => ((a . 3) (b . 1)). Any help
>would be greatly appreciated.
No, there's no standard function for this; it seems like a pretty unusual,
application-specific need rather than being appropriate for a
general-purpose library. And it's pretty easy to implement yourself, as in
the other response.
BTW, the values in that alist seem to be the count of occurrences, not the
frequency, where I interpret frequency to mean a ratio, e.g. ((a . 3/4) (b
. 1/4)).
--
Barry Margolin, ······@genuity.net
Genuity, Woburn, MA
*** DON'T SEND TECHNICAL QUESTIONS DIRECTLY TO ME, post them to newsgroups.
Please DON'T copy followups to me -- I'll assume it wasn't posted to the group.