Parsing 检查字符串是否包含整数
此代码不起作用的原因:Parsing 检查字符串是否包含整数,parsing,haskell,Parsing,Haskell,此代码不起作用的原因: import IO import Char isInteger "" = False isInteger (a:b) = if length b == 0 && isDigit(a) == True then True else if isDigit(a) == True then isInteger(b) else False main = do q <- getLine let x = read q if
import IO
import Char
isInteger "" = False
isInteger (a:b) =
if length b == 0 && isDigit(a) == True then True
else if isDigit(a) == True then isInteger(b)
else False
main = do
q <- getLine
let x = read q
if isInteger x == False then putStrLn "not integer"
else putStrLn "integer"
导入IO
导入字符
isInteger”“=错误
isInteger(a:b)=
如果长度b==0&&isDigit(a)==True,则为True
否则,如果isDigit(a)==真,则isInteger(b)
否则错误
main=do
q这将起作用:
main = do
q <- getLine -- q is already String - we don't need to parse it
if isInteger q == False then putStrLn "not integer"
else putStrLn "integer"
PS这并不是说你不能解析字符串(虽然这样做仍然没有意义),你可以,但是输入应该不同:String
只是Char
的列表,即使Show
threats[Char]
作为特例Read
没有,因此,为了读取字符串
只需将其作为列表传递:
Prelude> read "['4','2']" :: String
"42"
如果您向我们提供错误消息,则会对我们有所帮助:
/home/dave/tmp/so.hs:14:4:
parse error (possibly incorrect indentation)
Failed, modules loaded: none.
第14行是else putStrLn“整数”
这与缩进有关的提示是正确的。使用if-then-else和do表示法时,需要确保多行表达式——以及if-then-else是单个表达式——在第一行之后有额外的缩进
(在isInteger
函数中不使用do符号,这就是为什么相同的if-then-else缩进不会导致出现问题的原因。)
所以这没有编译错误:
main = do
q <- getLine
let x = read q
if isInteger x == False then putStrLn "not integer"
else putStrLn "integer"
main=do
qisInteger s=not(null s)和&all-isDigit s
:-)还要注意x==True
与x
是一样的(==True)
是标识函数。因此,例如,第一行可以是,如果长度b==0&&isDigit a,则为True
。但是你仍然在努力工作:-)哇-非常有趣的解决方案,非常感谢你:)@luqui为什么没有(空的s)
必要?@Rein,因为all-isDigit”“
是空的,但它不是整数(读
不会解析它)。这会伤害眼睛:如果某个东西==False,那么B另一个A
。更好的方法是:如果某个东西是另一个B
。或者至少使用而不是==False
main = do
q <- getLine
let x = read q
if isInteger x == False then putStrLn "not integer"
else putStrLn "integer"
main = do
q <- getLine
let x = read q
if isInteger x == False
then putStrLn "not integer"
else putStrLn "integer"