Haskell:检查字符串是否是有效的数字 [英] Haskell: check if string is valid number

查看:233
本文介绍了Haskell:检查字符串是否是有效的数字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在检查字符串时检查小数点是否是有效数字?



我在想的是我使用类似下面的内容,但添加代码检查小数点!

  isNumber :: String  - > Bool 
isNumber xs = all isDigit xs ||在这里添加额外的代码

在EBNF中定义的有效数字为:

 数字 - > .digit + |数字+ [.digit *] 

例如,.5,1.5,1,1都是有效的数字。 +
表示一个或多个匹配项,*表示零个或多个匹配项。

解决方案

这里有一个简单的策略: p>


  1. 删除字符串开头的所有数字。

  2. 剩余的字符串应该现在是

    a)空字符串,或者

    小数点后跟所有数字。


好的,差不多。这也会匹配空字符串,但我们可以将它们视为特殊情况。 p>

转换为Haskell:

  isNumber :: String  - > Bool 
isNumber= False
isNumber。 = False
isNumber xs =
case dropWhile isDigit xs of
- > True
('。':ys) - > all isDigit ys
_ - >假


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 the decimal point!

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

Where a valid number is defined in EBNF as:

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

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

解决方案

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

这篇关于Haskell:检查字符串是否是有效的数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆