我需要编写erlang函数,该函数接受一个字符串,然后在字符串包含浮点数或整数的情况下执行不同的操作。我曾考虑过使用string:to_float和string:to_integer,但是我想知道是否可以在模式匹配中使用它们来匹配不同的子句,或者是否需要使用ifs来检查一个子句。
答案 0 :(得分:3)
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
异常,这是完全适当的。