{"id":294,"date":"2007-01-31T14:02:33","date_gmt":"2007-01-31T14:02:33","guid":{"rendered":"http:\/\/scientopia.org\/blogs\/goodmath\/2007\/01\/31\/the-theory-of-monads-and-the-monad-laws\/"},"modified":"2007-01-31T14:02:33","modified_gmt":"2007-01-31T14:02:33","slug":"the-theory-of-monads-and-the-monad-laws","status":"publish","type":"post","link":"http:\/\/www.goodmath.org\/blog\/2007\/01\/31\/the-theory-of-monads-and-the-monad-laws\/","title":{"rendered":"The Theory of Monads and the Monad Laws"},"content":{"rendered":"<p> As promised, I&#8217;m finally going to get to the theory behind monads. As a quick review, the basic idea of the monad in Haskell is a hidden transition function &#8211; a monad is, basically, a state transition function.<\/p>\n<p> The theory of monads comes from category theory. I&#8217;m going to assume you know a little bit about category theory &#8211; if you have trouble with it, go take a look at my introductory posts <a href=\"http:\/\/scienceblogs.com\/goodmath\/goodmath\/category_theory\/\">here. <\/a><\/p>\n<p><!--more--><\/p>\n<p> Fundamentally, in category theory a monad is a category with a particular kind of structure. It&#8217;s a category with <em>one<\/em> object. That category has a collection of arrows which (obviously) are from the single object <em>to itself<\/em>. That one-object category has a <em>functor<\/em> from the category to itself. (As a reminder, a functoris an arrow between categories in the category of (small) categories.) <\/p>\n<p> The first trick to the monad, in terms of theory, is that it&#8217;s <em>fundamentally<\/em> about the functor: since the functor maps from a category to <em>the same category<\/em>, so you can almost ignore the category; it&#8217;s implicit in the definition of the functor. So we can almost treat the monad as if it were just the functor &#8211; that is, a kind of transition function.<\/p>\n<p> The other big trick is closely related to that. For the programming language application of monads, we can think of the single object in the category as the set of all possible states. So we have a category object, which is essentially the collection of all possible states; and there are arrows between the states representing possible state transitions. So the monad&#8217;s functor is really just a mapping from arrows to different arrows &#8211; which basically represents the way that changing the state causes a change in the possible transitions to other states. <\/p>\n<p> So what a monad gives us, in terms of category theory, in a conceptual framework that captures the concept of a state transition system, in terms of transition functions that <em>invisibly<\/em> carry a state. When that&#8217;s translated into programming languages, that becomes a <em>value<\/em> that implicitly takes an input state, possibly updates it, and returns an output state. Sound familiar? <\/p>\n<p> Let&#8217;s take a moment and get formal. As usual for category theory, first there are some preliminary definitions.<\/p>\n<ol>\n<li> Given a category, <b>C<\/b>, 1<sub>C<\/sub> is the <em>identity functor<\/em> from C to C.<\/li>\n<li> Given a category <b>C<\/b> with a functor <b>T<\/b> : <b>C<\/b> &rarr; <b>C<\/b>, <b>T<\/b><sup>2<\/sup> = <b>T<\/b> &ordm; <b>T<\/b>. <\/li>\n<li> Given a functor <b>T<\/b>, 1<sub>T<\/sub> : <b>T<\/b> &rarr; <b>T<\/b> is the <em>natural transformation<\/em> from <b>T<\/b> to <b>T<\/b>.<\/li>\n<\/ol>\n<p> Now,  with that out of the way, we can give the complete formal definition of a monad. Given a category <b>C<\/b>, a <em>monad on <b>C<\/b><\/em> is a triple:  (<b>T<\/b>:<b>C<\/b>&rarr;<b>C<\/b>, &eta;:1<sub>C<\/sub>&rarr;<b>T<\/b>, &mu;:<b>T<\/b><sup>2<\/sup> &rarr; <b>T<\/b>), where <b>T<\/b> is a functor, and &eta; and &mu; are natural transformations. The members of the triple must make the following two diagrams commute.<\/p>\n<p><img data-recalc-dims=\"1\" loading=\"lazy\" decoding=\"async\" alt=\"monad-prop1.jpg\" src=\"https:\/\/i0.wp.com\/scientopia.org\/img-archive\/goodmath\/img_300.jpg?resize=157%2C117\" width=\"157\" height=\"117\" \/><\/p>\n<p><\/p>\n<p><em>Commutativity of composition with &mu;<\/em><\/p>\n<hr \/>\n<p><img data-recalc-dims=\"1\" loading=\"lazy\" decoding=\"async\" alt=\"monad-prop2.jpg\" src=\"https:\/\/i0.wp.com\/scientopia.org\/img-archive\/goodmath\/img_301.jpg?resize=236%2C170\" width=\"236\" height=\"170\" \/><\/p>\n<p><\/p>\n<p><em>Commutativity of composition with &eta;<\/em><\/p>\n<p> What these two diagrams mean is that successive applications of the state-transition functor over <b>C<\/b> behave associatively &#8211; that any sequence of composing monadic functors will result in a functor with full monadic structure; and that the monadic structure will always preserve. Together, these mean that any sequence of operations (that is, applications of the monad functor) are themselves monad functors &#8211; so the building a sequence of monadic state transformers is guaranteed to behave as a proper monadic state transition &#8211; so what happens <em>inside<\/em> of the monadic functor is fine &#8211; to the rest of the universe, the difference between a sequence and a single simple operation is indistinguishable: the state will be consistently passed from application to application with the correct chaining behavior, and to the outside world, the entire monadic chain looks like like a single atomic monadic operation.<\/p>\n<p> Now, what does this mean in terms of programming? Each element of a monadic sequence in Haskell is an instantiation of the monadic functor &#8211; that is, it&#8217;s an <em>arrow<\/em> between states &#8211; a function, not a simple value &#8211; which is the basic trick to monads. They look like a sequence of <em>statements<\/em>; in fact, each statement in a monad is actually a function from state to state. And it looks like we&#8217;re writing sequence code &#8211; when what we&#8217;re actually doing is writing <em>function compositions<\/em> &#8211; so that when we&#8217;re done writing a monadic sequence, what we&#8217;ve <em>actually<\/em> done is written a <em>function definition<\/em> in terms of a sequence of function compositions.<\/p>\n<p> Understanding that, we can now clearly understand why we need the <em>return<\/em> function to use a non-monad expression inside of a monadic sequence &#8211; because each step in the sequence needs to be an instance of the monadic functor; an expression that <em>isn&#8217;t<\/em> an instance of the monadic functor couldn&#8217;t be composed with the functions in the sequence. The return function is really nothing but a function that combines a non-monadic expression with the <em>id<\/em> functor. <\/p>\n<p> In light of this, let&#8217;s go back and look at the definition of <code>Monad<\/code> in the Haskell standard prelude.<\/p>\n<pre>\nclass  Functor f  where\n  fmap              :: (a -&gt; b) -&gt; f a -&gt; f b\n\nclass  Monad m  where\n  (&gt;&gt;=)  :: m a -&gt; (a -&gt; m b) -&gt; m b\n  (&gt;&gt;)   :: m a -&gt; m b -&gt; m b\n  return :: a -&gt; m a\n  fail   :: String -&gt; m a\n\n  -- Minimal complete definition:\n  --      (&gt;&gt;=), return\n  m &gt;&gt; k  =  m &gt;&gt;= _ -&gt; k\n  fail s  = error s\n<\/pre>\n<p> The declaration of monad is connected with the definition of functor &#8211; if you look, you can see the connection. The fundamental operation of <code>Monad<\/code> is &#8220;<code>&gt;&gt;=<\/code>&#8221; &#8211; the chaining operation, which is type <code>m a -&gt; (a -&gt; m b) -&gt; m b<\/code> is deeply connected with the <code>fmap<\/code> operation from <code>Functor<\/code>&#8216;s <code>fmap<\/code> operation &#8211; the <code>a<\/code> in <code>m a<\/code> is generally going to be a type which can be a <code>Functor<\/code>. <\/p>\n<p> So the value type wrapped in the monad is a functor &#8211; in fact, <em>the<\/em> functor from the category definition! And the &#8220;<code>&gt;&gt;=<\/code>&#8221; operation is just the functor composition operation from the monad definition.<\/p>\n<p> A proper implementation of a monad needs to follow some fundamental rules &#8211; the rules are, basically, just Haskell translations of the structure-preserving rules about functors and natural transformations in the category-theoretic monad. There are two groups of laws &#8211; laws about the <code>Functor<\/code> class, which should hold for the transition function wrapped in the monad class; and laws about the monadic operations in the <code>Monad<\/code> class. One important thing to realize about the functor and monad laws is that they <em>are not enforced<\/em> &#8211; in fact, <em>cannot<\/em> be enforced! &#8211; but monad-based code using monad implementations that do not follow them may not work correctly. (A compile-time method for correctly verifying the enforcement of these rules can be shown to be equivalent to the halting problem.)<\/p>\n<p> There are two simple laws for <code>Functor<\/code>, and it&#8217;s pretty obvious why they&#8217;re fundamentally just strucure-preservation requirements. The functor class only has one operation, called <code>fmap<\/code>, and the two functor laws are about how it must behave.<\/p>\n<ol>\n<li> <code>fmap id = id<\/code>  <br \/> <em>(Mapping ID over any structured sequence results in an unmodified sequence)<\/em><\/li>\n<li> <code>fmap (f . g) = (fmap f) . (fmap g)<\/code>  <br \/><em>(&#8220;.&#8221; is the function composition operation; this just says that fmap preserves the structure to ensure that that mapping is associative with composition.)<\/em><\/li>\n<\/ol>\n<p> The monad laws are a bit harder, but not much. The mainly govern how monadic operations interact with non-monadic operations in terms of the &#8220;<code>return<\/code>&#8221; and &#8220;<code>&gt;&gt;=<\/code>&#8221; operations of the <code>Monad<\/code> class.<\/p>\n<ol>\n<li> <code>return x &gt;&gt;= f  = f x<\/code> <br \/><em>(injecting a value into the monad is basically the same as passing it as a parameter down the chain &#8211; return is really just the identity functor passing its result on to the next step.)<\/em><\/li>\n<li> <code> f &gt;&gt;= return = f<\/code> <br \/><em>(If you don&#8217;t specify a value for a return, it&#8217;s the same as just returning the result of the previous step in the sequence &#8211; again, return is just identity, so passing something into return shouldn&#8217;t affect it.)<\/em><\/li>\n<li> <code>seq &gt;&gt;= return . f = fmap f seq<\/code> <br \/><em>(composing return with a function is equivalent to invoking that function on the result of the monad sequence to that point, and wrapping the result in the monad &#8211; in other words, it&#8217;s just composition with identity.)<\/em><\/li>\n<li> <code>seq &gt;&gt;= (x -&gt; f x &gt;&gt;= g) = (seq &gt;&gt;= f) &gt;&gt;= g<\/code><br \/> <em>(Your implementation of &#8220;<code>&gt;&gt;=<\/code>&#8221; needs to be semantically equivalent to the usual translation; that is, it must behave like a functor composition.)<\/em><\/li>\n<\/ol>\n","protected":false},"excerpt":{"rendered":"<p>As promised, I&#8217;m finally going to get to the theory behind monads. As a quick review, the basic idea of the monad in Haskell is a hidden transition function &#8211; a monad is, basically, a state transition function. The theory of monads comes from category theory. I&#8217;m going to assume you know a little bit [&hellip;]<\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"jetpack_post_was_ever_published":false,"_jetpack_newsletter_access":"","_jetpack_dont_email_post_to_subs":false,"_jetpack_newsletter_tier_id":0,"_jetpack_memberships_contains_paywalled_content":false,"_jetpack_memberships_contains_paid_content":false,"footnotes":"","jetpack_publicize_message":"","jetpack_publicize_feature_enabled":true,"jetpack_social_post_already_shared":false,"jetpack_social_options":{"image_generator_settings":{"template":"highway","default_image_id":0,"font":"","enabled":false},"version":2}},"categories":[76,89],"tags":[],"class_list":["post-294","post","type-post","status-publish","format-standard","hentry","category-category-theory","category-haskell"],"jetpack_publicize_connections":[],"jetpack_featured_media_url":"","jetpack_shortlink":"https:\/\/wp.me\/p4lzZS-4K","jetpack_sharing_enabled":true,"jetpack_likes_enabled":true,"_links":{"self":[{"href":"http:\/\/www.goodmath.org\/blog\/wp-json\/wp\/v2\/posts\/294","targetHints":{"allow":["GET"]}}],"collection":[{"href":"http:\/\/www.goodmath.org\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"http:\/\/www.goodmath.org\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"http:\/\/www.goodmath.org\/blog\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"http:\/\/www.goodmath.org\/blog\/wp-json\/wp\/v2\/comments?post=294"}],"version-history":[{"count":0,"href":"http:\/\/www.goodmath.org\/blog\/wp-json\/wp\/v2\/posts\/294\/revisions"}],"wp:attachment":[{"href":"http:\/\/www.goodmath.org\/blog\/wp-json\/wp\/v2\/media?parent=294"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"http:\/\/www.goodmath.org\/blog\/wp-json\/wp\/v2\/categories?post=294"},{"taxonomy":"post_tag","embeddable":true,"href":"http:\/\/www.goodmath.org\/blog\/wp-json\/wp\/v2\/tags?post=294"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}