Skip to content

Instantly share code, notes, and snippets.

@boj
Created February 26, 2019 17:23
Show Gist options
  • Select an option

  • Save boj/d34ac9af032d1ff8dbc3f58fb01f5a19 to your computer and use it in GitHub Desktop.

Select an option

Save boj/d34ac9af032d1ff8dbc3f58fb01f5a19 to your computer and use it in GitHub Desktop.
{-# LANGUAGE OverloadedStrings #-}
module Main where
import Control.Monad.Reader
-- a basic IO function
f :: IO String
f = return "string"
-- you can pass IO functions to a function
-- which can be executed later.
-- the whole function has to stay in IO though
g :: IO String -> IO String
g f' = do
v <- f'
return (v ++ "-g")
-- a basic pure function that takes a string
-- and returns a string.
-- it can do nothing else
h :: String -> String
h s = s ++ "-h"
-- this is a pure function using the Reader monad
-- it has a string that gets passed around,
-- and the function itself returns a string
i :: Reader String String
i = do
s <- ask
return (s ++ "-reader")
-- while we don't do IO in here, we very well could
-- we also get access to `ask` via ReaderT
j :: ReaderT String IO Int
j = do
s <- ask
return (length s)
-- k doesn't actually use the Reader value
-- but the function below it does
k :: Int -> ReaderT String IO Int
k a = do
v <- j
return (v + a)
main :: IO ()
main = do
a <- f
print a
b <- g f
print b
-- note that pure functions don't get executed
-- the print statement actually evaluates the function
let c = h "string"
print c
-- this is a pure reader, thus the let
let d = runReader i "string"
print d
-- this is a monad transformer with IO at the bottom
-- therefore the action has to be executed
e <- runReaderT j "string"
print e
z <- runReaderT (k 10) "string"
print z
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment