2013-03-16 48 views
3

爲什麼下面的代碼塊:條件在做阻擋

main = do 
    line <- getLine 
    if null line 
     then runTestTT tests 
     else do 
      line2 <- getLine 
      seq::[Int] <- return $ map read $ words line2 
      print $ process seq 

拋出一個錯誤:

lgis.hs:28:13: 
    Couldn't match type `()' with `Counts' 
    Expected type: IO Counts 
     Actual type: IO() 
    In a stmt of a 'do' block: print $ process seq 
    In the expression: 
     do { line2 <- getLine; 
      seq :: [Int] <- return $ map read $ words line2; 
      print $ process seq } 
    In a stmt of a 'do' block: 
     if null line then 
      runTestTT tests 
     else 
      do { line2 <- getLine; 
       seq :: [Int] <- return $ map read $ words line2; 
       print $ process seq } 

儘管兩個:

main = do 
    runTestTT tests 

main = do 
    line <- getLine 
    line2 <- getLine 
    seq::[Int] <- return $ map read $ words line2 
    print $ process seq 

工作正常嗎?

回答

9

if then else的兩個分支必須具有相同的類型,但

runTestTT tests :: IO Counts 

print $ process seq :: IO() 

您可以添加一個return()then科,現代的方式來做到這一點是使用Control.Monad.void

main = do 
    line <- getLine 
    if null line 
     then void (runTestTT tests)   -- formerly: runTestTT tests >> return() 
     else do 
      line2 <- getLine 
      seq::[Int] <- return $ map read $ words line2 
      print $ process seq 

來修復它(或者你可以添加一個return some_value_of_type_Countselse分支)。

+0

這是'void'的用途:'then void(runTestTT tests)' – 2014-06-10 21:14:33

+0

True。感謝提醒,我還沒有習慣所有新的便利功能。 – 2014-06-10 21:33:51

+0

有沒有什麼方法可以使類似'>>'的操作符足夠多態來處理這個問題? 'a >> b'不關心'a'產生的類型;我自然會認爲這是一種存在量化的類型,但我不知道Haskell(或格拉斯哥Haskell)是否有正確的類型。 – dfeuer 2014-06-10 23:33:37