Checking if string contains float or int

Viewed 71

I need to write erlang function which takes in a string and then does different things if the string contains a float or an integer. I have thought of using string:to_float and string:to_integer, but I wonder if it's possible to use those in pattern-matching to match differen clauses or whether or not I need to use ifs to make the checking in one clause.

1 Answers

Erlang pattern matching is not a good approach to solving this problem due to the wide variety of number representations that would have to be handled. You're better off attempting a string-to-number conversion and then using guards to separate floats from integers:

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).

Replace the bodies of the first two functions with logic specific to the problem you're solving.

If you pass an argument that fails conversion, you'll get a badarg exception, which is entirely appropriate.

Related