print a value if it is not zero

2020-04-14 03:58发布

问题:

I need to print out a value if it is above zero:

info({mail, BoxPid, Messages, MessageCount, MessageDropCount}, Req, S) ->
    if MessageDropCount > 0 ->
            io:format("dropped=~p~n", [MessageDropCount]);
       true -> true
    end,
    ...,
    {loop, Req, S};

I do not like the true -> true part of the if expression. Is there a way to avoid it? Is there an idiom for that?

回答1:

The If Then page at the ErlangCentral wiki suggests these patterns:

  • [io:format("dropped=~p~n", [MessageDropCount]) || MessageDropCount > 0]
  • MessageDropCount > 0 andalso io:format("dropped=~p~n", [MessageDropCount])
  • MessageDropCount =< 0 orelse io:format("dropped=~p~n", [MessageDropCount])


回答2:

You ca use a function with pattern matching:

info({mail, BoxPid, Messages, MessageCount, MessageDropCount}, Req, S) ->
    printIfNotZero(MessageDropCount,"dropped=~p~n"),
    ...,
    {loop, Req, S};

...
printIfNotZero(0,_) -> ok;
printIfNotZero(C,M) -> io:format(M, [C]).

EDIT: a more general function could be the following:

info({mail, BoxPid, Messages, MessageCount, MessageDropCount}, Req, S) ->
    printCond(MessageDropCount =/= 0,"dropped=~p~n",[MessageDropCount]),
    ...,
    {loop, Req, S};

...
printCond(false,_,_) -> ok;
printCond(true,Format,Arglist) -> io:format(Format,Arglist).


标签: erlang