【问题标题】:Checking if string contains float or int检查字符串是否包含浮点数或整数
【发布时间】:2020-06-27 01:58:06
【问题描述】:

我需要编写 erlang 函数,它接受一个字符串,然后如果字符串包含浮点数或整数,则执行不同的操作。我曾想过使用 string:to_float 和 string:to_integer,但我想知道是否可以在模式匹配中使用它们来匹配不同的子句,或者我是否需要使用 ifs 来检查一个子句。

【问题讨论】:

    标签: functional-programming erlang pattern-matching


    【解决方案1】:

    Erlang 模式匹配不是解决这个问题的好方法,因为必须处理各种各样的数字表示。你最好尝试string-to-number conversion,然后使用守卫将浮点数与整数分开:

    float_or_integer(F) when is_float(F) -> float;
    float_or_integer(I) when is_integer(I) -> integer;
    float_or_integer(L) ->
        Number = try list_to_float(L)
                 catch
                     error:badarg -> list_to_integer(L)
                 end,
        float_or_integer(Number).
    

    将前两个函数的主体替换为特定于您正在解决的问题的逻辑。

    如果你传递一个转换失败的参数,你会得到一个badarg 异常,这是完全合适的。

    【讨论】:

    • 感谢您的回答。我发现它很有帮助。
    猜你喜欢
    • 1970-01-01
    • 2011-03-23
    • 1970-01-01
    • 2018-03-20
    • 1970-01-01
    • 2016-05-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多