99 Bottles of Beer (Erlang)

From LiteratePrograms

(Redirected from 99 Bottles of Beer (erlang))
Jump to: navigation, search
Other implementations: Alice ML | Erlang | Haskell | Inform 7 | Java | OCaml | Perl | Python | Ruby

The Implementation

As normal with erlang we use recursion to solve this problem.

<<program>>=
bottles(2) ->
    io:fwrite("Two bottles of beer on the wall,~nTwo bottles of beer!~n" ++
              "Take one down,~nPass it around,~nOne bottle of beer on the wall!~n~n", []),
    bottles(1).
bottles(1) ->
    io:fwrite("One bottle of beer on the wall,~nOne bottle of beer!~n" ++
              "Take it down,~nPass it around,~nNo more bottles of beer on the wall!~n", []),
    true;
bottles(N) when N > 1 ->
    io:fwrite("~p bottles of beer on the wall,~n~p bottles of beer!~n" ++
              "Take one down,~nPass it around,~n~p bottles of beer on the wall!~n~n", [N, N, N-1]),
    bottles(N - 1).

We are using escript to run this program. escript calls a function name main() with a list of command line arguments as the entry point. This in turn calls the recursive function bottles with the number of bottles (99) that we start with on the wall.

<<main>>=
main(_) ->
        bottles(99).

This snippet of code tells the shell script how to run this program. For most Linux computers this line will get the shell script to run the correct program.

<<header>>=
#!/usr/bin/env escript

To run this dowload the code and make NinetyNineBottles.sh executable and run it.

<<NinetyNineBottles.sh>>=
header
program
main
Views