Created
May 8, 2019 19:41
-
-
Save slipset/2047fb635654f5564701c2cbabf210e1 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(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