Created
May 4, 2019 08:38
-
-
Save etorreborre/6685dd229198010f54a9ae29b1ab6102 to your computer and use it in GitHub Desktop.
How to use IO with components
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
| data Logger m = Logger { | |
| info :: Text -> m () | |
| , warn :: Text -> m () | |
| } | |
| -- | IO is only used to create the Logger | |
| newLogger :: Logger IO | |
| newLogger = Logger { | |
| info = \t -> print ("[INFO] " <> show t) | |
| , warn = \t -> print ("[WARN] " <> show t) | |
| } | |
| data Calculator m = Calculator { | |
| add :: Int -> Int -> m Int | |
| } | |
| -- | IO is only used to create the Calculator | |
| newCalculator :: Logger IO -> Calculator IO | |
| newCalculator logger = Calculator { | |
| add = add' logger | |
| } | |
| -- | When using the Logger in the "business logic" we only need to assume `Monad m` | |
| add' :: Monad m => Logger m -> Int -> Int -> m Int | |
| add' logger a b = do | |
| let c = a + b | |
| info logger ("the result is " <> show c) | |
| pure c |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment