Skip to content

Instantly share code, notes, and snippets.

@jepio
Last active August 29, 2015 14:02
Show Gist options
  • Save jepio/f5c024e5847acd3db206 to your computer and use it in GitHub Desktop.
Save jepio/f5c024e5847acd3db206 to your computer and use it in GitHub Desktop.
Rev(erse) a list. erse ends up appending all elements once it gets to the end, while erse_tail will reverse as it goes.
-module(rev).
-export([start/0,erse/1,erse_tail/1]).
%% recursion with appending
erse([First|Rest]) -> erse(Rest)++[First];
erse([]) -> [].
%% tail recursion
erse_tail(L) -> erse_tail(L,[]).
erse_tail([],New) -> New;
erse_tail([H|T],New) -> erse_tail(T,[H|New]).
%% test
start() ->
N = 10000,
List = lists:seq(1,N),
{Time,_} = timer:tc(rev,erse,[List]),
{Time2,_} = timer:tc(rev,erse_tail,[List]),
%% using the built-in function
{Time3,_} = timer:tc(lists,reverse,[List]),
io:format("Appending ~p ms~n",[Time/1000]),
io:format("Tail recursion ~p ms~n",[Time2/1000]),
io:format("BIF ~p ms~n",[Time3/1000]).
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment