为什么以下代码块:
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
工作正常吗?
答案 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
。