Refactoring Clojure
Published on: 2025-07-11 16:28:01
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
... Read full article.