Haskell: check string is correct

How to check decimal point when string check is a valid number?

I think I'm using something like the following, but adding code to check the decimal point!

isNumber :: String -> Bool
isNumber xs = all isDigit xs || add extra code here

If a real number is defined in the EBNF as:

number -> .digit+ | digit+ [ .digit*]

For example, .5, 1.5, 1, 1. all valid numbers. + means one or more occurrences, and * means zero or more.

+4
source share
3 answers

Here's a simple strategy:

  • Reset all numbers at the beginning of the line.
  • Now the remaining line should be either

    a) an empty string or

    b) a decimal point followed by all digits.

Almost. This will also match the empty string ""and ".", but we can treat them as special cases.

Haskell Translation:

isNumber :: String -> Bool
isNumber ""  = False
isNumber "." = False
isNumber xs  =
  case dropWhile isDigit xs of
    ""       -> True
    ('.':ys) -> all isDigit ys
    _        -> False
+8

readMaybe ,

import Text.Read

, Double,

readMaybe "123" :: Maybe Double
Just 123.0

readMaybe "12a3" :: Maybe Double
Nothing

Nothing, . , , Int,

readMaybe "12.3" :: Maybe Int
Nothing
+4

reads, :

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

, .

, True , Haskell, . , - Parsec, @CarstenKönig .

+3

All Articles