2

如果它高于零,我需要打印出一个值:

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

我不喜欢表达的true -> true部分if。有没有办法避免它?有成语吗?

4

2 回答 2

3

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])
于 2013-10-18T09:39:49.440 回答
2

您可以使用具有模式匹配的函数:

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

编辑:更通用的功能可能如下:

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).
于 2013-10-18T03:46:50.133 回答