I am trying to wrap my head around Monads, and feel that if I could get an explaination to why this doesn't compile, I'd have a better understanding.
module Main where
import Data.Maybe
import System.Environment
myFunc :: String-> Maybe String
myFunc x = Just x
main :: IO ()
main = myFunc "yo" >>= putStrLn
The error I get is
blah.hs:9:10:
Couldn't match type `Maybe' with `IO'
Expected type: IO String
Actual type: Maybe String
In the return type of a call of `myFunc'
In the first argument of `(>>=)', namely `myFunc "yo"'
In the expression: myFunc "yo" >>= putStrLn
I realize that the issue is that I'm trying to match a Maybe
with an IO
, but I'm not entire sure how to cast my Maybe'd variable into an IO. Any help would be greatly appreciated!
You are correct in realizing that you are trying to match a Maybe
with an IO
. For the bind (>>=
) operator to typecheck, both the Monad should be the same. One way to solve this problem would be to wrap the Maybe
in an IO
monad using return
:
return (myFunc "yo") >>= putStrLn . show
Or more simply:
return (myFunc "yo") >>= print
That being said, you don't need all the fancy monad operators here. This should simply work:
main :: IO ()
main = print . myFunc $ "yo"
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments