summaryrefslogtreecommitdiff
path: root/exercism/emacs-lisp/word-count/word-count.el
blob: bd5177253fa99ba78184de7382ba4b48b0f4a782 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
;;; word-count.el --- word-count Exercise (exercism)

;;; Commentary:

(require 'cl-extra)

;;; Code:
(defun kj/extract-words (str)
  (let ((pos 0)
        (result nil))
    (while (string-match "[[:blank:]'\"]*\\([[:alnum:]']+\\)" str pos)
      (setq pos (match-end 1))
      (push (match-string 1 str) result))
    (nreverse result)))

(defun word-count (str)
  (let* ((table (make-hash-table :test 'equal))
         (result nil)
         (count-word (lambda (w)
                       (setq w (downcase w))
                       (let ((count (gethash w table 0)))
                         (puthash w (1+ count) table))))
         (push-output (lambda (w c)
                        (push (cons w c) result))))
    (cl-mapc count-word (kj/extract-words str))
    (maphash push-output table)
    result))
;;; word-count.el ends here