Skip to content

Instantly share code, notes, and snippets.

@theycallmeswift
Last active December 21, 2015 11:49
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save theycallmeswift/6301419 to your computer and use it in GitHub Desktop.
Save theycallmeswift/6301419 to your computer and use it in GitHub Desktop.
Fizzbuzz implemented in Erlang
%% DISCLAIMER: Please excuse my style, I don't write erlang.
-module(fizzbuzz).
-export([fizz_buzz/0]).
fizz_buzz() ->
fizz_buzz(1).
fizz_buzz(N) when N =< 100 ->
if
N rem 15 == 0 ->
io:format("fizzbuzz~n");
N rem 5 == 0 ->
io:format("buzz~n");
N rem 3 == 0 ->
io:format("fizz~n");
true ->
io:format("~p~n", [N])
end,
fizz_buzz(N + 1);
fizz_buzz(_) -> done.
%% DISCLAIMER: Please excuse my style, I don't write erlang.
-module(fizzbuzz).
-export([fizz_buzz/0]).
fizz_buzz() ->
fizz_buzz(1).
fizz_buzz(N) when N > 100 ->
done;
fizz_buzz(N) when N rem 15 == 0 ->
io:format("fizzbuzz~n"),
fizz_buzz(N + 1);
fizz_buzz(N) when N rem 5 == 0 ->
io:format("buzz~n"),
fizz_buzz(N + 1);
fizz_buzz(N) when N rem 3 == 0 ->
io:format("fizz~n"),
fizz_buzz(N + 1);
fizz_buzz(N) ->
io:format("~p~n", [N]),
fizz_buzz(N + 1).
@blt
Copy link

blt commented Aug 24, 2013

Hey, cool, you've got a pretty solid grasp of some fundamental concepts here and, more interestingly, have found a place where Erlang's if clause actually makes a ton of sense. Kudos!

Personally, I like the fizzbuz.erl more. I like that its more compact so you can see the causal relationship with side-effect and trigger closely and I like that there's less duplication overall; the recursion is so similar you lose out in the function-clause style--fizzbuz2.erl---simply because the density of the idea is much, much less than the bulk of the code.

Were fizz_buz/1 exposed to a public consumer I would suggest that you might add an is_integer/0 guard clause, but since that function is purely internal there's no reason to bother. I generally like to put my internal functions off behind a comment block: example

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment