Last active
March 25, 2022 19:44
-
-
Save tcsavage/4391349 to your computer and use it in GitHub Desktop.
Example of ReaderT monad transformer
This file contains 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 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 |
This file contains 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
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