Skip to content

Instantly share code, notes, and snippets.

@trung
Created November 6, 2009 08:17
Show Gist options
  • Save trung/227821 to your computer and use it in GitHub Desktop.
Save trung/227821 to your computer and use it in GitHub Desktop.
%% To demonstrate tail recursion in Erlang
-module (tailrecursion).
-export ([fact/1, qsort/1, loop/0]).
%% Factorial
fact(N) -> fact(N, 1).
fact(0, A) -> 1*A;
fact(N, A) -> fact(N-1, N*A).
%% Quick Sort
%% Think thru, you'll see it very easy to understand :p
qsort([]) -> [];
qsort([Single]) -> [Single];
qsort([Pivot|Rest]) ->
{Smallers, Greaters} = qsort(Pivot, Rest),
SortedSmallers = qsort(Smallers),
SortedGreaters = qsort(Greaters),
SortedSmallers ++ [Pivot] ++ SortedGreaters.
qsort(Pivot, List) -> qsort(Pivot, [], [], List).
qsort(_Pivot, Smallers, Greaters, []) -> {Smallers, Greaters};
qsort(Pivot, Smallers, Greaters, [First|Rest]) when First < Pivot ->
qsort(Pivot, [First|Smallers], Greaters, Rest);
qsort(Pivot, Smallers, Greaters, [First|Rest]) when First >= Pivot ->
qsort(Pivot, Smallers, [First|Greaters], Rest).
%% Loop
%% Just a sample, don't run!!!
loop() ->
receive
{status, ok} ->
loop()
end.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment