d-tb5a
Last Updated: February 25, 2016
·
715
· spiegela

Fizz Buzz in Erlang with tail recursion

I've seen several fizzbuzz implementations out there. Mine implements tail-recursion, which is a common (sometimes best) practice in erlang to improve the call-path for larger lists.

-module(fizzbuzz).
-compile(export_all).

run() ->
  run(lists:seq(1,100), []).

run([], Acc) ->
  lists:reverse(Acc);
run([H|T], Acc) ->
  run(T, [print_string(H)|Acc]).

print_string(X) when X rem 15 =:= 0 ->
  "FizzBuzz";
print_string(X) when X rem 3 =:= 0 ->
  "Fizz";
print_string(X) when X rem 5 =:= 0 ->
  "Buzz";
print_string(X) ->
  integer_to_list(X).

Enjoy!