Chapter 13. Yesod’s Monads
As you’ve progressed through this book so far, a number of monads have
appeared: Handler
, Widget
, and YesodDB
(for Persistent). As with most
monads, each one provides some specific functionality: Handler
gives access
to the request and allows you to send responses; a Widget
contains HTML, CSS,
and JavaScript; and YesodDB
lets you make database queries. In
model-view-controller (MVC) terms, we could consider YesodDB
to be the model,
Widget
to be the view, and Handler
to be the controller.
So far, we’ve presented some very straightforward ways to use these monads: your main handler will run in Handler
, using runDB
to execute a YesodDB
query and defaultLayout
to return a Widget
, which in turn was created by calls to toWidget
.
However, if we have a deeper understanding of these types, we can achieve some fancier results.
Monad Transformers
Monads are like onions. Monads are not like cakes.
Variation on a quote from Shrek
Before we get into the heart of Yesod’s monads, we need to understand a bit
about monad transformers. (If you already know all about monad transformers,
you can likely skip this section.) Different monads provide different
functionality: Reader
allows read-only access to some piece of data
throughout a computation, Error
allows you to short-circuit computations, and
so on.
Oftentimes, however, you’ll want to be able to combine a few of these features together. After all, why not have a computation with read-only access to some settings ...
Get Developing Web Apps with Haskell and Yesod, 2nd Edition now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.