{"id":292,"date":"2007-01-29T08:00:01","date_gmt":"2007-01-29T08:00:01","guid":{"rendered":"http:\/\/scientopia.org\/blogs\/goodmath\/2007\/01\/29\/more-monads-stateful-programming\/"},"modified":"2007-01-29T08:00:01","modified_gmt":"2007-01-29T08:00:01","slug":"more-monads-stateful-programming","status":"publish","type":"post","link":"http:\/\/www.goodmath.org\/blog\/2007\/01\/29\/more-monads-stateful-programming\/","title":{"rendered":"More Monads: Stateful Programming"},"content":{"rendered":"<p> Time for more monads. In this article, I&#8217;m going to show you how to implement a very simple<br \/>\n<em>state monad<\/em> &#8211; it&#8217;s a trivial monad which allows you to use a mutable state<br \/>\nconsisting of a single integer. Then we&#8217;ll expand it to allow a more interesting<br \/>\nnotion of state.<\/p>\n<p><!--more--><\/p>\n<p> Let&#8217;s get the trivial stuff out of the way. To start off, we&#8217;ll use a simple fixed<br \/>\nstate type which is just a wrapper for a single integer<\/p>\n<pre>\n&gt;data State = State Int deriving (Show)\n<\/pre>\n<p> A monad over that would be written:<\/p>\n<pre>\n&gt;data SimpleStateMonad a = SSMon (State -&gt; (a,State))\n<\/pre>\n<p> To understand that, just remember that the monad is really a <em>transition function<\/em> for<br \/>\nexecuting a sequence of computations that use a state. In fact, we&#8217;ll describe the sequence of steps<br \/>\nchained together that way as a single monad operation as a <em>monadic sequence<\/em>. In a monadic sequence, each step of the computation is going to take the current state, do something with it, and return both a value and an updated state.<\/p>\n<p> Given the monad type &#8211; the basic type of the step function for the sequences we want to build &#8211; the first thing that we need to do is implement the fundamental monadic operators. There are two of them: the sequencing operator <code>(&gt;&gt;=)<\/code>, and the <code>return<\/code> function that brings a non-monadic value into a monad.<\/p>\n<p> We&#8217;ll implement the <code>(&gt;&gt;=)<\/code> operator, which we&#8217;ll implement as a function named <em>chain<\/em>:<\/p>\n<pre>\n&gt;chain :: (SimpleStateMonad a) -&gt; (a -&gt; SimpleStateMonad b)\n&gt;          -&gt; SimpleStateMonad b\n&gt;chain (SSMon state) stepfun =\n&gt;      SSMon (s -&gt; let (carried, stateBefore) = state s\n&gt;                       SSMon stateMonadAfter = stepfun carried\n&gt;                   in stateMonadAfter stateBefore)\n<\/pre>\n<p> The way that <code>chain<\/code> works is crucial, and so we&#8217;ll take some time and tease it apart. Chain is a function that takes the result of the previous computation step of the sequence, and<br \/>\nchains it into the next step of the sequence. The way to understand the code is to look at the basic<br \/>\npieces, and how they&#8217;re put together:<\/p>\n<ul>\n<li> The first binding of the let: <code>(carried,stateBefore) = state s<\/code>. This looks<br \/>\nmysterious &#8211; so we&#8217;ll take the time to look at it carefully. <code>state<\/code> is the<br \/>\nfunction inside of the monad that carries hidden monadic state and the result of the previous<br \/>\nstep. So all we&#8217;re really doing here is unwrapping the results of the <em>previous<\/em> step &#8211; extracting the state and the return values, and binding them to separate variables. <code>carried<\/code> is the result of the previous step, and <code>stateBefore<\/code> is the<br \/>\nstate returned by the previous step &#8211; that is, the state <em>before<\/em> we chain in<br \/>\nthe next step of the monadic sequence.<\/li>\n<li> The second binding of the let: <code>SSMon stateMonadAfter = stepfun carried<\/code>. Again,<br \/>\nit looks mysterious, but it&#8217;s really pretty simple. The monad is a step function &#8211; we&#8217;re<br \/>\ncreating a step function <em>from<\/em> the result of the previous step, so that we can<br \/>\nuse that to run the next step. <code>stepfun carried<\/code> is just a function which<br \/>\npasses the state and return value of the first step into the second step of our<br \/>\nchain.<\/li>\n<li> The main expression of the let: <code>stateMonadAfter stateBefore<\/code>. This just<br \/>\nruns the step function we generated on the result of the previous step.<\/li>\n<li> The &lambda; wrapping the whole shebang: monads are a bit of a trap &#8211; you don&#8217;t<br \/>\nget to get out of them without using a type-specific operation that isn&#8217;t part of the<br \/>\nmonad class. The monadic chain operator needs to result in a monad value &#8211; the wrapping<br \/>\nlambda expression just encapsulates the stepping sequence we&#8217;ve built into a monadic<br \/>\nfunction wrapper.<\/li>\n<\/ul>\n<p> Return is trivial, so we&#8217;ll just write it inline in the declaration of our monad type as an instance of the monad typeclass. The typeclass declaration looks like:<\/p>\n<pre>\n&gt;instance Monad SimpleStateMonad where\n&gt;    statemonad &gt;&gt;= statefun = chain statemonad statefun\n&gt;    return nonMonadValue = SSMon (state -&gt; (nonMonadValue, state))\n<\/pre>\n<p> Nothing complicated there. The next thing we need to do is to write some functions usable<br \/>\n<em>inside<\/em> of a monadic computation to access and update the state hidden inside the<br \/>\nmonad. Let&#8217;s start with retrieving the state value:<\/p>\n<pre>\n&gt;getState :: SimpleStateMonad Int\n&gt;getState = SSMon (s@(State i) -&gt; (i,s))\n<\/pre>\n<p> That&#8217;s it! It&#8217;s just a monadic step function that takes the value hidden in the state,<br \/>\nand puts it into the &#8220;return value&#8221; slot of the monad result. So the monadic state is<br \/>\nunmodified, and the result passed to the next state is the value that was wrapped up in the monad.<\/p>\n<p> Updating is almost as easy:<\/p>\n<pre>\n&gt;putState ::  (Int -&gt; Int) -&gt; SimpleStateMonad ()\n&gt;putState updateFun =\n&gt;     let stateUpdateFun = ((State i)  -&gt; State (updateFun i))\n&gt;     in SSMon (s -&gt; ((), stateUpdateFun s))\n<\/pre>\n<p> <code>putState<\/code> takes a function that performs a modification of the state value. Since<br \/>\nwe want people to treat the state as an integer, we do a little bit of wrapping, to translate an <code>Int -&gt; Int<\/code> function to a <code>State -&gt; State<\/code> function. The real meat is just<br \/>\nexecuting the state update function to produce the new state value, and wrapping it up in a monad<br \/>\nthat returns the unit value and the updated state.<\/p>\n<p> Finally, we need a function that takes an initial state value, and a monadic sequence of operations, and executes the monadic sequence starting with the state value.<\/p>\n<pre>\n&gt;runWithState :: Int -&gt; SimpleStateMonad a -&gt;  (a,State)\n&gt;runWithState f (SSMon c) = c (State f)\n<\/pre>\n<p> And voila! We have a state monad. Let&#8217;s try a simple test of it. Here&#8217;s<br \/>\na monadic sequence that plays with the state a bit.<\/p>\n<pre>\n&gt;testState :: SimpleStateMonad Int\n&gt;testState = do\n&gt;\t           putState (3*)\n&gt;\t           putState (1+)\n&gt;\t           i \t           return (i+2)\n<\/pre>\n<p> Running that in GHCI gives us:<\/p>\n<pre> *Main&gt; runWithState 3 testState\n(12,State 10)\n*Main&gt; runWithState 10 testState (33,State 31)\n*Main&gt;\n<\/pre>\n<p> I ran it twice, with different values for the initial state. The code takes whatever the initial<br \/>\nstate is, multiplies it by three, and adds one. That&#8217;s the final value of the state. And then the do<br \/>\nblock finishes with a value of the current state plus two. What&#8217;s actually returned at the end of the<br \/>\ndo block is a pair of the return value of the last statement in the block, and the final state. As  you can see, it does exactly the right thing. It looks almost like a piece of imperative code,<br \/>\nexcept that the &#8220;assignment&#8221; operator, <code>putState<\/code> takes a function on the current<br \/>\nvalue of the state instead of just a new value.<\/p>\n<p> So, now we&#8217;ve seen the basic method that we can use t make a monad that can encapsulate a kind of<br \/>\nstate. But so far, it&#8217;s a pretty trivial kind of state: how much good is one integer? Suppose we<br \/>\nwanted something more than that. In fact, suppose we wanted an arbitrary set of named variables<br \/>\nencapsulated in a state. We do almost the same thing as the simple state monad; we just use a more<br \/>\ncomplicated value inside the monad, and a different set of functions for working with the value in<br \/>\nthe state. We&#8217;ll start by just building a trivial <em>non-monadic<\/em> implementation of a name\/value<br \/>\nlist.<\/p>\n<pre>\n&gt;type NameValueMap = [(String,Int)]\n&gt;\n&gt;getValueFromList :: NameValueMap -&gt; String -&gt; Int\n&gt;getValueFromList ((n,v):rest) name\n&gt;             | n == name = v\n&gt;              otherwise = getValueFromList rest name\n&gt;getValueFromList [] name = -1\n&gt;\n&gt;setValueInList :: NameValueMap -&gt; String\n-&gt; Int -&gt; [(String,Int)]\n&gt;setValueInList ((n,v):rest) name newval\n&gt;          | n == name = ((n,newval):rest)\n&gt;          | otherwise = ((n,v):(setValueInList rest name newval))\n&gt;setValueInList [] name newval = [(name,newval)]\n<\/pre>\n<p> Now, we&#8217;re going to wrap that as a monad. The declaration of the monad type<br \/>\nand the chain and return functions are going to be essentially identical to the integer<br \/>\nstate monad.<\/p>\n<pre>\n&gt;data MapStateMonad a = MapMon (NameValueMap -&gt; (a,NameValueMap))\n&gt;\n&gt;mchain :: (MapStateMonad a) -&gt;\n&gt;          (a -&gt; MapStateMonad b) -&gt;\n&gt;          MapStateMonad b\n&gt;mchain (MapMon state) stepfun =\n&gt;        MapMon (s -&gt; let (carried, stateBefore) = state s\n&gt;                          MapMon stateMonadAfter = stepfun carried\n&gt;                      in stateMonadAfter stateBefore)\n&gt;\n&gt;\n&gt;instance Monad MapStateMonad where\n&gt;    statemonad &gt;&gt;= statefun = mchain statemonad statefun\n&gt;    return nonMonadValue =\n&gt;            MapMon (state -&gt; (nonMonadValue, state))\n<\/pre>\n<p> Here&#8217;s where we do something a little bit different. Instead of having &#8220;getState&#8221; and &#8220;putState&#8221; functions for working on the state in the monad, we need operations that fit the new name-map state.<\/p>\n<pre>\n&gt;getFromState :: String -&gt; MapStateMonad Int\n&gt;getFromState name =\n&gt;      MapMon (statemap -&gt; (getValueFromList statemap name,\n&gt;                            statemap))\n&gt;\n&gt;setInState :: String -&gt; Int -&gt; MapStateMonad ()\n&gt;setInState  name newval =\n&gt;       MapMon (statemap -&gt;\n&gt;                   ((),\nsetValueInList statemap name newval))\n<\/pre>\n<p> And, just as in the case of the simple integer state monad, we need a way of running a monadic sequence with a particular initial state. And while we&#8217;re at it, we&#8217;ll write a test sequence.<\/p>\n<pre>\n&gt;runWithMapState :: NameValueMap -&gt;\n&gt;                   MapStateMonad a -&gt;\n&gt;                   (a,NameValueMap)\n&gt;runWithMapState f (MapMon c) = c f\n&gt;\n&gt;testMapMonad = do\n&gt;                  setInState \"x\" 3\n&gt;                  setInState \"y\" 5\n&gt;                  z                   x                   return (x*z)\n<\/pre>\n<p> Now, aside from a bit of syntax, <em>that<\/em> looks like an imperative program, doesn&#8217;t it? Except that we&#8217;ve implemented it in a pure functional way &#8211; using a hidden state parameter. That&#8217;s the basic idea of what we do with monads &#8211; they allow us to create mini-languages with different<br \/>\nsemantics based on the idea of chaining things together into monadic sequences. We write most of the program in the general functional language; but when we need to, we have multiple custom languages at our disposal in the form of the monad system. We can easily use monads for IO, for imperative programming, for Prolog-style backtracking, for non-determinism&#8230; All there,  in Monads.<\/p>\n<p> Next up, we&#8217;ll look at the theory of monads: what they are in category theory, and how that relates to  what we&#8217;ve seen in programming, and what rules are required by the monadic semantics to make a new monad work correctly.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>Time for more monads. In this article, I&#8217;m going to show you how to implement a very simple state monad &#8211; it&#8217;s a trivial monad which allows you to use a mutable state consisting of a single integer. Then we&#8217;ll expand it to allow a more interesting notion of state.<\/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":[89],"tags":[],"class_list":["post-292","post","type-post","status-publish","format-standard","hentry","category-haskell"],"jetpack_publicize_connections":[],"jetpack_featured_media_url":"","jetpack_shortlink":"https:\/\/wp.me\/p4lzZS-4I","jetpack_sharing_enabled":true,"jetpack_likes_enabled":true,"_links":{"self":[{"href":"http:\/\/www.goodmath.org\/blog\/wp-json\/wp\/v2\/posts\/292","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=292"}],"version-history":[{"count":0,"href":"http:\/\/www.goodmath.org\/blog\/wp-json\/wp\/v2\/posts\/292\/revisions"}],"wp:attachment":[{"href":"http:\/\/www.goodmath.org\/blog\/wp-json\/wp\/v2\/media?parent=292"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"http:\/\/www.goodmath.org\/blog\/wp-json\/wp\/v2\/categories?post=292"},{"taxonomy":"post_tag","embeddable":true,"href":"http:\/\/www.goodmath.org\/blog\/wp-json\/wp\/v2\/tags?post=292"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}