Last active
November 1, 2016 11:09
-
-
Save pekhee/ee822a9b14d88dafd44e2db3e8faa8b1 to your computer and use it in GitHub Desktop.
To do an IO action with the resulting value of a Monad we can either unwrap the Monad or use a Monad Transformer
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import Control.Monad.Trans (lift) | |
import Control.Monad.Trans.Maybe (MaybeT, runMaybeT) | |
monadicAdd :: Monad m => m Int -> m Int -> m Int | |
monadicAdd l r = do | |
l_ <- l | |
r_ <- r | |
return (l_ + r_) | |
printWithTransformerMonad :: MaybeT IO Int -> MaybeT IO Int | |
printWithTransformerMonad n = do | |
n_ <- n | |
lift . print $ n_ | |
return n_ | |
main :: IO () | |
main = do | |
let x = return 1 | |
let y = return 2 | |
let r = monadicAdd x y | |
runMaybeT $ printWithTransformerMonad r | |
return () |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
runghc monad_transformer.hs | |
#=> 3 |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
monadicAdd :: Monad m => m Int -> m Int -> m Int | |
monadicAdd l r = do | |
l_ <- l | |
r_ <- r | |
return (l_ + r_) | |
main :: IO () | |
main = do | |
let x = return 1 | |
let y = return 2 | |
-- Be careful, we will get a runtime error if monadicAdd returns Nothing | |
let Just r = monadicAdd x y | |
print r |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
runghc unwrap_monad.hs | |
#=> 3 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment