Skip to content

Instantly share code, notes, and snippets.

@davidallsopp
Created October 24, 2014 14:50
Show Gist options
  • Save davidallsopp/9aaf8568349e6b8643d4 to your computer and use it in GitHub Desktop.
Save davidallsopp/9aaf8568349e6b8643d4 to your computer and use it in GitHub Desktop.
Simple example of the Reader Monad (in Haskell)
module ReaderMonad where
import Control.Monad.Reader
stuff :: Reader Int String
stuff = do
s <- ask
return (show s ++ " green bottles")
main :: IO ()
main = print $ runReader stuff 99
-- what's the point of Reader, since we could just pass
-- the parameters to the stuff function?
-- Reader is used instead of global state, for "constants" etc
-- to avoid polluting every single function with params (which it might only pass
-- on to other functions, and not even use itself)
-- You still have to modify all these functions to use Reader, though
-- see http://lambdaman.blogspot.co.uk/2007/10/monadreader.html
-- See http://stackoverflow.com/questions/14178889/reader-monad-purpose
-- Can use 'asks' as well as 'ask' to avoid all the do-block boilerplate
-- and may create an alias for the reader if it's used in lots of places
type IntRead = Reader Int
stuff2 :: IntRead String
stuff2 = asks show
-- stuff2 = do asks $ \s -> (show s ++ " green bottles")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment