做块的条件

vir*_*tor 3 io haskell

为什么以下代码块:

main = do
    line <- getLine
    if null line
        then runTestTT tests
        else do
            line2 <- getLine
            seq::[Int] <- return $ map read $ words line2
            print $ process seq
Run Code Online (Sandbox Code Playgroud)

抛出错误:

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 }
Run Code Online (Sandbox Code Playgroud)

尽管两者都是:

main = do
    runTestTT tests
Run Code Online (Sandbox Code Playgroud)

main = do
    line <- getLine
    line2 <- getLine
    seq::[Int] <- return $ map read $ words line2
    print $ process seq
Run Code Online (Sandbox Code Playgroud)

工作得很好?

Dan*_*her 9

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

runTestTT tests :: IO Counts
Run Code Online (Sandbox Code Playgroud)

print $ process seq :: IO ()
Run Code Online (Sandbox Code Playgroud)

你可以添加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
Run Code Online (Sandbox Code Playgroud)

修复它(或者你可以添加return some_value_of_type_Countselse分支).