Haskell: check if string is valid number

前端 未结 3 431
慢半拍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: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.

提交回复
热议问题