Skip to content

Instantly share code, notes, and snippets.

@mylesmegyesi
Created November 23, 2011 22:17
Show Gist options
  • Save mylesmegyesi/1390092 to your computer and use it in GitHub Desktop.
Save mylesmegyesi/1390092 to your computer and use it in GitHub Desktop.
Bowling Kata in Clojure
(def STRIKE_SCORE 10)
(def SPARE_SCORE 10)
(def MAX_FRAMES 10)
(defn- max-frames? [frames]
(>= (count frames) MAX_FRAMES)
)
(defn- strike? [roll]
(= STRIKE_SCORE roll)
)
(defn- spare? [frame-score]
(= SPARE_SCORE frame-score)
)
(defn- second-roll [rolls]
(if-let [second-roll (second rolls)]
second-roll
0
)
)
(defn- first-roll [rolls]
(if-let [first-roll (first rolls)]
first-roll
0
)
)
(defn- next-two-rolls [rolls]
(+ (first-roll rolls) (second-roll rolls))
)
(defn- get-spare-frame-score [remaining-frames]
(+ SPARE_SCORE (first-roll remaining-frames))
)
(defn- get-strike-frame-score [remaining-frames]
(+ STRIKE_SCORE (next-two-rolls remaining-frames))
)
(defn rolls-to-frames [rolls]
(loop [rolls rolls frames []]
(if (or (empty? rolls) (max-frames? frames))
frames
(let [frame-score (next-two-rolls rolls)]
(cond
(strike? (first-roll rolls))
(let [remaining-rolls (rest rolls)]
(recur remaining-rolls (conj frames (get-strike-frame-score remaining-rolls)))
)
(spare? frame-score)
(let [remaining-rolls (rest (rest rolls))]
(recur remaining-rolls (conj frames (get-spare-frame-score remaining-rolls)))
)
:else
(let [remaining-rolls (rest (rest rolls))]
(recur remaining-rolls (conj frames frame-score))
)
)
)
)
)
)
(defn get-score [rolls]
(apply + (rolls-to-frames rolls))
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment