Haskell:无法将预期类型'IO b'与实际类型bool匹配

时间:2016-01-05 09:36:11

标签: haskell monads io-monad

我收到以下错误:

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调用它,我会得到一个结果True。但是,如果我从函数gameFunc中调用它,我会收到上述错误。任何想法出了什么问题?

1 个答案:

答案 0 :(得分:2)

问题是你的函数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。您可以在其他monadic环境中使用gameFunc,例如:

main = do
    b <- gameFunc
    print b

以便打印gameFunc

的结果