做块的条件

时间:2013-03-16 13:22:36

标签: haskell io

为什么以下代码块:

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

工作正常吗?

1 个答案:

答案 0 :(得分: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_Counts分支添加else