Search

Dark theme | Light theme

April 24, 2020

Clojure Goodness: Counting Frequency Of Items In A Collection

If we want to know how often an item is part of a collection we can use the frequencies function. This function returns a map where each entry has the item as key and the number of times it appears in the list as value.

In the following example Clojure code we use the frequencies function:

(ns mrhaki.core.frequencies
  (:require [clojure.test :refer [are is]]))


(def sample "Clojure is cool!")

(is (= {\space 2 \! 1 \C 1 \c 1 \e 1 \i 1 \j 1 \l 2 \o 3 \r 1 \s 1 \u 1}
       (frequencies sample))
    "Frequency of each character in sample")


(def list ["Clojure" "Groovy" "Cool" "Goodness"])

(is (= {\C 2 \G 2}
       (frequencies (map first list)))
    "Two words start with C and two with G")


(def numbers '(29 31 42 12 8 73 46))

(defn even-or-odd
  "Return string even when number is even, 
   otherwise return string odd."
  [n]
  (if (even? n)
    "even"
    "odd"))

(is (= {"odd" 3 "even" 4}
       (frequencies (map even-or-odd numbers)))
    "list numbers has 3 odd and 4 even numbers")


(def user {:user "mrhaki" :city "Tilburg" :age 46})

(is (= {java.lang.String 2 java.lang.Long 1}
       (frequencies (map type (vals user))))
    "user map has two values of type String and 1 of type Long")

Written with Clojure 1.10.1.