Wednesday, September 26, 2007

Understand your implementation by "tracing" the execution

In my previous post, i used Erlang to implement 2 simple algorithms when run, produced the desired results which i am pleased. But, upon reflection i found that i need to better my understanding of how Erlang executes the function i knew i needed to trace it.

Therefore, how do you add "debug/trace" feature into your own implementations ?

What i did is:

1/ Create a macro named "TRACE"
2/ Compiled the code using the "c"-command with an extra argument
3/ Ran the compiled code to view it, and voila! its done.

Below is an illustration of how i did it:


%
% Create a Erlang macro and include it in your *.erl file
%
-ifdef(debug).
-define(TRACE(X), io:format("TRACE ~p:~p ~p~n", [?MODULE, ?LINE, X])).
-else.
-define(TRACE(X), void).
-endif.
...
...
...
%
% N-th Permutation
% Note: the code in "bold" is an expansion of the newly created macro "TRACE"
%
perms([]) -> [[]];
perms(L) -> ?TRACE(L), [[H|T] || H <- L, T <- perms(L--[H])]. ... ...


Now, once you have done this naturally you would save the file and next you start up the Erlang shell and compile the file as illustrated in the screenshot below, afterwhich you run it!

No comments: