你可以在你的函数使用的条款卫士做到这一点:
f(N) when N rem 10 =:= 0 ->
io:format("divisible by 10~n");
f(N) when N rem 15 =:= 0 ->
io:format("divisible by 15~n");
f(N) when N rem 5 =:= 0 ->
io:format("divisible by 5~n").
或者你可以用if
表达做到这一点:
f(N) ->
if N rem 10 =:= 0 ->
io:format("divisible by 10~n");
N rem 15 =:= 0 ->
io:format("divisible by 15~n");
N rem 5 =:= 0 ->
io:format("divisible by 5~n")
end.
如果你从别的地方获得的数量,使用case
表达式可能更自然:
f() ->
case get_number() of
N when N rem 10 =:= 0 ->
io:format("divisible by 10~n");
N when N rem 15 =:= 0 ->
io:format("divisible by 15~n");
N when N rem 5 =:= 0 ->
io:format("divisible by 5~n")
end.
请注意,如果数字不能被5整除,所有这些表达式都会崩溃。这在Erlang中通常被认为是很好的风格:如果你的函数不能做任何合理的输入错误,最好让它崩溃并让调用者处理错误比在每个级别上处理错误使代码复杂化。当然,这取决于您的具体要求。
如果您正在寻找类似fizzbuzz的东西,请参阅[此答案](http://stackoverflow.com/a/3249892)。 –