Erlang decorators

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

    After searching the Internet, I came across an article .

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

    Immediately give a link to Github.

    So, the difference between my project - the decorator can be passed parameters and the verbose option , thanks to which the tuple with the name of the function and a line in the file will be passed to the decorator with the 3rd argument.

    An example of use that uses both of these features (certainly 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 the topic whether it is necessary or not, I’ll just be glad if someone comes in handy ...

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

    Also popular now: