Tail Recursion

Ponder this:

fact (0) ->
	1;
fact (N) ->
	N * fact (N - 1).

versus this:

fact(N) ->
	fact_helper(N, 1).
fact_helper(1, T) ->
	T;
fact_helper(N, T) ->
	fact_helper(N - 1, T * N).

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.

One Reply to “Tail Recursion”

  1. Pingback: Xanax cocktail.

Leave a Comment

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s