Saturday, October 13, 2007

Monad.Reader

The Reader monad is a simple and easy-to-use structure from the Haskell library that solves a common problem.

Very often, it's the case that you have a lot of functions that all need to use the same values. For instance, you might be laying out some text on a page, and you need to keep the details of the page size around in all your layout algorithms. Typically, you handle this situation by adding a new parameter to all your functions which represents the state. So,


layoutPage :: Text -> Page


becomes


layoutPage :: PageLayoutParams -> Text -> Page


This works just fine, but it can get really ugly. Every single function gets a new parameter, which must be threaded through to every related function that it ever calls. This causes visual clutter, particularly for functions that don't actually use the parameter themselves but just pass it on.

A function written in the Reader monad is augmented with a hidden parameter. For the hypothetical example above, we would write:


import Control.Monad.Reader
type LayoutFunc = Reader PageLayoutParams

layoutPage :: Text -> LayoutFunc Page


Note that the Reader monad is partially applied here. The result, LayoutFunc, is a new monad that adds a parameter of type PageLayoutParams to any code that runs inside it.

So, now that we have this monad, how do we use it? The "ask" operation retrieves the parameter that's hidden in the monad:


ask :: Reader a a


or, specialized to LayoutFunc:


ask :: LayoutFunc PageLayoutParams


In order to remain close to the example in question, I will provide specialized type signatures for the rest of the library functions. You can find the generic type signatures in the Haskell library documentation for Control.Monad.Reader.

Suppose that layoutPage started out like this before it was moved into the monad:


layoutPage st txt =
let width = pageWidth st
...


In the Reader monad, this becomes:


layoutPage txt =
do st <- ask
let width = pageWidth st
...


As you can see, we've gone from one line of code to two. As this is clearly unacceptable for a clutter-reducing device, the Reader module provides a convenience function encapsulating the above pattern:


asks :: (PageLayoutParams -> a) -> PageLayoutFunc a


This allows us to simplify the monadic implementation to:


layoutPage txt =
do width <- asks pageWidth
...


It's quite common, when multiple functions share context information, to invoke a function in an altered context. For instance, we might have a layoutSubPage routine that changes the page width:


layoutSubPage st newWidth txt =
doLayout (st {pageWidth = newWidth} txt)


The Reader equivalent of this idiom is the function "local":


local :: (PageLayoutParams -> PageLayoutParams) -> LayoutFunc a -> LayoutFunc a


local executes an operation in a context modified by its first parameter. For instance,


layoutSubPage newWidth txt =
local (\st -> st { pageWidth = newWidth }) txt


Finally, to actually invoke a computation in the Reader monad, use runReader:


runReader :: LayoutFunc a -> PageLayoutParams -> a

main = showPage (runReader defaultPageParams someText)


For much more information on the Reader monad, see All About Monads, or the Haskell library documentation.

18 Comments:

At 6:11 PM, Blogger alejuliet said...

You are the best...really... this was the best post I'd found, and I really really needed...thank u so much!

 
At 11:12 PM, Anonymous Anonymous said...

This is a great post; I'm definitely going to use the Reader monad in my code from now on, now that I understand it.

 
At 11:16 PM, Blogger Unknown said...

Good tutorial. Thanks.

 
At 9:53 AM, Anonymous Anonymous said...

Good past, thanks!

 
At 4:40 PM, Anonymous Anonymous said...

I enjoy what you guys are up too. This kind of clever work and coverage!

Keep up the great works guys I've included you guys to my blogroll.

my webpage ... low fee cash advance
My website: very nice web site

 
At 6:56 PM, Anonymous Anonymous said...

Somebody necessarily help to make significantly articles I
might state. That is the first time I frequented your website page
and so far? I amazed with the research you
made to create this particular submit amazing.

Fantastic job!

My web-site - check our their site
Also see my site - natural breast enhancement pills that work

 
At 7:04 PM, Anonymous Anonymous said...

I think this is among the most significant information for me.
And i am glad reading your article. But want to remark on
few general things, The website style is perfect, the articles is really nice :
D. Good job, cheers

Stop by my blog :: check our their site

 
At 12:21 AM, Blogger John said...

kobe bryant shoes
coach outlet online
kd shoes
concords 11
prada uk
oakley sunglasses
michael kors outlet
toms outlet
timberland boots
polo ralph lauren
tiffany and co
abercrombie fitch
michael kors outlet online
michael kors handbags
montblanc
michael kors outlet online
abercrombie
louis vuitton
uggs for men
uggs clearance
ugg boots
p90x workouts
ray ban sunglasses
louis vuitton
michael kors outlet
lebron james shoes
ray ban outlet
hollister clothing
coach factory outlet
cheap nfl jerseys
coach factory outlet
20151210yuanyuan

 
At 8:17 PM, Blogger oakleyses said...

uggs outlet, uggs on sale, ray ban sunglasses, ray ban sunglasses, louis vuitton, michael kors outlet online, oakley sunglasses wholesale, christian louboutin outlet, louis vuitton, uggs outlet, louis vuitton outlet, polo outlet, prada handbags, nike free, chanel handbags, longchamp outlet, michael kors outlet, replica watches, louis vuitton outlet, oakley sunglasses, michael kors outlet online, prada outlet, michael kors outlet online, longchamp outlet, burberry handbags, michael kors outlet, kate spade outlet, ray ban sunglasses, longchamp outlet, louis vuitton outlet, oakley sunglasses, nike air max, oakley sunglasses, replica watches, ugg boots, polo ralph lauren outlet online, ugg boots, gucci handbags, jordan shoes, cheap oakley sunglasses, michael kors outlet online, christian louboutin uk, burberry outlet, tory burch outlet, tiffany and co, christian louboutin shoes

 
At 8:21 PM, Blogger oakleyses said...

doudoune moncler, pandora uk, moncler outlet, vans, converse outlet, montre pas cher, louis vuitton, moncler, moncler, canada goose, canada goose outlet, ugg uk, links of london, barbour uk, supra shoes, replica watches, lancel, nike air max, moncler, moncler, moncler outlet, coach outlet, wedding dresses, canada goose outlet, pandora jewelry, karen millen uk, ugg, marc jacobs, juicy couture outlet, converse, moncler uk, louis vuitton, ugg pas cher, swarovski, pandora jewelry, gucci, canada goose, canada goose uk, ugg,uggs,uggs canada, pandora charms, juicy couture outlet, louis vuitton, louis vuitton, ray ban, ugg,ugg australia,ugg italia, canada goose jackets, swarovski crystal, canada goose, hollister, thomas sabo, canada goose outlet, toms shoes

 
At 10:49 PM, Blogger raybanoutlet001 said...

adidas nmd
yeezy boost 350
michael kors outlet store
http://www.raybanglasses.in.net
christian louboutin outlet
kobe basketball shoes
tiffany jewellery
tiffany and co outlet
michael kors factory outlet
michael kors outlet online
true religion sale
christian louboutin shoes
fitflops clearance
adidas nmd
nike huaraches
huarache shoes
ralph lauren uk

 
At 9:45 PM, Blogger chenlina said...

light up shoes
prada bags
oakley sunglasses
coach outlet online
cheap oakley sunglasses
stuart weitzman shoes
jordan shoes
north face
nfl jerseys wholesale
cheap jerseys
chenlina20180306

 
At 8:35 PM, Blogger Unknown said...

michael kors outlet online
air max 90
canada goose
soccer shoes
timberland
true religion
replica watches
reebok outlet
nike clothing
clarks shoes
20183.22hemeimei

 
At 12:57 AM, Blogger jeje said...

Voyons maintenant nike baskets air max classic bw homme comment la bioélectronique joue un rôle basket nike roshe run noir et blanc essentiel dans le domaine chaussure nike a talon pour femme de la médecine et d'autres chaussure nike air huarache pas cher domaines. Nike Shox Livrer contre site de chaussure air jordan pas cher les plus petits fabricants de chaussures. nike air max 1 pas cher femme noir magenta gris

 
At 7:47 AM, Blogger gem1musi said...

آهنگ مرتضی اشرفی لجباز
آهنگهای پرسپولیس
آهنگ میثم ابراهیمی سلامتی
آهنگ حمید هیراد دلبر
آهنگ حسین توکلی امسال قشنگه
آهنگ محمد علیزاده گاندو
ریمیکس های جدید رادیو جوان
آهنگ اشوان آهنگ شاد
ترانه جدید mp3
موزیک Mp3

 
At 11:35 AM, Blogger yanmaneee said...

moncler coat
hermes birkin
kd shoes
bape
off white
jordan 11
off white nike
michael jordan shoes
supreme clothing
yeezy 350

 
At 2:06 AM, Anonymous Anonymous said...

jordan sneakers
supreme outlet
off white clothing
golden goose sneakers
supreme
westbrook shoes
supreme hoodie
golden goose
fear of god outlet
golden goose

 
At 2:08 AM, Anonymous Anonymous said...

kd 15
off white
kd 15
supreme t shirt
bape
kobe byrant shoes
off white
hermes birkin
golden goose sneakers
kyrie 8

 

Post a Comment

<< Home