3

Why does the following block of code:

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

throw an error:

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 }

Even though both:

main = do
    runTestTT tests

and

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

work fine?

4

1 回答 1

9

an 的两个分支if then else必须具有相同的类型,但

runTestTT tests :: IO Counts

print $ process seq :: IO ()

您可以将 a 添加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分支)。

于 2013-03-16T13:25:37.237 回答