<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Robbie Langer on Medium]]></title>
        <description><![CDATA[Stories by Robbie Langer on Medium]]></description>
        <link>https://medium.com/@robbie0630?source=rss-58d5d217a15e------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*VsFpPPwTldJzlliez8eI0g.jpeg</url>
            <title>Stories by Robbie Langer on Medium</title>
            <link>https://medium.com/@robbie0630?source=rss-58d5d217a15e------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 05 Dec 2026 07:44:21 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@robbie0630/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Dissecting the State monad with Operational and Free monads]]></title>
            <link>https://medium.com/@robbie0630/dissecting-the-state-monad-with-operational-and-free-monads-3b965479f13c?source=rss-58d5d217a15e------2</link>
            <guid isPermaLink="false">https://medium.com/p/3b965479f13c</guid>
            <category><![CDATA[haskell]]></category>
            <category><![CDATA[functional-programming]]></category>
            <category><![CDATA[monads]]></category>
            <dc:creator><![CDATA[Robbie Langer]]></dc:creator>
            <pubDate>Fri, 02 Feb 2018 03:18:20 GMT</pubDate>
            <atom:updated>2018-02-03T23:21:24.712Z</atom:updated>
            <content:encoded><![CDATA[<p>Note: It is highly recommended that you understand the State monad before reading this article.</p><p>The State monad almost feels magical, with its ability to seemingly mutate a value in-place. However, I will walk you through the steps to build your own State monad using two different methods, namely operational and free monads.</p><h3>Part 1: Operational Monads</h3><p>An operational monad allows you to build your own custom monad using a set of primitive instructions. One is provided in the operational package, and it is called Program .</p><p>First, you have to import the Control.Monad.Operational module. Now let’s get crackalackin!</p><h4>Creating the primitives</h4><p>We are going to use a GADT (generalized algebraic datatype) called StateCmd to represent the primitives. This is available through the GHC extension -XGADTs . If you don’t know what a GADT is, think of it as a normal algebraic datatype where the constructors are specialized to different types. That probably didn’t help you, so let’s show what the type will look like:</p><pre>data StateCmd s a where<br>  Get :: StateCmd s s<br>  Put :: s -&gt; StateCmd s ()</pre><p>This implements the Get and Put primitives from the State monad. Now, we’re going to create the State monad!!!</p><pre>type State s a = Program (StateCmd s) a</pre><p>I know you absolutely want to implement the runState function to tear this little h*cker down, but we have to make a couple helper functions to make the primitives usable.</p><pre>get :: State s s<br>get = singleton Get</pre><pre>put :: s -&gt; State s ()<br>put x = singleton (Put x)</pre><p>It would be an absolute waste of time to keep typing singleton before each command, so whether you like it or not, we’re creating these functions.</p><h4>Creating runState</h4><p>The operational package provides a function called view to split the program into the head instruction and a continuation to the rest of the program. (Also, it provides a Return constructor to signify the end of the program.) Let’s show this in action:</p><pre>runState :: State s a -&gt; s -&gt; (a, s)<br>runState p s = case (view p) of<br>  Return x -&gt; (x, s)<br>  Get :&gt;&gt;= k -&gt; runState (k s) s<br>  Put x :&gt;&gt;= k -&gt; runState (k ()) x</pre><p>In English, this has three cases for the view: the Return case, where the program is over; the Get case, where the program is requesting the current state; and the Put case, where the program is requesting that the current state be changed. The continuation that is passed in the non-Return cases is how the runState function responds to the program’s requests.</p><h4>Wrapping up and trying it out</h4><p>Our operational State monad is fully implemented. Now, let’s do something cool with it! We’re going to implement a fibonacci function using this slightly modified example from the Haskell wiki:</p><pre>import Control.Monad (forM_)</pre><pre>fib&#39; :: (Integral a) =&gt; a -&gt; State (a, a) a<br>fib&#39; n = do<br>  forM_ [1..n] $ \_ -&gt; do<br>    (a, b) &lt;- get<br>    put (b, a+b)<br>  (a, b) &lt;- get<br>  return a<br><br>fib :: (Integral a) =&gt; a -&gt; a<br>fib n = fst $ runState (fib&#39; n) (0, 1)</pre><p>Run this example with your custom State monad, and it should work perfectly!</p><h3>Part 2: Free Monads</h3><p>Very similar and closely related to operational monads, I present you free monads. A free monad is a monad where everything about it is inferred from its Functor instance. You may wonder where we are going to get a functor from. The functor is in the primitives! Let’s add Control.Monad.Free to the imports.</p><h4>Creating the primitives</h4><p>Unlike the operational monad, where we used a GADT, we are simply going to use a normal datatype, which looks like this:</p><pre>data StateCmd s a = Get (s -&gt; a) | Put s a</pre><p>Unlike in the operational monad, where it created the continuations for us, we have to explicitly specify them. Now we are going to create the functor instance:</p><pre>instance Functor (StateCmd s) where<br>  fmap f (Get k) = Get (f . k)<br>  fmap f (Put x k) = Put x (f k)</pre><p>If this makes you uncomfortable, bored, tired, or nauseous, you can use the -XDeriveFunctor GHC extension, where you can simply add deriving (Functor) to the end of the datatype declaration. Now, we shall define the State monad:</p><pre>type State s a = Free (StateCmd s) a</pre><p>If this looks similar to the definition of the State operational monad, that’s because operational and free monads are similar. Now, unlike the operational monad, where you had to manually define the monadic primitives, the free monad has a Template Haskell helper function to create those automatically. (This requires the -XTemplateHaskell and -XFlexibleContexts GHC extensions. Don’t worry, these are the last extensions.) To do that, simply add Control.Monad.Free.TH to your imports, and add this line after the State declaration:</p><pre>makeFree &#39;&#39;StateCmd</pre><p>This automatically creates the get and put functions. How cool is that?!</p><h4>Creating runState</h4><p>Unlike operational monads, where you had to view the program to get the latest instruction, the Free monad <em>is</em> the instructions. (The analogue of Return in the operational monad is Pure in the free monad, as with (:&gt;&gt;=) and the somewhat confusingly-namedFree.) Let’s try it out:</p><pre>runState :: State s a -&gt; s -&gt; (a, s)<br>runState p s = case p of<br>  Pure x -&gt; (x, s)<br>  Free (Get k) -&gt; runState (k s) s<br>  Free (Put x k) -&gt; runState k x</pre><p>Notice how you don’t have to explicitly pass in the unit () in the Put case, because the free monad does that for you.</p><h4>Wrapping up and trying it out</h4><p>Now that we’ve finished the free State monad, try out the fibonacci example from earlier in the operational example.</p><h3>Final notes</h3><p>I hope you learned something about how the State monad works, and how to use operational and free monads!</p><p>The code can be found at a GitHub gist <a href="https://gist.github.com/robbie0630/20971ba51e09fdc82331ac3482ae69d8">here</a>!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3b965479f13c" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>