Skip to content

Instantly share code, notes, and snippets.

@slipset
Created May 8, 2019 19:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save slipset/2047fb635654f5564701c2cbabf210e1 to your computer and use it in GitHub Desktop.
Save slipset/2047fb635654f5564701c2cbabf210e1 to your computer and use it in GitHub Desktop.
(ns wc.core
(:require [clojure.core.reducers :as r]))
(defn char-counter [key init pred]
(fn [reducing-fn]
(fn
([acc]
(reducing-fn acc))
([acc c]
(reducing-fn (if (pred c)
(update acc key (fnil inc init))
acc) c)))))
(defn word-count [reducing-fn]
(let [in-word (volatile! false)]
(fn
([acc]
(reducing-fn acc))
([acc c]
(reducing-fn (cond
(#{\tab \newline \space} c)
(do (vswap! in-word not)
acc)
(not @in-word)
(do (vswap! in-word not)
(update acc :word-count (fnil inc 0)))
:else acc)
c)))))
(def xform (comp (char-counter :line-count 1 #{\newline})
(char-counter :char-count 0 (constantly true))
word-count))
(defn summarizer [acc _] acc)
(transduce xform (completing (r/monoid summarizer (constantly {}))) "lol\nfoo")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment