gpt4 book ai didi

haskell - do block 中的条件

转载 作者:行者123 更新时间:2023-12-02 17:07:18 24 4
gpt4 key购买 nike

为什么下面的代码块是这样的:

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

工作正常吗?

最佳答案

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分支)。

关于haskell - do block 中的条件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15449795/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com