<?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 Brian Lonsdorf on Medium]]></title>
        <description><![CDATA[Stories by Brian Lonsdorf on Medium]]></description>
        <link>https://medium.com/@drboolean?source=rss-a3129fead82b------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*ha7W0K2pqWz5uiws.jpg</url>
            <title>Stories by Brian Lonsdorf on Medium</title>
            <link>https://medium.com/@drboolean?source=rss-a3129fead82b------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 24 Nov 2026 16:44:46 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@drboolean/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[Robot Show: Interview with Jessitron]]></title>
            <link>https://medium.com/@drboolean/robot-show-interview-with-jessitron-a03aa62ac156?source=rss-a3129fead82b------2</link>
            <guid isPermaLink="false">https://medium.com/p/a03aa62ac156</guid>
            <category><![CDATA[functional-programming]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[promises]]></category>
            <category><![CDATA[code]]></category>
            <dc:creator><![CDATA[Brian Lonsdorf]]></dc:creator>
            <pubDate>Mon, 05 Feb 2018 20:57:53 GMT</pubDate>
            <atom:updated>2018-02-05T20:57:53.801Z</atom:updated>
            <content:encoded><![CDATA[<iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FGuCm1f4We7E%3Ffeature%3Doembed&amp;url=http%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DGuCm1f4We7E&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FGuCm1f4We7E%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="640" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/ad9f82460307e263eee656955e8602e6/href">https://medium.com/media/ad9f82460307e263eee656955e8602e6/href</a></iframe><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a03aa62ac156" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Robot show pilot]]></title>
            <link>https://medium.com/@drboolean/robot-show-pilot-aa2e935a9500?source=rss-a3129fead82b------2</link>
            <guid isPermaLink="false">https://medium.com/p/aa2e935a9500</guid>
            <dc:creator><![CDATA[Brian Lonsdorf]]></dc:creator>
            <pubDate>Sat, 23 Dec 2017 20:41:10 GMT</pubDate>
            <atom:updated>2017-12-23T20:41:46.908Z</atom:updated>
            <content:encoded><![CDATA[<iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2Fo3lTE9SKyi8%3Ffeature%3Doembed&amp;url=http%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3Do3lTE9SKyi8&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2Fo3lTE9SKyi8%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/4cb6aad7f0f007afd76d51912c0d6b80/href">https://medium.com/media/4cb6aad7f0f007afd76d51912c0d6b80/href</a></iframe><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=aa2e935a9500" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Laziness with Representable Functors]]></title>
            <link>https://medium.com/@drboolean/laziness-with-representable-functors-9bd506eae83f?source=rss-a3129fead82b------2</link>
            <guid isPermaLink="false">https://medium.com/p/9bd506eae83f</guid>
            <category><![CDATA[functional-programming]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[functor]]></category>
            <category><![CDATA[reader-monad]]></category>
            <category><![CDATA[representable]]></category>
            <dc:creator><![CDATA[Brian Lonsdorf]]></dc:creator>
            <pubDate>Thu, 20 Jul 2017 22:01:15 GMT</pubDate>
            <atom:updated>2017-07-21T02:15:11.919Z</atom:updated>
            <content:encoded><![CDATA[<p>Recommended listening during read: <a href="https://open.spotify.com/track/1vBb916w3u10h8U87QJ1GN">https://open.spotify.com/track/1vBb916w3u10h8U87QJ1GN</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/194/1*FTPBYhBuEG-yyLqsxMfesQ.jpeg" /></figure><h4>Tl;dr</h4><p>We can convert any indexable data structure into its function form to achieve laziness. Formally, there’s an isomorphism from any Representable Functor to Reader. Gist is here: <a href="https://gist.github.com/DrBoolean/9b951c1c2cb225be9c289b0a2239132f">https://gist.github.com/DrBoolean/9b951c1c2cb225be9c289b0a2239132f</a></p><h4>Prereq</h4><p>I boldly use words like curry (functions that take 1 arg at a time), isomorphism (a lossless transformation to/from), and functor (a type with a map method)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/152/1*ulBP-PZzFNE_N3kuWJ1UNQ.jpeg" /></figure><h3>Eager Beavers</h3><p>At work we have a data structure called UI that describes our design system.</p><p>It looks like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/cc263cb860cb68ab65afda6d2ac028fa/href">https://medium.com/media/cc263cb860cb68ab65afda6d2ac028fa/href</a></iframe><p>We have tooling, a documentation site, tests, etc, that all expect this structure.</p><p>Here’s sort of how we build/use it:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ffc754270b4c35b094b307c74563b48b/href">https://medium.com/media/ffc754270b4c35b094b307c74563b48b/href</a></iframe><p>At the end of the day, we want the whole thing, but while developing with hot reload and all, we don’t want to take the time to make every component on every change since it’s pretty expensive.</p><p>Turns out a “sparse” version with the component we’re working on filled out would suffice:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/53a4e09d4190b7ff1eb7f380f9d4e038/href">https://medium.com/media/53a4e09d4190b7ff1eb7f380f9d4e038/href</a></iframe><p>Ya know, something that can be lazily generated as we go along.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/170/1*8rQCkSdP-C8PfcrQPBlbRA.jpeg" /></figure><h3>REPRESENTABLE</h3><p>A functor is dubbed Representable if it isomorphic to Function.</p><p>This tends to be the case when we have a fixed number of “slots” in our functor and we can represent it with some other type as an index. To do so, we just need an isomorphism and some other type with which to index.</p><p>Lets see a few quick examples.</p><p><em>Id</em> can be represented by <em>undefined</em> since it has 1 slot and <em>undefined</em> has 1 instance</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5e4532a1dd46dd5378393996784bf244/href">https://medium.com/media/5e4532a1dd46dd5378393996784bf244/href</a></iframe><p>See the symmetry in those type signatures of <em>to/from</em> there? In <em>to</em> we simply capture the data structure in a closure via currying and return a function that gives us the value. Going the other way, <em>from</em> just calls that function to give us back <em>Id</em><strong><em>.</em></strong></p><p><em>Pair</em> can be represented by <em>Boolean</em> since it has 2 slots and <em>Boolean</em> has 2 instances:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/625b645e87ae77b34a1d89977ae8ec60/href">https://medium.com/media/625b645e87ae77b34a1d89977ae8ec60/href</a></iframe><p>We could also choose any other type with 2 instances — it doesn’t have to be <em>Boolean </em>(though I’m partial).</p><p>So we can turn our functor into a function and back. Neat!</p><p>If you think about it, feeding a function some input to get a value is the same thing as feeding a data structure some index to get a value. So we can convert from a data structure that can be indexed, to a function which takes an index to a value.</p><p>This only works on types that don’t change shape and have a fixed number of slots.</p><p>Well that sounds perfect for our <em>UI</em> issue — instead of a full eager data structure, we can convert it to a lazy function that gets us components on demand.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/247/1*7Zd1zJRd7ggyRT_Jej7dqA.jpeg" /></figure><h3>Represent!</h3><p><em>UI</em> is already a functor since <em>Map</em> has a <em>map </em>method via Immutable.js.<br>Let’s make <em>UI</em> a representable functor by adding an index type and isomorphism:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/80d5b7bf0c7a5f7bc4b658f2e6933d74/href">https://medium.com/media/80d5b7bf0c7a5f7bc4b658f2e6933d74/href</a></iframe><p>For the index type we used the list of <em>Components</em> since we know the keys line up with the values in our <em>UI</em> (cause that’s how we build it). Formally, we’d say we <em>UI</em> is “represented by” <em>Components</em>. This is cheating a bit. Usually, you’d see a sum type like <em>Components = Alert | Button | DataTable </em>I’m fine with this morally, since we can’t be that much more type safe in plain JS anyways.</p><p>So that’s our index type. Next we defined our isomorphism (the <em>to/from</em> part).</p><p>The<em> </em><em>from</em> :: <em>(Component -&gt; a) -&gt; UI </em>function basically says “given a function from <em>Component</em> to some <em>a, </em>I’ll build up the whole <em>UI</em> structure”. We just use that same <em>reduce</em> we used to build <em>UI </em>earlier except this time, we pass the index to the provided function so we can set the value to whatever.</p><p>Now for the other way, <em>to :: UI -&gt; (Component -&gt; a).</em> Which says, given a <em>UI</em>, I can return you an index function. Currying for the win!</p><h4>Takin’ it for a spin</h4><p>Let’s change this old version:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5a89d1131296e545a35f89d1888333b2/href">https://medium.com/media/5a89d1131296e545a35f89d1888333b2/href</a></iframe><p>To this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/eb629514d94f040ea42dcbdb45175d77/href">https://medium.com/media/eb629514d94f040ea42dcbdb45175d77/href</a></iframe><p>Comparing these two, we only have to change the beginning and end bits. <em>from</em> will build up the whole <em>UI</em> structure from a function — here we just use the identity function <em>x =&gt; x</em> to recover what we had. Then we call <em>to(empty)</em> and <em>map</em> away. Note, we’re not mapping over our Immutable.Map anymore, we’re mapping over our function!</p><p>Wait, Function doesn’t have a functor instance in JS… Never fear though, we can use one more isomorphism.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/157/1*GsgGdNjiJg_O53HUhv4DOg.jpeg" /></figure><h3>Reader Monad</h3><p>The default <em>map</em> behavior for a function is simply composition. I’ve written about it before:</p><p><a href="https://medium.com/@drboolean/monoidal-contravariant-functors-are-actually-useful-1032211045c4">Monoidal Contravariant Functors are actually useful!</a></p><p>Instead of altering <em>Function.prototype</em>, we can add a wrapper we call <em>Reader</em>.</p><p>Here’s a quick implementation:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/05f799205e19333016e7814333888cda/href">https://medium.com/media/05f799205e19333016e7814333888cda/href</a></iframe><p>It simply swallows up our function so we can decorate with <em>map </em>and <em>chain </em>and stuff.</p><p>Okay now we’re all set:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/131c90089ca1011bae5d9dd1f1a3ec55/href">https://medium.com/media/131c90089ca1011bae5d9dd1f1a3ec55/href</a></iframe><p>Great! We didn’t have to do anything except throw a <em>Reader</em> around it and call <em>run</em>. Problem solved!</p><h3>Extra things to Know</h3><ul><li>Representable works on types with fixed or infinite slots, but not varying shapes or sum types in general.</li><li>Every Representable functor is distributive (like traversable) and a monad/comonad due to it being isomorphic to Reader</li><li>Sum types typically index into Product types. For further reading checkout functor Pairings and Adjunctions</li></ul><p>Full, running code is posted here: <a href="https://gist.github.com/DrBoolean/9b951c1c2cb225be9c289b0a2239132f">https://gist.github.com/DrBoolean/9b951c1c2cb225be9c289b0a2239132f</a></p><p>This was inspired by Chris Penner’s recent work. Checkout his blog <a href="http://chrispenner.ca/">http://chrispenner.ca/</a></p><p>*Artwork by Garth Jones <a href="https://www.behance.net/gallery/30375121/Sketchbook-2015">https://www.behance.net/gallery/30375121/Sketchbook-2015</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9bd506eae83f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Divide and Conquer with Algebraic Structures]]></title>
            <link>https://medium.com/@drboolean/divide-and-conquer-with-algebraic-structures-14070106fb4?source=rss-a3129fead82b------2</link>
            <guid isPermaLink="false">https://medium.com/p/14070106fb4</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[functional-programming]]></category>
            <dc:creator><![CDATA[Brian Lonsdorf]]></dc:creator>
            <pubDate>Wed, 01 Jun 2016 14:58:43 GMT</pubDate>
            <atom:updated>2016-06-01T14:58:43.206Z</atom:updated>
            <content:encoded><![CDATA[<p>Recommended listening during read:</p><p><a href="https://open.spotify.com/track/29h3NmtIybnBQDJiTM8TuB">https://open.spotify.com/track/29h3NmtIybnBQDJiTM8TuB</a></p><h4>Tl;dr</h4><p>Pure functional data structures allow us to focus on the composition of complex, effectful workflows through reasoning and interchangeable instances. We can stub functions to return these types, get the composition right, then circle back to implement the functions. Also, <strong><em>traverse</em></strong> kicks ass.</p><h4>Prereq</h4><p>To get a feel for algebraic structures see <a href="https://github.com/fantasyland/fantasy-land">https://github.com/fantasyland/fantasy-land</a>.</p><h3>Fix me a Fixture</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/491/1*Ar49YZ905liaOrIXRu7nWg.jpeg" /></figure><p>It’s no secret that I enjoy functional programming. Writing code this way typically involves two steps:</p><ol><li>Make some tiny functions</li><li>Compose those tiny functions</li></ol><p>Besides the reuse, simplicity, etc, one reason I enjoy this approach is that it enables me to focus on one part at a time — composition or the function implementation. This comes in handy when dealing with a complex function or workflow.</p><p>Consider this problem: We’d like to load these fixtures into a db and return a matching data structure of created records. So, looking at the data below, <strong><em>dino_jr</em></strong> will be our fixture name that points to an instance of the <strong><em>Band</em></strong> model and so on.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e29a9f947597aad5f620d09d44b5921b/href">https://medium.com/media/e29a9f947597aad5f620d09d44b5921b/href</a></iframe><p>What’s more, we want to replace the “<strong><em>x_id</em></strong>” references to other fixtures (e.g. <strong><em>band_id</em></strong><em> </em>and <strong><em>venue_id</em></strong> in the <strong><em>dino_stubbs </em></strong>event) with the actual database ids from the surrounding fixtures — by doing so, our ORM will take care of relationship methods.</p><p>If all goes well, we should be able to write something like:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/bb5cc7f948ed4503271145ba8f208b26/href">https://medium.com/media/bb5cc7f948ed4503271145ba8f208b26/href</a></iframe><p>Think for a minute on how you might approach this issue without pure functional data structures. Can you imagine the mutation? Callbacks firing off without warning. And the loops, oh goodness, the nested loops! I suspect it’d feel a little like tuning up a moving car.</p><h3>Composing with algebraic reasoning</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/448/1*55Jzam5TAhYLdBEduQeMrw.jpeg" /></figure><p>To tackle this issue, let’s focus on the composition rather than the functions here. We’ll need to traverse (and preserve) our data structure while inserting database records, which deals with multiple asynchronous actions. Then we’ll need to coordinate a second pass once all is created to add the relationship ids — another set of async actions.</p><p>There are a few composition hints here: We’ll need to <strong><em>traverse</em></strong> the data structure as well as coordinate (i.e. <strong><em>chain</em></strong>) a second pass. We’ll need an effect capturing type to model async.</p><blockquote>We can swap out any algebraic data structure with another and preserve compositional reasoning.</blockquote><p>To handle the async coordination, I would normally jump straight in and work with <strong><em>Task</em></strong>,<strong><em> </em></strong>which is a lazy promise (see <a href="https://github.com/folktale/data.task">https://github.com/folktale/data.task</a>)<em>.</em><strong><em> </em></strong>However, in this case, we have a complex composition and <strong><em>Task</em></strong> is a bit opaque. Not to worry, there’s a useful trick: We can swap out any algebraic data structure with another and preserve compositional reasoning.</p><p>Since we can swap types, let’s choose the benign <strong><em>Id</em></strong> type to capture effects since it is easy to inspect, then trade it in for <strong><em>Task</em></strong> once we have our composition down.</p><p>I’ll use <strong><em>Id</em></strong> from <a href="https://www.npmjs.com/package/fantasy-identities">https://www.npmjs.com/package/fantasy-identities</a> and Immutable.Map from <a href="https://www.npmjs.com/package/immutable-ext">https://www.npmjs.com/package/immutable-ext</a>.</p><h4>Mapping Maps</h4><p>How do we surgically replace nested objects while maintaining structure? Let’s try <strong><em>map:</em></strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/df88bc3b9d8b72f6ac42ef73707b1c01/href">https://medium.com/media/df88bc3b9d8b72f6ac42ef73707b1c01/href</a></iframe><p>That alters each value, but the result type: <strong><em>Map({a: Id(2), b: Id(3)}) </em></strong>is undesirable. The values are all bottled up in <strong><em>Id</em></strong> and hard to get at.</p><p><strong><em>traverse</em></strong> is a general function that’s like <strong><em>map</em></strong>, but it flips two container-like data structures around while running the transform function. So if I have, say, a <strong><em>Maybe(IO(x))</em></strong> I can get a <strong><em>IO(Maybe(x))</em></strong> or if I have a <strong><em>List(Task(x)) </em></strong>i can get <strong><em>Task(List(x)).</em></strong></p><p>Let’s look at how the function <strong><em>traverse</em></strong> works on <strong><em>Map</em></strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2983cfabcef66c17b2e42dcebd993d04/href">https://medium.com/media/2983cfabcef66c17b2e42dcebd993d04/href</a></iframe><p>By using <strong><em>traverse</em></strong> we ended up with <strong><em>Id(Map({a: 2, b: 3}))</em></strong> which is much nicer. We have one <strong><em>Id</em></strong> on the outside and all the values are left unbottled, as it were.</p><p>Keep in mind that if we replaced <strong><em>Id </em></strong>with <strong><em>Task</em></strong>,<strong><em> </em></strong>every place that’s inside the type would be async. Therefore, in this example, we’d have 1 0utter <strong><em>Task</em></strong> that would tell us when all the async work inside those objects had finished.</p><p>But this sketch, doesn’t quite match our needs. For our fixtures, we’d like to dig two levels deep and change the values while maintaining the structure.</p><p>Can we just <strong><em>traverse</em></strong> twice?</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/616cfcf041f54ca7d895ffb3ccf84ea2/href">https://medium.com/media/616cfcf041f54ca7d895ffb3ccf84ea2/href</a></iframe><p>Yes we can! We can place our inner objects into an effect capturing type and have it bubble all the way out all whilst maintaining our object structure.</p><h3>Plugging it together</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/455/1*bxKh3KYXloCjVeCF70tGJQ.jpeg" /></figure><p>So following our sketch above, we want to <strong><em>traverse</em></strong> our tables, then <strong><em>traverse</em></strong> the inner instances. Let’s write our main function, <strong><em>makeFixtures.</em></strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5407386fd6b50c4f8f945f72010eda52/href">https://medium.com/media/5407386fd6b50c4f8f945f72010eda52/href</a></iframe><p>I’ve faked a <strong><em>createRecord</em></strong> function. Since I know <strong><em>createRecord</em></strong> is going to have an effect, I stubbed it with <strong><em>Id</em></strong>. I can then circle back and implement it later. This is what that whole focusing on one thing business was about.</p><p>So at this point, we have our first pass (<strong><em>record</em></strong> is a placeholder for the db instance):</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/18d650f59895e3b2aeaa9519e904b0de/href">https://medium.com/media/18d650f59895e3b2aeaa9519e904b0de/href</a></iframe><p>Next, we have to do the whole double traversal thing again to update each record with its associations. We use <strong><em>chain</em></strong> (aka flatMap) to sequence effects. Again, I’ve faked an <strong><em>associateRels</em></strong> function for now so we can focus on composing, but it doesn’t matter what it does as long as it returns our <strong><em>Id</em></strong> type.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b5b8eb2e047c99729d7c7e2e9f315980/href">https://medium.com/media/b5b8eb2e047c99729d7c7e2e9f315980/href</a></iframe><p>Now that we’ve got the composition down, all that’s left to do is implement the functions for real and swap out <strong><em>Id</em></strong> for <strong><em>Task</em></strong>. Since they are just db writes, I won’t bore the reader with implementation.</p><h3>Conclusions</h3><p>The common apis like <strong><em>map, traverse, chain</em></strong> give us a framework of reasoning and help us compose the nasty parts like async, error handling, and loops. As we saw with <strong><em>Id</em></strong>, they even allow us to swap out one type for another.</p><p>We were able to divide and conquer in a completely different way than one might expect coming from an imperative background. Now, time to use these fixtures to write some tests!</p><p>*Art by Alevtina Khabibova</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=14070106fb4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Free(er) Monads in JS pt2]]></title>
            <link>https://medium.com/@drboolean/free-er-monads-in-js-pt2-8ab3b9efa510?source=rss-a3129fead82b------2</link>
            <guid isPermaLink="false">https://medium.com/p/8ab3b9efa510</guid>
            <category><![CDATA[scala]]></category>
            <category><![CDATA[functional-programming]]></category>
            <dc:creator><![CDATA[Brian Lonsdorf]]></dc:creator>
            <pubDate>Sat, 27 Feb 2016 17:23:41 GMT</pubDate>
            <atom:updated>2016-02-27T17:23:41.170Z</atom:updated>
            <content:encoded><![CDATA[<iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FKFCEJUjsdQg%3Ffeature%3Doembed&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DKFCEJUjsdQg&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FKFCEJUjsdQg%2Fhqdefault.jpg&amp;key=d04bfffea46d4aeda930ec88cc64b87c&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/16ce3374e8a02cc514bd8cc2c0d2b45e/href">https://medium.com/media/16ce3374e8a02cc514bd8cc2c0d2b45e/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4a4deffa23aa4ca512262854bf07ace6/href">https://medium.com/media/4a4deffa23aa4ca512262854bf07ace6/href</a></iframe><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8ab3b9efa510" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Free(er) Monads in JS]]></title>
            <link>https://medium.com/@drboolean/free-er-monads-in-js-f5a59e7abc82?source=rss-a3129fead82b------2</link>
            <guid isPermaLink="false">https://medium.com/p/f5a59e7abc82</guid>
            <dc:creator><![CDATA[Brian Lonsdorf]]></dc:creator>
            <pubDate>Fri, 26 Feb 2016 02:30:51 GMT</pubDate>
            <atom:updated>2016-02-26T15:31:26.325Z</atom:updated>
            <content:encoded><![CDATA[<iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FRkDtMeZXMTA%3Ffeature%3Doembed&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DRkDtMeZXMTA&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FRkDtMeZXMTA%2Fhqdefault.jpg&amp;key=d04bfffea46d4aeda930ec88cc64b87c&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/94a04f14b19598c2ca2e137d8f8c3ba5/href">https://medium.com/media/94a04f14b19598c2ca2e137d8f8c3ba5/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2b4707becbc0109009993bba67f53cc0/href">https://medium.com/media/2b4707becbc0109009993bba67f53cc0/href</a></iframe><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f5a59e7abc82" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Coyoneda in JS]]></title>
            <link>https://medium.com/@drboolean/coyoneda-in-js-a6565b46878c?source=rss-a3129fead82b------2</link>
            <guid isPermaLink="false">https://medium.com/p/a6565b46878c</guid>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[functional-programming]]></category>
            <dc:creator><![CDATA[Brian Lonsdorf]]></dc:creator>
            <pubDate>Sat, 20 Feb 2016 20:04:21 GMT</pubDate>
            <atom:updated>2016-02-26T15:40:47.249Z</atom:updated>
            <content:encoded><![CDATA[<iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FWH5BrkzGgQY%3Ffeature%3Doembed&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DWH5BrkzGgQY%26feature%3Dyoutu.be&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FWH5BrkzGgQY%2Fhqdefault.jpg&amp;key=d04bfffea46d4aeda930ec88cc64b87c&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/f041b73506179bb9e69397a7bcabbd33/href">https://medium.com/media/f041b73506179bb9e69397a7bcabbd33/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/29c3cf4a69c82b02b6a228508a14cb04/href">https://medium.com/media/29c3cf4a69c82b02b6a228508a14cb04/href</a></iframe><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a6565b46878c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Lenses with Immutable.js]]></title>
            <link>https://medium.com/@drboolean/lenses-with-immutable-js-9bda85674780?source=rss-a3129fead82b------2</link>
            <guid isPermaLink="false">https://medium.com/p/9bda85674780</guid>
            <category><![CDATA[lenses]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[functional-programming]]></category>
            <dc:creator><![CDATA[Brian Lonsdorf]]></dc:creator>
            <pubDate>Fri, 22 Jan 2016 02:09:17 GMT</pubDate>
            <atom:updated>2016-01-22T23:44:49.327Z</atom:updated>
            <content:encoded><![CDATA[<p>Recommended listening during read: spotify:track:3bCmDqflFBHijgJfvtqev5</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/300/1*5xHbZybS_Furw5BM3589CQ.jpeg" /></figure><h4>Tl;dr</h4><p>Lenses are pretty useful to dig deep into data structures and make changes in a pure functional way. Immutable.js and lenses are a great fit because they provide us with a universal api for working with built in and immutable data structures. We can also convert between built in and Immutable.js structures with isos which makes library interop easier.</p><h4>Prereq</h4><p>I’m going to be assuming some knowledge of ramda, which implies understanding the basics of currying and composition. If you’re not familiar, you may want to first read <a href="http://fr.umio.us/why-ramda/">http://fr.umio.us/why-ramda/</a></p><p>Here’s the import section for this post if you want to run each example*</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/016737de407f4b7cc884ee4013c26d42/href">https://medium.com/media/016737de407f4b7cc884ee4013c26d42/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/300/1*Jb0zS67TCsAkv1mJP11qaQ.jpeg" /></figure><h3>Through the Looking-Glass</h3><p>What is a lens? Well, it’s a getter/setter pair. Okay, they are more than that, but for now think of them as such. Let’s first define some data, then play around with one.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1b8d2e2a92c309c5df9e7a6ea8b315ac/href">https://medium.com/media/1b8d2e2a92c309c5df9e7a6ea8b315ac/href</a></iframe><p>This data consists of a user, Charles, who has two suspiciously simple addresses. What are you hiding, Charles?</p><h4>Basic usage</h4><p>Now we must define a lens to access properties on this data… let’s use <em>lensProp</em> to make a <em>name</em> lens.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1deeece17200db224e62bfed893b27cb/href">https://medium.com/media/1deeece17200db224e62bfed893b27cb/href</a></iframe><p>As the examples suggest, <em>name</em> does nothing on its own. It must be used with another function like <em>view, set, </em>or<em> over</em>.</p><p><em>view(name)</em> amounts to <em>prop(‘name’)</em> in this situation. What is interesting, though, is <em>set</em> and <em>over —</em> they preserve the whole data structure despite the alterations<em>. </em>They are also pure (hence, immutable) setters so we needn’t worry about bugs and the cognitive load arising from mutable state.</p><p>This isn’t the most efficient setter if you want to change hundreds of records (in that case use immutable.js like below), but it’s a great, cheap way to get an immutable change and I’ll bet it has no measurable performance difference at all in your application.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/400/1*Z74DexIGzXqJibPTKjctqA.jpeg" /></figure><h3>Composition</h3><p>Lenses compose with each other. They do so in left-to-right order, much like transducers, their <a href="https://www.reddit.com/r/haskell/comments/2cv6l4/clojures_transducers_are_perverse_lenses/">perverse</a> cousins.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/946a9bab8fa235be9b16ec707d1423d9/href">https://medium.com/media/946a9bab8fa235be9b16ec707d1423d9/href</a></iframe><p>We made a lens called <em>firstStreet </em>which is the composition of the <em>address</em>, <em>street</em>, and <em>first</em> lenses. We introduced <em>lensIndex</em> here, which does what one might expect — makes a lens that accesses the zeroth index of an array. **</p><p>What’s amazing is that we’re just using normal <em>compose, </em>which means our lenses are just functions, and indeed they are. Notice too, we can compose object accessor lenses like <em>street</em> with array lenses like <em>first. </em>Finally, witness the ease at which we perform surgery to a small piece of the nested data structure.</p><h4>Mapping</h4><p>What if we need to access our user nested inside of a functor? We can use <em>mapped</em> which is also a lens. It acts like <em>map</em>.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9f68645383fb58acd4627bcd4de88dbf/href">https://medium.com/media/9f68645383fb58acd4627bcd4de88dbf/href</a></iframe><p>Since our user is three functors deep (Task, Maybe, []), we use <em>mapped</em> 3 times to drill down to the user.</p><p>Where might all of this be useful? Let’s see a “real world” example.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/300/1*BPSkB-eNbFaVXwUj8FScUw.jpeg" /></figure><h3>The Real World</h3><p>Say we’re going to try to render a profile page with our user. For security reasons, we must remove the street number. That’s pretty real world, huh.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5420f54088a68e831e5677b487906ff3/href">https://medium.com/media/5420f54088a68e831e5677b487906ff3/href</a></iframe><p>Since the <em>over</em> function makes an immutable change while keeping our user in tact, we can update just the streets and send the whole thing off to the screen unharmed***</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/400/1*0-Ya8KRw8lGXteW9ysFizA.jpeg" /></figure><h3>Immutable.js</h3><p>Making our own lenses is fairly straight forward. We have a helper function <em>lens</em> that takes two function arguments: our getter and our setter. So if we want to make a lens that works for immutable.js we can just delegate to its <em>get </em>and <em>set</em> methods.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6c0ef87a78e02c6e3992806fad188315/href">https://medium.com/media/6c0ef87a78e02c6e3992806fad188315/href</a></iframe><p>Now we can use this lens to recreate the example above:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4b82600c0cbc37f1169009afbabc8079/href">https://medium.com/media/4b82600c0cbc37f1169009afbabc8079/href</a></iframe><p>The big win here is that we can compose getters/setters from Immutable with other getters/setters as well as lenses like <em>mapped</em>. This gives us one api to compose the world. You might also think of this as a protocol or interface for getters/setters: As a caller, I don’t need to know if I should use <em>brackets</em>, <em>dot</em>, <em>get()/set()</em>, <em>prop(), </em>etc — I can just give the lens to <em>view/set/over</em>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/300/1*RzEpySx9ZFnsCzNNk8x86w.jpeg" /></figure><h3>Isomorphisms</h3><p>An issue that comes up when working with Immutable.js is that most libraries expect built-in data structures, not things like <em>List</em> and <em>Map</em>. This forces us to convert with <em>toJS()</em> often, which is a pain.</p><p>We can define an isomorphism using <em>iso</em> that will work like a lens. Just like the <em>lens</em> helper function, it takes two arguments: a function that converts and a function that recovers. So here we can convert to and from a normal JS array to a <em>List.</em></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5d922ec3f7763e5ea7035c2f92b5fea3/href">https://medium.com/media/5d922ec3f7763e5ea7035c2f92b5fea3/href</a></iframe><p>Let’s take it for a spin:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c6e2e021f3e9e2685fff3f503471c79d/href">https://medium.com/media/c6e2e021f3e9e2685fff3f503471c79d/href</a></iframe><p>There are many isomorphisms between Immutable.js data types themselves let alone to JS and back, try to define some for fun!</p><p>In addition to <em>isos, </em>there are also <em>folds</em> and <em>traversals</em>, but we don’t have the time to go into them here. I will say that since Immutable.js structures implement <em>reduce</em>, we can use folds right out of the box (e.g. sum, max, any, etc). I should post some examples on the twitters…</p><p>*I don’t believe <a href="https://github.com/ramda/ramda-lens">https://github.com/ramda/ramda-lens</a> is on npm just yet (should be very shortly) so just point the package.json entry at the git url for now.</p><p>**@puffnfresh pointed out that <em>[]</em> does not satisfy the lens laws so <em>lensIndex(0)</em> does not qualify as a lens so that’s a misnomer. In <a href="https://hackage.haskell.org/package/lens-4.13.1/docs/Control-Lens-At.html">https://hackage.haskell.org/package/lens-4.13.1/docs/Control-Lens-At.html</a> <em>ix, </em>its analog, is considered a traversal or LensLike.</p><p>***Checkout <a href="http://joneshf.github.io/programming/2015/12/19/Lenses-and-Virtual-DOM-Support-Open-Closed.html">http://joneshf.github.io/programming/2015/12/19/Lenses-and-Virtual-DOM-Support-Open-Closed.html</a> for further examples</p><p>All artwork by: <a href="http://javierperez.ws/">http://javierperez.ws/</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9bda85674780" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Monoidal Contravariant Functors are actually useful!]]></title>
            <link>https://medium.com/@drboolean/monoidal-contravariant-functors-are-actually-useful-1032211045c4?source=rss-a3129fead82b------2</link>
            <guid isPermaLink="false">https://medium.com/p/1032211045c4</guid>
            <category><![CDATA[functional-programming]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Brian Lonsdorf]]></dc:creator>
            <pubDate>Fri, 01 Jan 2016 19:38:24 GMT</pubDate>
            <atom:updated>2016-01-05T03:53:55.827Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/213/1*Cnu3ldiVOyHtUH7Nt6Wsrw.jpeg" /></figure><h4>Tl;dr</h4><p>The tl;dr is that we can take functions that are concrete in their output, combine them with <em>concat</em>, and <em>contramap</em> over their input. This allows us to do cool things like combine filter predicates and sort comparisons while providing flexibility on their arguments. I ran out of acceptable blog post space, but it also is wonderfully useful when transducing.</p><h4>Prereq</h4><p>I expect you already know what a monoid is before reading this. If not, checkout <a href="https://www.youtube.com/watch?v=JZSoPZUoR58">https://www.youtube.com/watch?v=JZSoPZUoR58</a> to get a feel for monoids as well as transducers which I’ll touch on toward the end of this post. Also, you should be comfortable with functors before tackling contravariant ones.</p><p>Lastly, here’s a quick set of imports if you’d like to follow along. You’ll just want to <em>npm install ramda pointfree-fantasy daggy</em>. I’m using babel-node to run this locally.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8c16e934d7587b242bd6d706ec5b9d1b/href">https://medium.com/media/8c16e934d7587b242bd6d706ec5b9d1b/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/91/1*28IQR8rx5WfbAC4hPJsFng.jpeg" /></figure><h3>Covariant Functors</h3><p>The functors we’re used to are called covariant functors. We don’t normally mention the covariant part since it’s the norm.</p><p>Since contravariant functors usually hold functions, it’s helpful to know how functions are normal, covariant functors before we discuss a different type of variance.</p><h4>Function Functors</h4><p>If we think of a function as a container for an eventual value — the output we get by running the function — then mapping it would just be composition. Check it out:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2d876679dec71876ee764ebcede09be2/href">https://medium.com/media/2d876679dec71876ee764ebcede09be2/href</a></iframe><p>The functor instance is literally just composition:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/156dfac51c758953998c8f36db096364/href">https://medium.com/media/156dfac51c758953998c8f36db096364/href</a></iframe><p>The part to notice is in a function <em>(a -&gt; b)</em>, we map over the output <em>b</em>. So we get <em>(String -&gt; Int)</em>, <em>(String -&gt; Bool)</em>, etc. This trick of composing as we map works just fine because of the composition law of functors:</p><p><em>compose(map(f), map(g)) == map(compose(f, g))</em></p><p>Many functors are built this way including <em>IO</em>, <em>Task, </em>and <em>Stream</em>. Mapping simply builds up a computation to run later — kind of like the command pattern. It’s also worth mentioning the function functor is the basis of the Reader monad.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AznPt1RWSYEP9bEtgoNUyQ.png" /></figure><h3>Contravariant Functors</h3><p>With contravariant functors, we map over the <em>a</em> in <em>(a -&gt; b)</em>. In other words, the input, not the output. We usually need to do this when the <em>b</em> is a concrete type that we can’t change and the <em>a</em> is stuck inside a type already. Um. er. Let’s just look at some examples to get a feel.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/198/1*Y9BWx_nf1BGWI09Y_TA9lg.jpeg" /></figure><h4><strong>Predicates</strong></h4><p>Let’s make ourselves a <em>Pred</em> type:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4f98cd49e9c63f7db91a1f4ac42fa38b/href">https://medium.com/media/4f98cd49e9c63f7db91a1f4ac42fa38b/href</a></iframe><p>We call its one property <em>run</em> because it’s holding a function inside the type. This function must be <em>(a -&gt; Bool)</em> which is parameterized on its input, but concrete on its output. This is the typical shape of a contravariant functor as we’ll be mapping over the input, not the output.</p><p>For a type to be a contravariant functor, we must provide a method called <em>contramap :: (b -&gt; a)</em>. Here it is for <em>Pred</em>:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b2a5e7290667a49457e3afc161c63997/href">https://medium.com/media/b2a5e7290667a49457e3afc161c63997/href</a></iframe><p>Contrast this with the covariant function functor (say that 10 times quickly in a mirror to summon Kmett). It simply composes <em>g</em> beforehand, which has the effect of transforming our <em>a </em>before it gets to the <em>(a -&gt; Bool) </em>function. We’re contravariant baby!</p><p>I find it’s much cooler to see in use if we first make it a monoid so let’s do that before playing with it.</p><h4>Pred Monoid</h4><p>We’ll <em>concat</em> two <em>Pred</em>s by running both and keeping the conjunction. We should make the <em>empty</em> method always returns <em>true</em> so it acts as <em>identity</em>.</p><p>This is basically the <em>All</em> monoid under the hood. We could make it more generic by calling <em>concat</em> on the return values or parameterizing the underlying monoid, but let’s stick with this for simplicity.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c90fb3cc8eb1ecde86e67b4a6b79b96b/href">https://medium.com/media/c90fb3cc8eb1ecde86e67b4a6b79b96b/href</a></iframe><h4>Pred Examples</h4><p>Now to use this crazy thing:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/821e9b1ad6f972a66c5e7a8e3a272647/href">https://medium.com/media/821e9b1ad6f972a66c5e7a8e3a272647/href</a></iframe><p>What’s so cool about this is that we can make a flexible rule engine. We combine multiple predicate functions with <em>concat</em> and <em>map</em> over the input before we have to return the <em>Bool</em>. This isn’t specific to <em>Array</em> — we could apply this to S<em>tream</em> or <em>Tree</em> or <em>Option</em> or other types that have a <em>filter</em> method (which can be derived from any foldable monoid).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/251/1*EblHrGtR8j-wB-On9nnIIg.jpeg" /></figure><h4>Comparisons</h4><p>Time to look at a different contravariant functor. We need to do a bit of setup first, however. JavaScript’s <em>sort()</em> expects a return type of <em>1,0,-1</em>. We should make an enum to make it easier to understand and talk about this output.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ebef770ed3d5786fce1e8bf3c33d743f/href">https://medium.com/media/ebef770ed3d5786fce1e8bf3c33d743f/href</a></iframe><p>Also since we’re going to use <em>Ordering</em> directly as a monoid and we didn’t make a full on <em>Ordering</em> type wrapper, let’s just make some normal functions to act as our monoid instance.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/bffba837cec8cceead44151454bf242a/href">https://medium.com/media/bffba837cec8cceead44151454bf242a/href</a></iframe><p>That’s a weird looking monoid instance, but it’s pretty simple. If the first ordering is <em>EQ</em>, it uses the second one: <em>o2</em>. So if given to <em>sort()</em>, it acts like “sort by this, then by that”. We could formalize this further and use cool tricks like <em>valueOf</em> to make <em>Ordering</em> a type that actually works with <em>sort()</em>, but let’s get to the good stuff.</p><h4>Comparison Type</h4><p>Here’s the definition:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/352502d5d1f4291bff9380cacb372031/href">https://medium.com/media/352502d5d1f4291bff9380cacb372031/href</a></iframe><p>Just like <em>Pred</em>, we have a function inside which we’ll call <em>compare</em>. This function is concrete on its output, but not its input so we know it’d be useful as a contravariant functor. Let’s make it so:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b09a62710b490646f493d0985b00f4ec/href">https://medium.com/media/b09a62710b490646f493d0985b00f4ec/href</a></iframe><p>Check it out — we hit both our inputs with <em>f</em> before comparing. In effect, we map over our input and keep the concrete output. Again, the monoid instance makes this infinitely cooler, so let’s use our <em>Ordering</em> stuff to make it happen before playing with it.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/99c4eacbd4901824beb9bc5897985644/href">https://medium.com/media/99c4eacbd4901824beb9bc5897985644/href</a></iframe><p>We just defer to our previous <em>Ordering</em> monoid under the hood. So this will act like “sort by this, then by that” when we <em>concat </em>two<em> Comparison</em>s<em>.</em></p><h4>Comparison Examples</h4><p>Now let’s play around with our <em>Comparison</em> type. I think it’d be interesting to sort by a specific set of rules.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/27d2c853a274c5e64d3c82c33a96ac96/href">https://medium.com/media/27d2c853a274c5e64d3c82c33a96ac96/href</a></iframe><p>We’re using a standard JS <em>sort()</em> here. This can almost certainly be made nicer by using a <em>sortBy(f)</em> function that understands <em>Ordering </em>(perhaps by using a <em>valueOf</em> trick). In any case, we can combine and sort by our blackjack rules. But what if we don’t have <em>Int</em>’s? <em>contramap</em> to the rescue:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/bd8857d780815df7f94a8cfc636b030e/href">https://medium.com/media/bd8857d780815df7f94a8cfc636b030e/href</a></iframe><p>Check that out! We can convert our cards to ints before comparing them. Mapping input ftw!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/161/1*1vroCM8RwzVea5AOIn2myg.jpeg" /></figure><h3>Conclusion…or is it?</h3><p>I wanted to talk about how transducers are monoidal contravariant functors, but this post is pretty long as it is. I’ll probably write a follow up post soon on that, but if you want to see the example, here is a gist link (they’re at the bottom): <a href="https://gist.github.com/DrBoolean/fdef9e08352ac42754f1">https://gist.github.com/DrBoolean/fdef9e08352ac42754f1</a></p><p>I hope this post helped you gain an intuition about contravariant functors. There are many more instances out there so keep an eye out!</p><p>*Artwork by Olle Eksell via <a href="http://www.doodlersanonymous.com/">http://www.doodlersanonymous.com/</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1032211045c4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Debugging Functional]]></title>
            <link>https://medium.com/@drboolean/debugging-functional-7deb4688a08c?source=rss-a3129fead82b------2</link>
            <guid isPermaLink="false">https://medium.com/p/7deb4688a08c</guid>
            <category><![CDATA[functional-programming]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[debugging]]></category>
            <dc:creator><![CDATA[Brian Lonsdorf]]></dc:creator>
            <pubDate>Tue, 06 Oct 2015 19:02:33 GMT</pubDate>
            <atom:updated>2016-06-09T00:20:19.556Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/99/1*gFheg9J4BST0pxHboj9dog.jpeg" /></figure><h3>What’s the problem</h3><p>When working with <a href="http://ramdajs.com/">ramda</a> or <a href="https://github.com/lodash/lodash-fp">lodash-fp</a>, one may run into some rather cryptic error messages. When trying to console.log a function we’re presented with the guts of some internal curry or compose implementation that tells us nothing. At <a href="http://looprecur.com/">Loop/Recur</a> we enjoy working with Functional JavaScript so I’d like to see this improve.</p><p>This post will demonstrate a simple solution that can go a long way to enhance the debugging experience in functional JavaScript applications.</p><h3>Test subjects</h3><p>Here are some simple functions to use in our tests. Two are named and curried, one is anonymous.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0245a1e6db70076c62e85e2244f0bb72/href">https://medium.com/media/0245a1e6db70076c62e85e2244f0bb72/href</a></iframe><h3>Fixing Curry</h3><p>Here’s a simple curry implementation I took from <a href="http://blog.carbonfive.com/2015/01/14/gettin-freaky-functional-wcurried-javascript/">Erin Swenson-Healey’s post</a></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ee4e64f33309f894d852ffcfe0f8a11e/href">https://medium.com/media/ee4e64f33309f894d852ffcfe0f8a11e/href</a></iframe><p>Let’s make an <em>inc</em> function that just adds 1, then we’ll inspect it with <em>console.log</em>:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a84fc735d024ef68cbdee5ecd776f338/href">https://medium.com/media/a84fc735d024ef68cbdee5ecd776f338/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/98/1*8g8LLIEqmHt6q2O8OMpYZQ.jpeg" /></figure><p>Riiiiigghhhht. That’s not really all that helpful. It would be lovely to see <em>add</em> and its argument <em>1</em> somewhere so I know what’s going on.</p><p>Let’s fix this up. The trick is to overwrite<em> toString()</em> and have it refer to the original function (called <em>fx</em> here). Then we’ll log out the args that are applied.</p><p>Here’s the important bit (I’ll show it all together when we’re finished).</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a6d5a00baa447330d8745914d418c7ec/href">https://medium.com/media/a6d5a00baa447330d8745914d418c7ec/href</a></iframe><p>In the words of daft punk, one more time:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/739dcbaaf3bc02bd5982f8aaf2a3db22/href">https://medium.com/media/739dcbaaf3bc02bd5982f8aaf2a3db22/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/116/1*-OJOCDcQCCM7Gd_UeIuMfQ.jpeg" /></figure><p>Wow, that’s so much more helpful than displaying curry’s implementation. What if we don’t apply it at all though?</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/cf2673af1bf1380362e4530100a71287/href">https://medium.com/media/cf2673af1bf1380362e4530100a71287/href</a></iframe><p>Doh! We’ll need to also overwrite <em>f1.toString()</em>, which will simply be <em>fx.toString()</em>.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4038be39d819bc1c3da54f163b51bd4a/href">https://medium.com/media/4038be39d819bc1c3da54f163b51bd4a/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c48d20fb73bd4a43a68d8246692800d9/href">https://medium.com/media/c48d20fb73bd4a43a68d8246692800d9/href</a></iframe><p>Great! We can inspect the actual underlying function in all cases. Now, let’s look at a slightly more complicated example:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/77194bd55a0e08c46e1af2efbfd52842/href">https://medium.com/media/77194bd55a0e08c46e1af2efbfd52842/href</a></iframe><p>Here, <em>map</em> and <em>inc</em> are both partially applied functions. The output is alright, but like an antique contact lens, it’s a little hard on the eyes. If we named the functions, why not show that instead?</p><p>Here’s a helper:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/824d083a6508fc58b7aad0390d7b6ed5/href">https://medium.com/media/824d083a6508fc58b7aad0390d7b6ed5/href</a></iframe><p>Now we can output a very nice inspection of the currying going down:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6fd5d448809a128de0797c6e95b1b80c/href">https://medium.com/media/6fd5d448809a128de0797c6e95b1b80c/href</a></iframe><p>Here’s the improved <em>curry</em> in all its debuggable glory:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1d90ef028f4e2a1820139d2e6932b57c/href">https://medium.com/media/1d90ef028f4e2a1820139d2e6932b57c/href</a></iframe><h3>Fixing Compose</h3><p>We can inspect functions made via <em>compose()</em> with the same trick.</p><p>I’ll steal a simple <em>compose</em> from <a href="http://blakeembrey.com/articles/2014/01/compose-functions-javascript/">Blake Embrey’s post</a>. By the way, I chose these two implementations of <em>curry</em> and <em>compose</em> because they were the first search results and seemed simple enough. The ones in ramda and lodash are optimized and thus more complicated.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/108a1416b0dbf2617b206ac9ef927839/href">https://medium.com/media/108a1416b0dbf2617b206ac9ef927839/href</a></iframe><p>We end up in compose’s messy bedroom if we try to inspect our function:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/88dd66c6804f48d6ca46734e3247459d/href">https://medium.com/media/88dd66c6804f48d6ca46734e3247459d/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/187/1*UI3ETO5_ODC72hGRMqE2Rw.jpeg" /></figure><p>That’s not very friendly. Let’s use our new favorite debugging tool: <em>toString()</em></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7677e23da47e7dafa26448edc431f7ac/href">https://medium.com/media/7677e23da47e7dafa26448edc431f7ac/href</a></iframe><p>This is a little more complicated because we have to slice the arguments object and stringify each function. Let’s take it for a spin:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7dbced6c040a047766ce200250205ca0/href">https://medium.com/media/7dbced6c040a047766ce200250205ca0/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/100/1*XKkPVKs07SE0QSBHbQeOwA.jpeg" /></figure><p>Since <em>map</em> and <em>add</em> are curried, they are using our previous<em> toString()</em>. We just output the normal <em>toString()</em> for <em>head</em>.</p><p>This approach works particularly well if we are composing other compositions — as one does in this paradigm.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/646d3817aa53e8aa1d4811783f765377/href">https://medium.com/media/646d3817aa53e8aa1d4811783f765377/href</a></iframe><p>It inlines our composition nicely. We can do extra fancy tricks to pretty print, but this is already a huge improvement over the opaque innards of <em>compose</em>.</p><h3>Approaching perfection</h3><p>There’s one very common error when using <em>compose</em>. Often times, we give it something other than a function. This typically occurs when we either forget to partially apply a function of multiple arguments or we accidentally apply a function with all its arguments.</p><p>To demonstrate:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/31b809335c03d7f5b80218137b001152/href">https://medium.com/media/31b809335c03d7f5b80218137b001152/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/157/1*kf2xivpWFTWAV6W8NnU2Ww.jpeg" /></figure><p>We’ve called <em>add</em> with two arguments, returning a value rather than a function to <em>compose</em> (yes I know functions are values too…).</p><p>Let’s catch this error and throw a better message:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4f0a639d18e87b3e2694f552eb7685f4/href">https://medium.com/media/4f0a639d18e87b3e2694f552eb7685f4/href</a></iframe><p>Let’s try this again:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2da3061c94baff5ea2410d0e1390ee7d/href">https://medium.com/media/2da3061c94baff5ea2410d0e1390ee7d/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/97/1*8hRJqui-MwZA0lauunEXdg.jpeg" /></figure><p>Much nicer to see what’s going on here. Of course, types would prevent this in the first place, but then I’d suggest using Elm or PureScript instead of messing with any of this stuff.</p><h3>In closing</h3><p>We can overwrite the string values in order to display better errors. This is a significant improvement over the current state of affairs and I think all JavaScript FP libraries should incorporate better debugging in general.</p><p>We could use this to show memoized functions in a sane way. The same technique can be used to display the inner value of functors and monads as well (shown <a href="https://github.com/folktale/data.maybe/blob/master/lib/maybe.js#L261,">here</a> though it should be recursive).</p><p>When I feel writey, I’m still working on the <a href="https://github.com/MostlyAdequate/mostly-adequate-guide">Mostly Adequate Guide</a> if you’re into this junk. G’day.</p><p>*Artwork by Alexandria Gold <a href="http://riaartworld.tumblr.com/page/2">http://riaartworld.tumblr.com</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7deb4688a08c" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>