The kid's travel song about sharing beer exposes lots of awkwardness in many programming languages. Learn how it is written in your language to get past these bumps.
The song counts backwards, like Count Down.
The song substitutes parameters into strings, like Concatenating strings.
The song has the special case of singular vs. plural, like Case Analysis.
The last three verses would be as follows.
3 bottles of beer on the wall 3 bottles of beer take one down, pass it around 2 bottles of beer on the wall 2 bottles of beer on the wall 2 bottles of beer take one down, pass it around 1 bottle of beer on the wall 1 bottle of beer on the wall 1 bottle of beer take one down, pass it around 0 bottles of beer on the wall
We offer this solution in CoffeeScript .
plural = (n,s) -> if n==1 then s else "#{s}s" beers = (n) -> "#{n} #{plural n, 'bottle'} of beer" wall = (n) -> "#{beers n} on the wall" take = -> "take one down, pass it around" verse = (n) -> [wall(n), beers(n), take(), wall(n-1)] console.log verse(n).join("\n"),"\n" for n in [99..1]
In CoffeeScript (n)-> creates a function with argument n while #{n} substitutes the value of n into a string.
We define a function for each variation of string. A verse is an array of these, ready to be joined with punctuation. The result is logged to the console for each of the 99 verses.
References
See more examples in many languages.
We recreate the calculation refactoring example, the 99 bottles of beer song, from the open source conference and invite viewers to try it themselves.