For reasons passing comprehension, my corner of Twitter was touched briefly yesterday by a discussion of the interview process and FizzBuzz.

Whether using FizzBuzz is a useful tool or an admission of defeat I leave to others, but I thought it’d be fun to play with the problem in Erlang.

Problem description

Here’s the example problem:

Write a program that prints the numbers from 1 to 100. But for multiples of three print“Fizz” instead of the number and for the multiples of five print“Buzz”. For numbers which are multiples of both three and five print“FizzBuzz”.

Pretty boring, and hopefully anyone reading this could solve this in their sleep, but even simple problems take on a different flavor when tackled using Erlang and pattern matching.

I wanted to extend it a bit so that instead of hard-coding 3, 5,“Fizz” and“Buzz” as values, they could be passed as arguments.

Pass, the first

fizzbuzz() ->
fizzbuzz(1, 100, { 3, "Fizz" }, { 5, "Buzz" }).

I’ve now turned everything into a parameter.

Base case:

fizzbuzz(N, End, _, _) when N > End ->
ok;

Simple enough. Let’s tackle the“FizzBuzz” case next, where N is a multiple of both 3 and 5.

Note that the arguments are now a list, and we pass two copies of it into the“real” function definitions so that after we work our way down the list of parameters when evaluating one value of N, we’ll have another copy of the original list for the next N value.

This time we don’t have the same pattern matching flexibility since we can’t use arbitrary nested list elements in guard operations.