print a value if it is not zero

2020-04-14 03:28发布

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?

标签: erlang
2条回答
啃猪蹄的小仙女
2楼-- · 2020-04-14 03:59

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])
查看更多
霸刀☆藐视天下
3楼-- · 2020-04-14 04:09

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).
查看更多
登录 后发表回答