Last active
May 3, 2020 12:51
-
-
Save ryu1kn/dddfb3d44bdcad60cada3af680e984b1 to your computer and use it in GitHub Desktop.
Same code with and without Reader monad
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
module WithoutReader where | |
import Prelude | |
import Control.Monad.Reader (asks) | |
import Data.String (toLower) | |
import Effect (Effect) | |
import Effect.Console (log) | |
type Config = {username :: String} | |
appConfig :: Config | |
appConfig = {username: "FOO"} | |
main :: Effect Unit | |
main = do | |
log $ app appConfig -- Instead of using `runReader`, just apply a function | |
app :: Config -> String -- Type is of a normal function | |
app = do -- A function is a monad. Monad here is (Config ->) | |
name <- getName -- `config` is not explicitly passed to `getName`, but done as a monad context | |
pure $ "Hello " <> name <> "!" -- `pure` wraps its argument back into the monad (i.e. function). Equivalent to `const` | |
getName :: Config -> String -- Type is of a normal function | |
getName = do | |
name <- asks _.username -- A function inherits MonadAsk. | |
pure $ toLower name |
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
module WithReader where | |
import Prelude | |
import Control.Monad.Reader (Reader, asks, runReader) | |
import Data.String (toLower) | |
import Effect (Effect) | |
import Effect.Console (log) | |
type Config = {username :: String} | |
appConfig :: Config | |
appConfig = {username: "FOO"} | |
main :: Effect Unit | |
main = do | |
log $ runReader app appConfig | |
app :: Reader Config String | |
app = do | |
name <- getName | |
pure $ "Hello " <> name <> "!" | |
getName :: Reader Config String | |
getName = do | |
name <- asks _.username | |
pure $ toLower name |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment