Refactoring Clojure

https://news.ycombinator.com/rss Hits: 5
Summary

Refactoring Clojure (1) This article is based on Writing Friendlier Clojure by Adam Bard, where he shows his approach at refactoring some Clojure code that implements an order-1 word-level Markov text generator. Our mission is to take this code and make it readable: (defn markov-data [text] (let [maps (for [line (clojure.string/split text #"\.") m (let [l (str line ".") words (cons :start (clojure.string/split l #"\s+"))] (for [p (partition 2 1 (remove #(= "" %) words))] {(first p) [(second p)]}))] m)] (apply merge-with concat maps))) (defn sentence [data] (loop [ws (data :start) acc []] (let [w (rand-nth ws) nws (data w) nacc (concat acc [w])] (if (= \. (last w)) (clojure.string/join " " nacc) (recur nws nacc))))) After playing a bit with it in the REPL to get a feeling of what is going on and of the shape of the data structure involved, we can start thinking how to refactor. Remember that refactoring means changing the code without changing its behavior, so to know that we are not changing the behavior we need tests. Since the code exists already, we need characterization tests, well explained in the book Working Effectively with Legacy Code by Michael Feathers. The following tests characterize the function markov-data: (deftest markov-of-empty-string (is (= {:start ["."]} (markov/markov-data "")))) (deftest markov-of-one-word-with-stop (is (= {:start ["A."]} (markov/markov-data "A.")))) (deftest markov-of-one-word-without-stop (is (= {:start ["A."]} (markov/markov-data "A")))) (deftest markov-of-two-words (is (= {:start ["A"], "A" ["B."]} (markov/markov-data "A B.")))) (deftest markov-of-two-1-word-sentences (is (= {:start ["A." "B."]} (markov/markov-data "A. B.")))) (deftest markov-of-two-2-word-sentences (is (= {:start ["A" "C"], "A" ["B."], "C" ["D."]} (markov/markov-data "A B. C D.")))) (deftest markov-of-two-sentences-with-repetition (is (= {:start ["A" "A"], "A" ["B." "B"], "B" ["C."]} (markov/markov-data "A B. A B C")))) (deftest markov-of-four-words-with-...

First seen: 2025-05-15 20:40

Last seen: 2025-05-16 00:41