Exercise 7-7

109 views
Skip to first unread message

Erlcoder

unread,
Aug 28, 2010, 11:22:09 AM8/28/10
to Erlang Programming
Using the erlang macro facility to count the number of calls to a
particular function in a particular module... This may be really
simple and I'm thinking of it the wrong way, but how would one do
this?

I assume they're talking about something more than just calling the
following macro every time you call a particular function, right?

-define(COUNT(N), N+1).

Rudolph Gatt

unread,
Aug 28, 2010, 1:26:25 PM8/28/10
to Erlang Programming
Hi, macros are quite new for me. I was reading that I can get the
module name by using the predefined macro ?MODULE. Can someone tell we
whether there is a predefined macro which gives the function name,
instead of the module name? If there isn't a predefined macro can
someone give me some tips of how to define such macro?

Thanks in advance

Yoshihiro Tanaka

unread,
Aug 29, 2010, 3:44:30 AM8/29/10
to erlang-prog...@googlegroups.com
Hello,

I think there is no predefined function macro. But you can use
parse_transform/2 instead. Here is my try:


-module(cm_).
-export([parse_transform/2]).

parse_transform(ASTs, _Options) -> [parse_cm(T) || T <- ASTs].

parse_cm({function, _, FuncName, _, _} = T) ->
{FuncName, _} = erl_syntax_lib:analyze_function(T),
erl_syntax_lib:map(
fun(Node) ->
erl_syntax:revert(
case erl_syntax:is_atom(Node, cm_FUNC) of
true -> erl_syntax:atom(FuncName);
false -> Node
end
)
end, T);
parse_cm(T) -> T.


Then, you can use it like below using -compile directive:
-module(test).
-compile([export_all]).
-compile({parse_transform, cm_}).

macro_test() -> lists:foreach(fun(X) -> X end,
[ custom_macro1(), custom_macro2(), custom_macro3()] ).

custom_macro1() ->
io:format("Module:~p Function:~p~n", [?MODULE, cm_FUNC]).
custom_macro2() ->
io:format("Module:~p Function:~p~n", [?MODULE, cm_FUNC]).
custom_macro3() ->
io:format("Module:~p Function:~p~n", [?MODULE, cm_FUNC]).


I haven't tested it throughly, so it might not work in some cases.
--
Yoshi

> --
> Erlang Programming Website:
> http://www.erlangprogramming.org/

Yoshi

unread,
Aug 29, 2010, 4:50:14 AM8/29/10
to Erlang Programming
I guess so. For example, this might be idiomatic, but I came up using
process dictionary like following:

-module(test).
-compile([export_all]).
-compile({parse_transform, cm_}).
-define(Key, list_to_atom(atom_to_list(?MODULE) ++
atom_to_list(cm_FUNC))).
-define(COUNT_CALL(ModFunc), (put( ModFunc, (case get(ModFunc) of
undefined -> 1; N -> N + 1 end)))).

custom_macro1() ->
?COUNT_CALL(?Key),
io:format("Module:~p Function:~p~n", [?MODULE, cm_FUNC]).

Then you can check how many times custom_macro1/0 function in test
module was called using get(testcustom_macro1).

--
Yoshi
Reply all
Reply to author
Forward
0 new messages