检查字符串是否包含 float 或 int

Checking if string contains float or int

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

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 异常,这是完全合适的。