Skip to content

Instantly share code, notes, and snippets.

@tcsavage
Last active March 25, 2022 19:44
Show Gist options
  • Save tcsavage/4391349 to your computer and use it in GitHub Desktop.
Save tcsavage/4391349 to your computer and use it in GitHub Desktop.
Example of ReaderT monad transformer
module Main where
import Control.Monad (replicateM)
import Control.Monad.Trans (lift)
import Control.Monad.Reader (ReaderT, ask, runReaderT)
import Control.Monad.Random (Rand, getRandomR, evalRand)
import System.Random (getStdGen, StdGen)
import Text.Printf
op :: ReaderT Int (Rand StdGen) String
op = do
x <- ask -- Get read-only state from ReaderT
y <- lift $ getRandomR (0, 1 :: Double) -- Lift Rand computation into ReaderT
return $ printf "%d : %f" x y -- Build String value to return
main :: IO ()
main = do
rand <- getStdGen -- Get random generator from IO
let ops = replicateM 3 op -- ReaderT Int (Rand StdGen) [String]
let ranReader = runReaderT ops 5 -- Pass '5' in as read-only state. Rand StdGen [String]
let ranRandom = evalRand ranReader rand -- [String]
print ranRandom
ghci> main
["5 : 0.6494038665120211","5 : 0.325141434228958","5 : 0.41333205510519855"]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment