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).

    % This row is required for decorators
    % exporting decorator function
    % api exports
    % pretty decorator usage
    -define(MEMOIZE, -decorate({?MODULE,memoize,[?MODULE],verbose})).
        case ets:info(memoize) of
            undefined ->
        case ets:lookup(memoize,{Module,FunName,Args}) of
            [] ->
                R = apply(F,[Args]),
            [{_,Value}] ->
    ?MEMOIZE. % decorator
    fact(N) when is_integer(N) andalso 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]).
      ... }.
    >> timer:tc(memoize,fact,[1000]).
      ... }.

    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 ...

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

    Also popular now: