Skip to content

Instantly share code, notes, and snippets.

@jlouis
Created July 17, 2010 15:11
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jlouis/479566 to your computer and use it in GitHub Desktop.
Save jlouis/479566 to your computer and use it in GitHub Desktop.
%% Naive factorial, not tail recursive
%% (caveat, not tested)
fac(0) -> 1;
fac(N) when is_integer(N), N > 0 ->
RecCall = fac(N-1), %% The recursive call is not the last thing that happens
RecCall * N. % This is the last thing that happens
%% Tail recursive variant:
tfac(N) -> tfac(N, 1).
tfac(0, Acc) -> Acc;
tfac(N, Acc) when is_integer(N), N > 0 ->
tfac(N-1, Acc * N). %% Here the call is tail recursive.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment