Erlang 切换(大小写)整除性

标签 erlang

我想使用 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/

相关文章:

erlang - 如何查看在后台运行的 Erlang 应用程序控制台?

erlang - 可搜索的离线 Erlang 文档?

import - 为什么 Erlang 既为模块提供 `import`,又为 header 提供 `include`?

timer - 如何以精确时间(即 10 毫秒)定期运行 Erlang 进程

erlang - 如何为使用 rebar 运行测试的 common_test 指定配置文件

ios - MUCLight 离线消息获取 XMPP

erlang - Mnesia - 指定存储策略时因 bad_type 中止

erlang - 我如何知道 elixir 的 CPU 中的内核数量?

erlang - 钢筋外壳 - 传递配置文件