问题描述
如何在检查字符串时检查小数点是否是有效数字?
我在想的是我使用类似下面的内容,但添加代码检查小数点!
isNumber :: String - > Bool
isNumber xs = all isDigit xs ||在这里添加额外的代码
在EBNF中定义的有效数字为:
数字 - > .digit + |数字+ [.digit *]
例如,.5,1.5,1,1都是有效的数字。 +
表示一个或多个匹配项,*表示零个或多个匹配项。
这里有一个简单的策略: p>
- 删除字符串开头的所有数字。
-
剩余的字符串应该现在是
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:
- Strip off all the digits at the beginning of the string.
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:检查字符串是否是有效的数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!