我想使用 Erlang 来确定传递给函数的变量是否可以被数字整除。我考虑过使用 case
来执行此操作,但是我找不到解决方案。 case
是适合这项工作的工具吗?
示例:将数字传递给函数 f()。如果该数字能被 10 整除,则打印一条语句。如果它能被 15 整除,则打印不同的语句。如果它能被 5 整除,我想我想打印第三条语句,但不是“能被 10 整除”或“能被 15 整除”的语句,因为这个案例已经被处理了。
我的直觉告诉我 case
适合这项工作,但我是 Erlang 新手,很难将其拼凑在一起。
最佳答案
您可以在函数子句上使用防护来做到这一点:
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 中通常被认为是良好的风格:如果您的函数无法对错误的输入执行任何明智的操作,那么最好让它崩溃并让调用者处理错误而不是通过在每个级别处理错误来使代码复杂化。当然,这取决于您的具体要求。
关于Erlang 切换(大小写)整除性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35505770/