2011-04-17 15 views
0

爲什麼這個代碼不工作:檢查字符串是否持有整數

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" 
+3

'isInteger s = not(null s)&& all isDigit s' :-) – luqui 2011-04-17 08:45:30

+2

另請注意,'x == True'和'x'是一樣的。 '(== True)'是身份函數。所以例如。第一行可以是'如果長度b == 0 && isDigit a then True'。但是......你仍然在努力工作:-) – luqui 2011-04-17 08:47:14

+0

哇 - 非常有趣的解決方案,非常感謝你:) – mrquestion 2011-04-17 09:13:45

回答

2

這將工作:

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" 

原因在運行時錯誤「Prelude.read你的代碼的結果:沒有解析「是因爲getLine :: IO StringisInteger :: String -> Bool,表達式let x = read x將嘗試將String解析爲String。自己嘗試一下:

Prelude> read "42" :: String 
"*** Exception: Prelude.read: no parse 

PS這並不是說你不能解析字符串(儘管它仍然沒有真正意義上做到這一點),你可以,但輸入應該是不同的:String只是一個的Char並且即使Show威脅列表[Char]作爲特殊情況Read沒有,所以爲了readString只是把它作爲一個清單:

Prelude> read "['4','2']" :: String 
"42" 
+0

不幸的是它仍然不起作用:( – mrquestion 2011-04-17 09:16:05

+0

哦,我知道 - '其他'應該在'然後'下面:)大聲笑:) – mrquestion 2011-04-17 10:00:05

0

它可以幫助我們,如果你給我們的錯誤消息:

/home/dave/tmp/so.hs:14:4: 
    parse error (possibly incorrect indentation) 
Failed, modules loaded: none. 

線14 else putStrLn "integer"

的提示,這是與縮進做是正確的。當你使用if-then-else和do-notation時,你需要確保多行表達式---和if-then-else是單個表達式---在第一行之後有額外的縮進。

所以這個沒有編譯錯誤(你不會在你的isInteger功能,這就是爲什麼IF-THEN-ELSE不會導致問題有相同的縮進用做表示法)

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" 

然後,您仍然有問題Ed'ka指出。但至少它編譯。

+2

它傷害了眼睛:'如果某事==假然後B別A'。更好:「如果某件事是別的B」。 – Ingo 2011-04-17 10:17:09

+0

或者至少使用'not'而不是'== False' – 2011-04-17 17:30:59