Created
June 10, 2014 11:19
-
-
Save gausby/7b31d00bea9e97cf416e to your computer and use it in GitHub Desktop.
Elixir Implementation of 99 Bottles of Beer on the Wall
This file contains hidden or 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
defmodule Bottles do | |
@moduledoc """ | |
Will print the lyrics for the song 99 bottles of beer on the wall. | |
See `Bottles.sing` and `Bottles.create_stream` for usage examples. | |
""" | |
@doc """ | |
`Bottles.sing`, given a number, will print the lyrics for that verse. | |
If it is given a range it will print all the verses between these | |
numbers. | |
Bottles.sing(99..0) |> IO.puts | |
For heavy drinking, please consider `Bottle.create_stream`. | |
""" | |
def sing(number) when is_integer(number), do: do_sing(number) | |
def sing(bottles..stop) when is_integer(stop) and stop >= 0 and is_integer(bottles) and bottles >= stop do | |
Enum.map(bottles..stop, &do_sing/1) | |
end | |
@doc """ | |
`create_stream` will create a stream map that sing the song in a lazy | |
manner. | |
Bottles.create_stream(1000..0) |> Enum.map(&IO.puts/1) | |
Use this option for heavy binge drinking sessions. | |
""" | |
def create_stream(bottles..stop) do | |
Stream.map(bottles..stop, &sing/1) | |
end | |
@doc false | |
defp do_sing(0), do: "No more bottles of beer on the wall, no more bottles of beer.\n#{do_take_beer(0)}" | |
defp do_sing(1), do: "1 bottle of beer on the wall, 1 bottle of beer.\n#{do_take_beer(1)}" | |
defp do_sing(n) when is_integer(n) and n > 0 do | |
"#{n} bottles of beer on the wall, #{n} bottles of beer.\n#{do_take_beer(n)}" | |
end | |
@doc false | |
defp do_take_beer(0), do: "Go to the store and buy some more, 99 bottles of beer on the wall.\n" | |
defp do_take_beer(1), do: "Take one down and pass it around, no more bottles of beer on the wall.\n" | |
defp do_take_beer(2), do: "Take one down and pass it around, 1 bottle of beer on the wall.\n" | |
defp do_take_beer(n) when is_integer(n) and n > 0 do | |
"Take one down and pass it around, #{n - 1} bottles of beer on the wall.\n" | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment