Skip to content

Frequency Table

;;; Frequency Table
;;;
;;; prints sorted frequency table for a sequence

(defun freqcount(seq)
  ;; create map of counters
  (let ((m (hashmap)))
    ;; for each  word in text that matches pattern
    (foreach (word  seq)
         ;;; lowercase word
      (assoc! m word
              (+ 1 (get m word))))
    ;; sort list of Map Entries by their values
    (sort (lambda (a b)
            (- (get b "value")
               (get a "value")))
      ;;; get Map.Entries into list
          (append () m))))

(let ((txt "If in this heart a hope be dear,
            ⁠That sound shall charm it forth again:
            If in these eyes there lurk a tear,
            ⁠'Twill flow, and cease to burn my brain")
      (numbers (map (lambda (x) (random 7))
                    (make-array :size 10 :elementType "int"))))
  (print "Word frequency table for text\n"  txt "\n"
         (freqcount
          (map #'lowercase
               (append () (re-seq
                           (re-pattern "\\w+") txt))))
         "\n\n")

  (print "Character frequency table for text\n"  txt "\n"
         (freqcount txt )
         "\n\n")
  (print "Frequency table for array of numbers\n"  numbers "\n"
         (freqcount numbers )
         "\n\n"))

Output:

Word frequency table for text
If in this heart a hope be dear,
            ⁠That sound shall charm it forth again:
            If in these eyes there lurk a tear,
            ⁠'Twill flow, and cease to burn my brain
[if=2, a=2, in=2, be=1, sound=1, hope=1, eyes=1, these=1, that=1, tear=1, and=1, dear=1, twill=1, flow=1, burn=1, again=1, this=1, shall=1, it=1, forth=1, my=1, brain=1, heart=1, lurk=1, cease=1, charm=1, there=1, to=1]

Character frequency table for text
If in this heart a hope be dear,
            ⁠That sound shall charm it forth again:
            If in these eyes there lurk a tear,
            ⁠'Twill flow, and cease to burn my brain
[ =63, a=13, e=13, h=9, r=9, t=9, i=7, n=7, l=6, s=6, o=5, f=4, 
=3, b=3, d=3, ,=3, u=3, I=2, T=2, ⁠=2, c=2, m=2, w=2, y=2, g=1, '=1, k=1, p=1, :=1]

Frequency table for array of numbers
[6, 0, 4, 3, 0, 1, 4, 5, 3, 1]
[0=2, 1=2, 3=2, 4=2, 5=1, 6=1]