FizzBuzz (Erlang)

From LiteratePrograms

Jump to: navigation, search

FizzBuzz is a common exercise program, such as Hello, world! or 99 Bottles of Beer. It is based on a common game of the same name. The program prints a series of natural numbers, substituting those divisible by 3 with "Fizz", those divisible by 5 with "Buzz" and those divisible by both 3 and 5 with "FizzBuzz".

The interface to our Erlang implementation of FizzBuzz is a a single argument function called fizzbuzz. The fizzbuzz function will print FizzBuzz values for the first N natural numbers. The argument to the function specifies the value of N.


To implement FizzBuzz in Erlang, we use a tail-recursive loop. We'll need two variables: a loop counter and the maximum number of iterations. We initialize the loop counter to 1 (the first natural number), and set the maximum number of iterations to the value of N passed by the caller.

fizzbuzz(N) -> fizzbuzz(1, N).

The heart of our implementation is the fizzbuzz/2 function, which implements the tail-recursive loop. At each iteration, fizzbuzz/2 checks the current value of the loop counter I against the FizzBuzz rules, and prints a corresponding message.

fizzbuzz(I, N) when I =< N -> 
        I rem 15 =:= 0 -> io:format("FizzBuzz~n");
        I rem 3  =:= 0 -> io:format("Fizz~n");
        I rem 5  =:= 0 -> io:format("Buzz~n");
        true           -> io:format("~p~n", [ I ])
    fizzbuzz(I+1, N);

The tail-recursive loop halts when the loop counter is greater than the maximum number of iterations.

fizzbuzz(_, _) -> ok.
Download code
Personal tools