Skip to content

Instantly share code, notes, and snippets.

@fabian
Created May 14, 2011 13:43
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 fabian/972221 to your computer and use it in GitHub Desktop.
Save fabian/972221 to your computer and use it in GitHub Desktop.
Implementation of factorial with primitive recursive function in Erlang
#!/usr/bin/env escript
-module(factorial).
-export([fac/1]).
%% Successor
succ(X) -> X + 1.
%% Addition
add(0, Y) -> Y;
add(X, Y) -> succ(add(X - 1, Y)). % add(X + 1, Y) -> succ(add(X, Y))
%% Multiplication
mult(0, _) -> 0;
mult(X, Y) -> add(mult(X - 1, Y), Y). % mult(X + 1, Y) -> add(mult(X, Y), Y)
%% Factorial
fac(0) -> 1;
fac(X) -> mult(X, fac(X - 1)). % fac(X + 1) -> mult(fac(X), X)
main(_) ->
io:fwrite("!0 = ~w~n", [fac(0)]),
io:fwrite("!3 = ~w~n", [fac(3)]),
io:fwrite("!5 = ~w~n", [fac(5)]).
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment