Haskell: check if string is valid number

前端 未结 3 433
慢半拍i
慢半拍i 2021-01-11 16:48

How do I check for a decimal point when checking a string is a valid number?

What I am thinking is that I use something like the following, but add code to check for

相关标签:
3条回答
  • 2021-01-11 17:30

    Here's a simple strategy:

    1. Strip off all the digits at the beginning of the string.
    2. The remaining string should now be either

      a) the empty string, or

      b) a decimal point followed by all digits.

    Well, almost. This would also match the empty string "" and "." but we can treat those as special cases.

    Translated to Haskell:

    isNumber :: String -> Bool
    isNumber ""  = False
    isNumber "." = False
    isNumber xs  =
      case dropWhile isDigit xs of
        ""       -> True
        ('.':ys) -> all isDigit ys
        _        -> False
    
    0 讨论(0)
  • 2021-01-11 17:43

    A simple approach involves using readMaybe for converting a string into a number,

    import Text.Read
    

    and so for checking whether it is a Double,

    readMaybe "123" :: Maybe Double
    Just 123.0
    
    readMaybe "12a3" :: Maybe Double
    Nothing
    

    The latter returns Nothing, the string is not a valid number. In a similar fashion, if we assume it is an Int,

    readMaybe "12.3" :: Maybe Int
    Nothing
    
    0 讨论(0)
  • 2021-01-11 17:44

    Take a look at reads, then:

    isNumber :: String -> Bool
    isNumber str =
        case (reads str) :: [(Double, String)] of
          [(_, "")] -> True
          _         -> False
    

    Maybe there is a better way, though.

    Note that this will return True for numbers that are considered valid in Haskell, your particular use case is not fully covered by this. If you need custom parsing according to your specification you should use something like Parsec, as @CarstenKönig has suggested in his comment.

    0 讨论(0)
提交回复
热议问题