Skip to content

Instantly share code, notes, and snippets.

@Quantisan
Created March 7, 2012 15:37
Show Gist options
  • Save Quantisan/1993844 to your computer and use it in GitHub Desktop.
Save Quantisan/1993844 to your computer and use it in GitHub Desktop.
equal-weight mapped counter
(comment
;; "Usage Example"
(facts
(attrib-model [["a" "a"]
["b"]
["b" "c" "a"]
["b"]]
equal-weights) => {"a" 4/3, "b" 7/3, "c" 1/3})
)
(defn count-occur [coll]
(reduce (fn [m x]
(assoc m x (inc (m x 0))))
{} coll))
(defn map-entry? [x]
(= (type x) clojure.lang.MapEntry))
(defn equal-weights
"
Returns a map with the keys being the elements of an input collection
and vals as a ratio of occurence within the input collection.
Example:
=> (equal-weights [\"a\" \"a\" \"b\" \"c\"])
{\"a\" 2/4, \"b\" 1/4, \"c\" 1/4}
"
[coll]
(let [cnt (count-occur coll)
sum (apply + (vals cnt))]
(loop [m-out {}, m-in cnt]
(let [e (first m-in)]
(if (map-entry? e)
(recur (assoc m-out (key e) (/ (val e) sum)) (rest m-in))
m-out)))))
(defn update-map [m e]
(if-let [[k v] e]
(assoc m k (+ (m k 0) v))
m))
(defn aggregate-maps [m1 m2]
(let [e (first m2)]
(if (map-entry? e)
(aggregate-maps (update-map m1 e) (rest m2))
m1)))
(defn attrib-model [coll model]
(let [cnts (map model coll)]
(reduce aggregate-maps {} cnts)))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment