📜 ⬆️ ⬇️

Erlang decorators

Sometimes Erlang lacks this interesting feature, so I wanted to get hold of this feature.

Searching across the expanses of the Internet came across an article .

The author has almost completely implemented all the functionality except for passing arguments to the decorator.

Immediately give a link to Github.
')
So, the difference between my project - the decorator can be passed the parameters and the verbose option, thanks to which a tuple with the name of the function and a string in the file will be passed to the decorator as the 3rd argument.

An example of use that uses both of these features (of course not production, but the essence should be clear).

-module(memoize). % This row is required for decorators -compile([{parse_transform,decorators}]). % exporting decorator function -export([memoize/4]). % api exports -export([fact/1]). % pretty decorator usage -define(MEMOIZE, -decorate({?MODULE,memoize,[?MODULE],verbose})). memoize(F,Args,{FunName,_Line},Module)-> case ets:info(memoize) of undefined -> ets:new(memoize,[public,named_table]); _-> ok end, case ets:lookup(memoize,{Module,FunName,Args}) of [] -> R = apply(F,[Args]), ets:insert(memoize,{{Module,FunName,Args},R}), R; [{_,Value}] -> Value end. ?MEMOIZE. % decorator fact(N) when is_integer(N) andalso N>=1 -> fact(N,1). fact(1,Acc) -> Acc; fact(N,Acc) -> fact(N-1,Acc*N). 


Well, the test of 2 calls:

 >> timer:tc(memoize,fact,[1000]). {1282, ... }. >> timer:tc(memoize,fact,[1000]). {9, ... }. 


Those. the increase is noticeable :)

I don’t want to breed a holivar on whether it’s necessary or not, I’ll just be happy if someone comes in handy ...

PS
If anyone is interested, I can further fully describe the whole process of code generation through parse_transform ...

Source: https://habr.com/ru/post/146495/


All Articles