Factorial in Erlang

Example for versions erl 5.7.3

This example uses recursive factorial definition. Note that Erlang has no built-in loops, so the example uses a recursive function which starts with larger values of N, but calls itself for N-1 before printing N!. loop(_) is a clause that defines evaluation of loop() when its argument is not an integer or is negative; it is necessary for a proper function definition.

-module(prog).
 
-export([main/0, loop/1]).
 
fact(0) -> 1;
fact(N) -> N * fact(N-1). 
 
loop(N) when is_integer(N), N>=0 -> 
    loop(N-1),
    io:format("~B! = ~B~n",[N,fact(N)]);
loop(_) -> ok.
 
main() -> loop(16).