frequency of each unique item in collection

2008-12-11 Thread bOR_
Hi all, I thought I remembered there was a method in the api somewhere that would count the frequency of each unique item in a collection, but I can't find it anymore. What would be a brief way to write that in clojure? (In ruby: array.inject(Hash.new(0)) {|hash,key| hash[key] += 1 ; hash})

Re: frequency of each unique item in collection

2008-12-11 Thread Dave Griffith
(defn frequencies [coll] (reduce (fn [map val] (assoc map val (if (contains map val) (get map val) 1)) #{}) ) On Dec 11, 9:21 am, bOR_ [EMAIL PROTECTED] wrote: Hi all, I thought I remembered there was a method in the api somewhere that would count the frequency of each unique

Re: frequency of each unique item in collection

2008-12-11 Thread Mark McGranaghan
I don't recall a histogram-like method, though I may just be forgetting. (defn frequencies [coll] (reduce (fn [map val] (assoc map val (inc (get map val 1 {} coll)) On Thu, Dec 11, 2008 at 9:33 AM, Dave Griffith [EMAIL PROTECTED] wrote: (defn frequencies [coll]

Re: frequency of each unique item in collection

2008-12-11 Thread Randall R Schulz
On Thursday 11 December 2008 06:33, Dave Griffith wrote: On Dec 11, 9:21 am, bOR_ [EMAIL PROTECTED] wrote: Hi all, I thought I remembered there was a method in the api somewhere that would count the frequency of each unique item in a collection, but I can't find it anymore. What would

Re: frequency of each unique item in collection

2008-12-11 Thread Stuart Sierra
On Dec 11, 9:21 am, bOR_ [EMAIL PROTECTED] wrote: I thought I remembered there was a method in the api somewhere that would count the frequency of each unique item in a collection, but I can't find it anymore. What would be a brief way to write that in clojure? I think what you want is:

Re: frequency of each unique item in collection

2008-12-11 Thread Dave Griffith
Yup, five bugs by my count. Not bad for a one-liner. More coffee necessary. Same algorithm, but tested. (defn frequencies [coll] (reduce (fn [map val] (assoc map val (if (contains? map val) (+ 1 (get map val)) 1))) {} coll) ) On Dec 11, 9:52 am, Randall R Schulz [EMAIL PROTECTED]

Re: frequency of each unique item in collection

2008-12-11 Thread Stuart Sierra
I've added a slightly modified version to clojure.contrib.seq-utils: (defn frequencies Returns a map from distinct items in coll to the number of times they appear. [coll] (reduce (fn [counts x] (assoc counts x (inc (get counts x 0 {} coll)) -Stuart Sierra

Re: frequency of each unique item in collection

2008-12-11 Thread mago
Slightly shorter version: (defn frequencies Returns a map from distinct items in coll to the number of times they appear. [coll] (reduce (fn [counts x] (merge-with + counts {x 1})) {} coll)) On Dec 11, 9:14 am, Stuart Sierra