Idiomatic Clojure way to find the most commonly used items in seq

Given a sequence of elements, I want to find the n most common elements in decreasing order of frequency. So, for example, I would like to pass this unit test:

(fact "can find 2 most common items in a sequence"
      (most-frequent-n 2 ["a" "bb" "a" "x" "bb" "ccc" "dddd" "dddd" "bb" "dddd" "bb"]) 
      =>
      '("bb" "dddd"))

I am new to Clojure and still trying to grab the standard library. Here is what I came up with:

(defn- sort-by-val [s]        (sort-by val s))
(defn- first-elements [pairs] (map #(get % 0) pairs))

(defn most-frequent-n [n items]
  "return the most common n items, e.g. 
     (most-frequent-n 2 [:a :b :a :d :x :b :c :d :d :b :d :b])  => 
         => (:d :b)"
  (take n (->
           items               ; [:a :b :a :d :x :b :c :d :d :b :d :b]
           frequencies         ; {:a 2, :b 4, :d 4, :x 1, :c 1}
           seq                 ; ([:a 2] [:b 4] [:d 4] [:x 1] [:c 1])
           sort-by-val         ; ([:x 1] [:c 1] [:a 2] [:b 4] [:d 4])
           reverse             ; ([:d 4] [:b 4] [:a 2] [:c 1] [:x 1])
           first-elements)))   ; (:d :b :a :c :x)

However, this seems like a complex chain of functions to perform a fairly general operation. Is there a more elegant or more idiomatic (or more efficient) way to do this?

+5
source share
1 answer

As you find, usually you should use a combination of sorting and frequency to get a list sorted by frequency.

(sort-by val (frequencies ["a" "bb" "a" "x" "bb" "ccc" "dddd" "dddd" "bb" "dddd" "bb"]))
=> (["x" 1] ["ccc" 1] ["a" 2] ["dddd" 3] ["bb" 4])

, / . , - :

(defn most-frequent-n [n items]
  (->> items
    frequencies
    (sort-by val)
    reverse
    (take n)
    (map first)))

( , ->>).

, , . - . #/Java, , ......

+8

All Articles