Skip to content

Instantly share code, notes, and snippets.

@ckirkendall
Last active December 16, 2015 01:49
Show Gist options
  • Save ckirkendall/5357684 to your computer and use it in GitHub Desktop.
Save ckirkendall/5357684 to your computer and use it in GitHub Desktop.
wrap function in clojure based on Uncle Bob's http://blog.8thlight.com/uncle-bob/2013/01/07/FPBE3-Do-the-rules-change.html. I wrote this to provide a more readable and idiomatic version than what Uncle Bob presented.
(use '[clojure.string :only (split)])
(defn break-long-word [n word]
(if (> (count word) n)
[(take n word) (break-long-word n (drop n word))]
[word]))
(defn break-long-words [n words]
(mapcat #(break-long-word n %) words))
(defn combine-words [n [w1 w2 & words]]
(cond (not w1) []
(not w2) [w1]
(>= (+ (count w1) (count w2)) n) (cons w1 (combine-words n (cons w2 words)))
:else (cons (str w1 " " w2) (combine-words n words))))
(defn wrap [n i]
(->> (split i #" ")
(break-long-words n)
(combine-words n)
(interpose "\n")
(flatten)
(apply str)))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment