Skip to content

Instantly share code, notes, and snippets.

@etorreborre
Created May 4, 2019 08:38
Show Gist options
  • Select an option

  • Save etorreborre/6685dd229198010f54a9ae29b1ab6102 to your computer and use it in GitHub Desktop.

Select an option

Save etorreborre/6685dd229198010f54a9ae29b1ab6102 to your computer and use it in GitHub Desktop.
How to use IO with components
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