如果值高于零,我需要打印出一个值:
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
部分。有没有办法避免它?那有成语吗?
答案 0 :(得分:3)
If Then page at the ErlangCentral wiki表明了这些模式:
[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])
答案 1 :(得分: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).