Ponder this:
<pre>
fact (0) ->
1;
fact (N) ->
N * fact (N - 1).
</pre>
versus this:
<pre>
fact(N) ->
fact_helper(N, 1).
fact_helper(1, T) ->
T;
fact_helper(N, T) ->
fact_helper(N - 1, T * N).
</pre>
The advantage of learning Erlang (albeit very slowly, with lots of interruptions) is that it directly introduces a lot of concepts I’ve been marginally aware of before. For instance, the second example implements factorial using tail recursion. The advantage is that a compiler doesn’t have to implement a call-stack when playing with arguments. See wikipedia entry.
Leave a Reply