[英]Haskell: Couldn't match expected type 'IO b' with actual type bool
我收到以下錯誤:
Couldn't match expected type `IO b' with actual type `Bool'
In the expression:
upCheck
["########", "#11xxx3#", "#xx2xx3", "#002xx3", ....] 2 [2, 3, 4]
In the expression:
do { s <- readFile "projekt-board.txt";
let content = lines s;
printTable content;
printHelp;
.... }
In an equation for `gameFunc':
gameFunc
= do { s <- readFile "projekt-board.txt";
let content = ...;
printTable content;
.... }
使用gameFunc
的定義:
gameFunc = do
s <- readFile "projekt-board.txt"
let content = lines s
printTable content
printHelp
upCheck ["########","#11xxx3#","#xx2xx3","#002xx3","#7x2x44#"] 2 [2,3,4]
和功能upCheck
:
upCheck :: [[Char]] -> Int -> [Int] -> Bool
upCheck tableArr number posArr = do
--posArr saadakse findBlock funktsiooniga
let arv = findVIndex (findVertIndex tableArr number)
let str = tableArr !! (posArr !! 0)
if ((posArr !! 0) == 1)
then False
else if arv == (-1)
then False
else if isHorizontal str number
then False
else if (tableArr !! ((posArr !! 0)-1)) !! arv /= 'x'
then False
else True
因此,基本上,這里發生的事情是upCheck
是一個用於檢查某些條件是否匹配的函數,當我從ghci調用它的方式與從gameFunc
函數調用它的方式gameFunc
,我將得到結果True
。 但是,如果我從gameFunc
函數中調用它, gameFunc
收到上述錯誤。 任何想法出了什么問題?
問題是您的功能gameFunc
使用了do表達式,該表達式是monad (在本例中為IO
monad)的語法糖。 您可以使用return
函數將任何非monadic結果轉換為monadic結果:
return :: Monad m => a -> m a
因此,您可以將gameFunc
重寫為(請參見最后一行):
gameFunc = do
s <- readFile "projekt-board.txt"
let content = lines s
printTable content
printHelp
return $ upCheck ["########","#11xxx3#","#xx2xx3","#002xx3","#7x2x44#"] 2 [2,3,4]
現在gameFunc
的類型為IO Bool
。 您可以在其他單子環境中使用gameFunc
,例如:
main = do
b <- gameFunc
print b
為了打印gameFunc
的結果。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.