Skip to content

Instantly share code, notes, and snippets.

@nilsmartel
Created August 6, 2021 17:39
Show Gist options
  • Save nilsmartel/de2caaf27ab3ae9d02cfc41baf8c28d3 to your computer and use it in GitHub Desktop.
Save nilsmartel/de2caaf27ab3ae9d02cfc41baf8c28d3 to your computer and use it in GitHub Desktop.
(ns beer-song
(:require [clojure.string :as string]))
(require '[clojure.core.match :refer [match]])
;; 2 bottles of beer on the wall, 2 bottles of beer.
;; Take one down and pass it around, 1 bottle of beer on the wall.
;; 1 bottle of beer on the wall, 1 bottle of beer.
;; Take it down and pass it around, no more bottles of beer on the wall.
;; No more bottles of beer on the wall, no more bottles of beer.
;; Go to the store and buy some more, 99 bottles of beer on the wall.
(def part1 " of beer on the wall, ")
(def part2 " of beer.\n")
(def part3 " down and pass it around, ")
(def part4 " of beer on the wall.\n")
(defn verse
"Returns the nth verse of the song."
[num] (match num
0 (str "No more bottles" part1 "no more bottles" part2 "Go to the store and buy some more, 99 bottles" part4)
1 (str "1 bottle" part1 "1 bottle" part2 "Take it" part3 "no more bottles" part4)
n (str n " bottles" part1 n " bottles" part2 "Take one" part3 (- n 1) (if (= n 2) " bottle" " bottles") part4)
)
)
(defn sing
"Given a start and an optional end, returns all verses in this interval. If
end is not given, the whole song from start is sung."
([start] (sing start 0))
([start end] (string/join "\n" (map verse (reverse (range end (+ start 1))))))
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment