Skip to content

Instantly share code, notes, and snippets.

@dtchepak
Created August 1, 2012 12:29
Show Gist options
  • Save dtchepak/3226421 to your computer and use it in GitHub Desktop.
Save dtchepak/3226421 to your computer and use it in GitHub Desktop.
Simple reader monad
instance Functor ((->) t) where
--fmap :: (a -> b) -> (t -> a) -> (t -> b)
fmap = (.)
instance Monad ((->) t) where
return = const
--(>>=) :: (t -> a) -> (a -> t -> b) -> t -> b
f >>= g = \t -> let a = f t
in g a t
data Person = Person { name :: String, age :: Int, address :: String }
showPerson :: Person -> String
showPerson = do
x <- ("Name: " ++) . name
y <- ("Age: " ++) . show . age
z <- ("Address: " ++) . address
return . unlines $ [x,y,z]
@dtchepak
Copy link
Author

dtchepak commented Aug 6, 2012

With Control.Monad.Reader:

showPerson4 :: Person -> String
showPerson4 = 
    let showPersonReader = do
        x <- asks $ ("Name: " ++) . name
        y <- asks $ ("Age: " ++) . show . age
        z <- asks $ ("Address: " ++) . address
        return . unlines $ [x, y, z]
    in runReader showPersonReader

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment