Erlang (programming language): Difference between revisions

Content deleted Content added
m fixed lint errors – stripped tags
Fibonacci sequence: copyedit comments and remove redundant rules from the shortened program
Line 133:
%% If fib/1 is passed an integer less than 3, then return 1
%% 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;
 
Line 144:
%% ---------------------------------------------------------------------
 
%% If fib_int/3 receives a 10 as its first argument, then we're done, so
%% return the value in argument BA. The Sincethird weargument areis notdenoted interested_ in theto
%% to disregard its value.
%% value of the second argument, we denote this using _ to indicate a
fib_int(10, _A, B_) -> BA;
%% "don't care" value
fib_int(1, _, B) -> B;
 
%% For all other argument combinations, recursively call fib_int/3
%% where each call does the following:
%% - decrement counter N
%% - Takepass the previous fibonacci value inthird argument Bas andthe passnew itsecond asargument
%% - pass the sum of the second and third arguments as the new
%% argumentthird Aargument
%% - Calculate the value of the current fibonacci number and pass it
%% as argument B
fib_int(N, A, B) -> fib_int(N-1, B, A+B).
</syntaxhighlight>
 
Omitting the comments, and redundant clauses that serve only to illustrate syntax, gives a much shorter program.
Here is the same program without the explanatory comments:
 
<syntaxhighlight lang="erlang">
Line 166 ⟶ 164:
-export([fib/1]).
 
fib(0) -> 0;
fib(N) when N < 0 -> err_neg_val;
fib(N) when N < 3 -> 1;
fib(N) -> fib_int(N, 0, 1).
 
fib_int(10, _A, B_) -> BA;
fib_int(N, A, B) -> fib_int(N-1, B, A+B).
</syntaxhighlight>