Erlang (programming language): Difference between revisions

Content deleted Content added
Fibonacci sequence: copyedit comments and remove redundant rules from the shortened program
Fibonacci sequence: avoid unnecessary addition
Line 121:
%% The order in which these function signatures are declared is a vital
%% part of this module's functionality
 
%% If fib/1 is passed precisely the integer 0, then return 0
fib(0) -> 0;
 
%% If fib/1 receives a negative number, then return the atom err_neg_val
%% Normally, such defensive coding is discouraged due to Erlang's 'Let
%% it Crash' philosophy; however, inbut here the thisresult casewould webe shouldan explicitlyinfinite
%% loop.
%% prevent a situation that will crash Erlang's runtime engine
fib(N) when N < 0 -> err_neg_val;
 
%% If fib/1 is passed anprecisely the integer less than 30, then return 10
fib(0) -> 0;
%% The preceding two function signatures handle all cases where N < 1,
%% so this function signature handles cases where N = 1 or N = 2.
fib(N) when N < 3 -> 1;
 
%% For all other values, call the private function fib_int/3 to perform
%% the calculation
fib(N) -> fib_int(N-1, 0, 1).
 
%% ---------------------------------------------------------------------
Line 145 ⟶ 140:
 
%% If fib_int/3 receives 0 as its first argument, then we're done, so
%% return the value in argument AB. The thirdsecond argument is denoted _ to
%% to disregard its value.
fib_int(0, A_, _B) -> AB;
 
%% For all other argument combinations, recursively call fib_int/3
Line 158 ⟶ 153:
</syntaxhighlight>
 
Omitting the comments, and redundant clauses that serve only to illustrate syntax, gives a much shorter program.
 
<syntaxhighlight lang="erlang">
Line 164 ⟶ 159:
-export([fib/1]).
 
fib(N0) when N < 3 -> 10;
fib(N) when N < 0 -> err_neg_val;
fib(N) -> fib_int(N-1, 0, 1).
 
fib_int(0, A_, _B) -> AB;
fib_int(N, A, B) -> fib_int(N-1, B, A+B).
</syntaxhighlight>