Last active
August 29, 2015 14:10
-
-
Save ddellacosta/ba7e03951ba1bafd3ec9 to your computer and use it in GitHub Desktop.
Diamond kata -- done via "RDD" (http://blog.jayfields.com/2014/01/repl-driven-development.html) vs. TDD
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 diamond.core) | |
(def alphabet "ABCDEFGHIJKLMNOPQRSTUVWXYZ") | |
(defn append-end | |
"Takes a diamond string and appends the reverse of the string minus | |
first char, so i.e. ---A becomes ---A---, D--- becomes D-----D, etc." | |
[s] | |
(str s (apply str (reverse (butlast s))))) | |
(defn diamond-start | |
"Using length len to determine length of string and idx to determine inverse position | |
of alpha char, creates the beginning of the diamond string, like | |
---A, --B-, -C--, D---, etc." | |
[len idx alpha] | |
(str (apply str (take (- (dec len) idx) (repeat "-"))) | |
(get alpha idx) | |
(apply str (take idx (repeat "-"))))) | |
(defn diamond-str-fn | |
"Returns closure over string length len which calculates correct diamond string | |
per reduce iteration and appends to line sequence: | |
['---A---' '--B-B--' (...etc.) ]" | |
[len alpha] | |
(fn [lines idx] (->> (diamond-start len idx alpha) append-end (conj lines)))) | |
(defn diamond | |
"Generates vector of diamond strings. Takes integer length len and alphabet string alpha." | |
[len alpha] | |
(assert (<= len 26)) | |
(let [seqn (reduce (diamond-str-fn len alpha) [] (range 0 len))] | |
(concat seqn (reverse (butlast seqn))))) | |
(defn print-diamond | |
"Simple utility to print seq of diamond strings." | |
[dseq] | |
(doseq [line dseq] (println line))) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Haskell version here for fun.
Edit: a few comments based on observations comparing the Haskell and Clojure versions.
This could simply be because I structured the Clojure version above poorly, but I realize that in some cases I tended to split off functions more when they became hard to read vs. when it seemed logically meaningful to do so.
It's also fair to point out that I spent more time re-factoring the Clojure version, and had a better idea of the algorithm I would use before I wrote the Haskell version.