简体   繁体   中英

Couldn't match expected type `IO ()' with actual type `a0 -> m0 a0'

Here's my code:

doSomething :: IO Bool -> IO () -> IO ()
doSomething cond body = cond >>= ( \condition -> if condition then return else body )

It gives me this error:

Couldn't match expected type `IO ()' with actual type `a0 -> m0 a0'
In the expression: return
In the expression: if condition then return else body
In the second argument of `(>>=)', namely
  `(\ condition -> if condition then return else body)'

I also tried this equivalent notation:

whileM :: IO Bool -> IO () -> IO ()
whileM cond body = do
                     condition <- cond
                     if condition then return else body

but I am getting more or less the same notation. I understand that the error is saying that the function expects me to return a Monad but instead I am returning a function which transforms a0 into a monad m a0 . How can I fix this?

Unlike in (pretty much all) other languages, in Haskell, return doesn't mean "terminate this code and go back to the next line of what called it".

In Haskell, it (roughly) means "wrap this thing up in a monad". In the context of the do notation, this often occurs at the place in the code where control is given back to the "caller" (again, this isn't really the correct word, but will do in this analogy).

Hence, return needs a parameter here (the thing to be wrapped up).... return is of type Monad m => a -> ma , but your function is returning type IO () . The thing you will therefore need to wrap up is of type () , a type with just one element, '()' itself.

Change return to return () , and see if that works.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM