<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <channel>
    <title>DEV Community: Hadrian Hughes</title>
    <description>The latest articles on DEV Community by Hadrian Hughes (@hadrianhughes).</description>
    <link>https://dev.to/hadrianhughes</link>
    <image>
      <url>https://media2.dev.to/dynamic/image/width=90,height=90,fit=cover,gravity=auto,format=auto/https:%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Fuser%2Fprofile_image%2F363476%2Fd04ceba7-b6a9-454c-add4-0ac5974304c4.png</url>
      <title>DEV Community: Hadrian Hughes</title>
      <link>https://dev.to/hadrianhughes</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://dev.to/feed/hadrianhughes"/>
    <language>en</language>
    <item>
      <title>Understanding applicatives in Haskell</title>
      <dc:creator>Hadrian Hughes</dc:creator>
      <pubDate>Wed, 10 Apr 2024 00:00:00 +0000</pubDate>
      <link>https://dev.to/hadrianhughes/understanding-applicatives-in-haskell-1g2a</link>
      <guid>https://dev.to/hadrianhughes/understanding-applicatives-in-haskell-1g2a</guid>
      <description>&lt;p&gt;My previous post was about the problem of parsing left-recursive grammars when using the parser combinator pattern in Haskell. In my code examples, I made extensive use of applicatives but didn't explain what they are or how they work. This was partially because their syntax is fairly intuitive when applied to parser construction, but also because I hadn't really grokked them myself---I was relying heavily on that intuitiveness without properly understanding what I was doing. So, I decided to take a deeper look at applicatives, what they are and how they work.&lt;/p&gt;

&lt;p&gt;Rather than defining applicatives from the get-go, I'll present how they're used by parser libraries, as this is the way I first became properly aware of them.&lt;/p&gt;

&lt;p&gt;Let's say we're building a programming language, and we want to be able to declare variables in the style of C---for example, we might declare an integer like &lt;code&gt;int x;&lt;/code&gt;. To represent this in the AST, we might create a type like so:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight haskell"&gt;&lt;code&gt;&lt;span class="kr"&gt;data&lt;/span&gt; &lt;span class="kt"&gt;VarDecl&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="kt"&gt;VarDecl&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt; &lt;span class="n"&gt;varType&lt;/span&gt; &lt;span class="o"&gt;::&lt;/span&gt; &lt;span class="kt"&gt;String&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;varName&lt;/span&gt; &lt;span class="o"&gt;::&lt;/span&gt; &lt;span class="kt"&gt;String&lt;/span&gt; &lt;span class="p"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Then to parse this kind of expression, we might create a parser like so:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight haskell"&gt;&lt;code&gt;&lt;span class="n"&gt;varDeclP&lt;/span&gt; &lt;span class="o"&gt;::&lt;/span&gt; &lt;span class="kt"&gt;Parser&lt;/span&gt; &lt;span class="kt"&gt;VarDecl&lt;/span&gt;
&lt;span class="n"&gt;varDeclP&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="kt"&gt;VarDecl&lt;/span&gt; &lt;span class="o"&gt;&amp;lt;$&amp;gt;&lt;/span&gt; &lt;span class="n"&gt;string&lt;/span&gt; &lt;span class="o"&gt;&amp;lt;*&amp;gt;&lt;/span&gt; &lt;span class="n"&gt;string&lt;/span&gt; &lt;span class="o"&gt;&amp;lt;*&lt;/span&gt; &lt;span class="n"&gt;symbol&lt;/span&gt; &lt;span class="s"&gt;";"&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;As I mentioned previously, it is fairly intuitive to read this code as "we want to parse a string, then another string, then a semicolon and then use those things to construct a &lt;code&gt;VarDecl&lt;/code&gt;." But how exactly does this work? It isn't immediately obvious how the two strings end up populating the &lt;code&gt;varType&lt;/code&gt; and &lt;code&gt;varName&lt;/code&gt; fields correctly. To understand it, let's break down this parser function piece by piece.&lt;/p&gt;

&lt;h2&gt;
  
  
  Data constructors are functions
&lt;/h2&gt;

&lt;p&gt;The first important thing to know is that in Haskell, instantiating a data type is done using a &lt;em&gt;data constructor&lt;/em&gt;, and these data constructors are just functions. In the snippet above where we define the &lt;code&gt;VarDecl&lt;/code&gt; type, we write &lt;code&gt;VarDecl&lt;/code&gt; on both sides of the &lt;code&gt;=&lt;/code&gt; sign. The instance on the left is defining the name of the &lt;em&gt;type&lt;/em&gt;, whereas the instance on the right is specifying the name of the &lt;em&gt;constructor&lt;/em&gt; used for instantiating the type. If we wanted to, we could give the constructor a different name from the type, like &lt;code&gt;VarDeclConstructor&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;We then specify that &lt;code&gt;VarDecl&lt;/code&gt; is a record type by placing the fields we expect between curly braces. It isn't obvious, but we're actually creating a function called &lt;code&gt;VarDecl&lt;/code&gt; with the signature &lt;code&gt;String -&amp;gt; String -&amp;gt; VarDecl&lt;/code&gt;---a function that takes two strings and returns a &lt;code&gt;VarDecl&lt;/code&gt;. The function's arguments are the fields we specified between the curly braces, in the order we specified them.&lt;/p&gt;

&lt;p&gt;To explicitly construct a &lt;code&gt;VarDecl&lt;/code&gt; for the expression &lt;code&gt;int x;&lt;/code&gt; we would use the data constructor like so:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight haskell"&gt;&lt;code&gt;&lt;span class="kt"&gt;VarDecl&lt;/span&gt; &lt;span class="s"&gt;"int"&lt;/span&gt; &lt;span class="s"&gt;"x"&lt;/span&gt;
&lt;span class="c1"&gt;-- This creates a value like&lt;/span&gt;
&lt;span class="c1"&gt;-- VarDecl { varType = "int", varName = "x" }&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Understanding data constructors gets us a step closer to understanding how the two strings in &lt;code&gt;varDeclP&lt;/code&gt; are used to construct a &lt;code&gt;VarDecl&lt;/code&gt;: we're simply passing arguments to a function in the order they appear in the constructor definition.&lt;/p&gt;

&lt;h2&gt;
  
  
  What is a functor
&lt;/h2&gt;

&lt;p&gt;The next term in the parser is the &lt;code&gt;&amp;lt;$&amp;gt;&lt;/code&gt; operator. This is an alias of the &lt;code&gt;fmap&lt;/code&gt; function, made into an infix operator. &lt;code&gt;fmap&lt;/code&gt; is part of the &lt;code&gt;Functor&lt;/code&gt; typeclass---it has the signature:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight haskell"&gt;&lt;code&gt;&lt;span class="n"&gt;fmap&lt;/span&gt; &lt;span class="o"&gt;::&lt;/span&gt; &lt;span class="kt"&gt;Functor&lt;/span&gt; &lt;span class="n"&gt;f&lt;/span&gt; &lt;span class="o"&gt;=&amp;gt;&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;a&lt;/span&gt; &lt;span class="o"&gt;-&amp;gt;&lt;/span&gt; &lt;span class="n"&gt;b&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="o"&gt;-&amp;gt;&lt;/span&gt; &lt;span class="n"&gt;f&lt;/span&gt; &lt;span class="n"&gt;a&lt;/span&gt; &lt;span class="o"&gt;-&amp;gt;&lt;/span&gt; &lt;span class="n"&gt;f&lt;/span&gt; &lt;span class="n"&gt;b&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;It is used to "lift" a function into a functorial context, meaning a function that takes &lt;code&gt;a&lt;/code&gt; and returns &lt;code&gt;b&lt;/code&gt; becomes a function that takes &lt;code&gt;f a&lt;/code&gt; (&lt;code&gt;a&lt;/code&gt; in the context of a functor &lt;code&gt;f&lt;/code&gt;) and returns &lt;code&gt;f b&lt;/code&gt; (&lt;code&gt;b&lt;/code&gt; in the context of a functor &lt;code&gt;f&lt;/code&gt;).&lt;/p&gt;

&lt;p&gt;I won't go into detail about functors here, but they can be thought of as types which can be mapped over. The clearest example of a functor is the list type. For a list, &lt;code&gt;fmap&lt;/code&gt; behaves exactly the same as &lt;code&gt;map&lt;/code&gt;: replacing &lt;code&gt;f&lt;/code&gt; in &lt;code&gt;fmap&lt;/code&gt;'s signature with list types gives us:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight haskell"&gt;&lt;code&gt;&lt;span class="n"&gt;fmap&lt;/span&gt; &lt;span class="o"&gt;::&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;a&lt;/span&gt; &lt;span class="o"&gt;-&amp;gt;&lt;/span&gt; &lt;span class="n"&gt;b&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="o"&gt;-&amp;gt;&lt;/span&gt; &lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="n"&gt;a&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt; &lt;span class="o"&gt;-&amp;gt;&lt;/span&gt; &lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="n"&gt;b&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;code&gt;fmap&lt;/code&gt; takes a function from &lt;code&gt;a -&amp;gt; b&lt;/code&gt; and gives us back a function that applies that function to each element in a list and then returns the resulting list. Since &lt;code&gt;&amp;lt;$&amp;gt;&lt;/code&gt; is an alias for &lt;code&gt;fmap&lt;/code&gt;, the following expressions mean the same thing:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight haskell"&gt;&lt;code&gt;&lt;span class="n"&gt;fmap&lt;/span&gt; &lt;span class="n"&gt;f&lt;/span&gt; &lt;span class="n"&gt;xs&lt;/span&gt; &lt;span class="o"&gt;==&lt;/span&gt; &lt;span class="n"&gt;f&lt;/span&gt; &lt;span class="o"&gt;&amp;lt;$&amp;gt;&lt;/span&gt; &lt;span class="n"&gt;xs&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Importantly, the behaviour of &lt;code&gt;fmap&lt;/code&gt; changes based on the particular functorial context of its second argument. Let's add parentheses to our parser to make it clearer how this applies there.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight haskell"&gt;&lt;code&gt;&lt;span class="n"&gt;varDeclP&lt;/span&gt; &lt;span class="o"&gt;::&lt;/span&gt; &lt;span class="kt"&gt;Parser&lt;/span&gt; &lt;span class="kt"&gt;VarDecl&lt;/span&gt;
&lt;span class="n"&gt;varDeclP&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="p"&gt;((&lt;/span&gt;&lt;span class="kt"&gt;VarDecl&lt;/span&gt; &lt;span class="o"&gt;&amp;lt;$&amp;gt;&lt;/span&gt; &lt;span class="n"&gt;string&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="o"&gt;&amp;lt;*&amp;gt;&lt;/span&gt; &lt;span class="n"&gt;string&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="o"&gt;&amp;lt;*&lt;/span&gt; &lt;span class="n"&gt;symbol&lt;/span&gt; &lt;span class="s"&gt;";"&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Function application is left-associative, so the parentheses do not alter the function's behaviour, they only highlight the associativity.&lt;/p&gt;

&lt;p&gt;The first sub-expression we have is &lt;code&gt;VarDecl &amp;lt;$&amp;gt; string&lt;/code&gt;. We are lifting the data constructor &lt;code&gt;VarDecl&lt;/code&gt; (which, again, is just a function) into whichever context &lt;code&gt;string&lt;/code&gt; is in. Which context is that? The &lt;code&gt;string&lt;/code&gt; parser has the signature &lt;code&gt;string :: Parser String&lt;/code&gt;, so assuming &lt;code&gt;Parser&lt;/code&gt; is a member of the &lt;code&gt;Functor&lt;/code&gt; typeclass (it needs to be for the parser combinator pattern to work) we can use it as the second argument to &lt;code&gt;fmap&lt;/code&gt;. Let's substitute &lt;code&gt;Parser&lt;/code&gt; for &lt;code&gt;f&lt;/code&gt; and &lt;code&gt;String&lt;/code&gt; for &lt;code&gt;a&lt;/code&gt; in the &lt;code&gt;fmap&lt;/code&gt; type signature:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight haskell"&gt;&lt;code&gt;&lt;span class="n"&gt;fmap&lt;/span&gt; &lt;span class="o"&gt;::&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="kt"&gt;String&lt;/span&gt; &lt;span class="o"&gt;-&amp;gt;&lt;/span&gt; &lt;span class="n"&gt;b&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="o"&gt;-&amp;gt;&lt;/span&gt; &lt;span class="kt"&gt;Parser&lt;/span&gt; &lt;span class="kt"&gt;String&lt;/span&gt; &lt;span class="o"&gt;-&amp;gt;&lt;/span&gt; &lt;span class="kt"&gt;Parser&lt;/span&gt; &lt;span class="n"&gt;b&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This works, but what is the type of &lt;code&gt;b&lt;/code&gt;? Well, functions are always curried, and the &lt;code&gt;VarDecl&lt;/code&gt; constructor has the signature &lt;code&gt;VarDecl :: String -&amp;gt; String -&amp;gt; VarDecl&lt;/code&gt;, so passing a single string argument to it leaves us with a resulting function of type &lt;code&gt;String -&amp;gt; VarDecl&lt;/code&gt;---this is &lt;code&gt;b&lt;/code&gt;.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight haskell"&gt;&lt;code&gt;&lt;span class="n"&gt;fmap&lt;/span&gt; &lt;span class="o"&gt;::&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="kt"&gt;String&lt;/span&gt; &lt;span class="o"&gt;-&amp;gt;&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="kt"&gt;String&lt;/span&gt; &lt;span class="o"&gt;-&amp;gt;&lt;/span&gt; &lt;span class="kt"&gt;VarDecl&lt;/span&gt;&lt;span class="p"&gt;))&lt;/span&gt; &lt;span class="o"&gt;-&amp;gt;&lt;/span&gt; &lt;span class="kt"&gt;Parser&lt;/span&gt; &lt;span class="kt"&gt;String&lt;/span&gt; &lt;span class="o"&gt;-&amp;gt;&lt;/span&gt; &lt;span class="kt"&gt;Parser&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="kt"&gt;String&lt;/span&gt; &lt;span class="o"&gt;-&amp;gt;&lt;/span&gt; &lt;span class="kt"&gt;VarDecl&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Because our &lt;code&gt;VarDecl&lt;/code&gt; constructor is a binary function, mapping it over a single argument in the &lt;code&gt;Parser&lt;/code&gt; context results in a partially applied function lifted into that context. What we want is to continue passing arguments to the function so we can finish building our &lt;code&gt;VarDecl&lt;/code&gt; record, but we'll need another way to invoke it now that it's in the &lt;code&gt;Parser&lt;/code&gt; context. Now we're ready to introduce applicatives.&lt;/p&gt;

&lt;h2&gt;
  
  
  What is an applicative?
&lt;/h2&gt;

&lt;p&gt;An applicative (short for applicative functor) is a special case of functors, where the type of value inside the functor can be a function. For a type to qualify as a member of the &lt;code&gt;Applicative&lt;/code&gt; class, it must implement two functions:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight haskell"&gt;&lt;code&gt;&lt;span class="n"&gt;pure&lt;/span&gt; &lt;span class="o"&gt;::&lt;/span&gt; &lt;span class="kt"&gt;Functor&lt;/span&gt; &lt;span class="n"&gt;f&lt;/span&gt; &lt;span class="o"&gt;=&amp;gt;&lt;/span&gt; &lt;span class="n"&gt;a&lt;/span&gt; &lt;span class="o"&gt;-&amp;gt;&lt;/span&gt; &lt;span class="n"&gt;f&lt;/span&gt; &lt;span class="n"&gt;a&lt;/span&gt;
&lt;span class="o"&gt;&amp;lt;*&amp;gt;&lt;/span&gt; &lt;span class="o"&gt;::&lt;/span&gt; &lt;span class="kt"&gt;Functor&lt;/span&gt; &lt;span class="n"&gt;f&lt;/span&gt; &lt;span class="o"&gt;=&amp;gt;&lt;/span&gt; &lt;span class="n"&gt;f&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;a&lt;/span&gt; &lt;span class="o"&gt;-&amp;gt;&lt;/span&gt; &lt;span class="n"&gt;b&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="o"&gt;-&amp;gt;&lt;/span&gt; &lt;span class="n"&gt;f&lt;/span&gt; &lt;span class="n"&gt;a&lt;/span&gt; &lt;span class="o"&gt;-&amp;gt;&lt;/span&gt; &lt;span class="n"&gt;f&lt;/span&gt; &lt;span class="n"&gt;b&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The &lt;code&gt;pure&lt;/code&gt; function takes a value of type &lt;code&gt;a&lt;/code&gt; and lifts it into the context of a functor type &lt;code&gt;f&lt;/code&gt;. This means that for a &lt;code&gt;Functor f&lt;/code&gt; to also be a member of the &lt;code&gt;Applicative&lt;/code&gt; class, it must be possible to construct an instance of &lt;code&gt;f&lt;/code&gt; from a single value.&lt;/p&gt;

&lt;p&gt;The &lt;code&gt;&amp;lt;*&amp;gt;&lt;/code&gt; function, called the sequential application operator, takes an applicative value (a function &lt;code&gt;a -&amp;gt; b&lt;/code&gt; in a functorial context) and a value of type &lt;code&gt;f a&lt;/code&gt; (&lt;code&gt;a&lt;/code&gt; in the same context). The value inside the &lt;code&gt;f a&lt;/code&gt; argument is fed into the function &lt;code&gt;a -&amp;gt; b&lt;/code&gt; inside the applicative, and the resulting &lt;code&gt;b&lt;/code&gt; value is returned, still inside the &lt;code&gt;f&lt;/code&gt; context. As with functors, the specifics of how this behaviour is implemented is different for each instance of &lt;code&gt;Applicative&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;Let's revisit the list functor for a concrete example. To test if lists are a member of the &lt;code&gt;Applicative&lt;/code&gt; class, we'll need to see if we can implement the &lt;code&gt;pure&lt;/code&gt; and &lt;code&gt;&amp;lt;*&amp;gt;&lt;/code&gt; functions. We can implement &lt;code&gt;pure&lt;/code&gt; by simply taking some value &lt;code&gt;x&lt;/code&gt; and creating a list where &lt;code&gt;x&lt;/code&gt; is the only element.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight haskell"&gt;&lt;code&gt;&lt;span class="n"&gt;pure&lt;/span&gt; &lt;span class="o"&gt;::&lt;/span&gt; &lt;span class="n"&gt;a&lt;/span&gt; &lt;span class="o"&gt;-&amp;gt;&lt;/span&gt; &lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="n"&gt;a&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;
&lt;span class="n"&gt;pure&lt;/span&gt; &lt;span class="n"&gt;x&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="n"&gt;x&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;For sequential application, we need to accept a list of functions &lt;code&gt;a -&amp;gt; b&lt;/code&gt; along with a list of &lt;code&gt;a&lt;/code&gt; values, apply the each function in the first list to each value in the second, and then return the list of results.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight haskell"&gt;&lt;code&gt;&lt;span class="o"&gt;&amp;lt;*&amp;gt;&lt;/span&gt; &lt;span class="o"&gt;::&lt;/span&gt; &lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="n"&gt;a&lt;/span&gt; &lt;span class="o"&gt;-&amp;gt;&lt;/span&gt; &lt;span class="n"&gt;b&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt; &lt;span class="o"&gt;-&amp;gt;&lt;/span&gt; &lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="n"&gt;a&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt; &lt;span class="o"&gt;-&amp;gt;&lt;/span&gt; &lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="n"&gt;b&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;
&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;f&lt;/span&gt;&lt;span class="o"&gt;:&lt;/span&gt;&lt;span class="n"&gt;fs&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="o"&gt;&amp;lt;*&amp;gt;&lt;/span&gt; &lt;span class="n"&gt;xs&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;f&lt;/span&gt; &lt;span class="o"&gt;&amp;lt;$&amp;gt;&lt;/span&gt; &lt;span class="n"&gt;xs&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="o"&gt;&amp;lt;&amp;gt;&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;fs&lt;/span&gt; &lt;span class="o"&gt;&amp;lt;*&amp;gt;&lt;/span&gt; &lt;span class="n"&gt;xs&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;span class="kt"&gt;[]&lt;/span&gt; &lt;span class="o"&gt;&amp;lt;*&amp;gt;&lt;/span&gt; &lt;span class="kr"&gt;_&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="kt"&gt;[]&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This recursive implementation takes the list of functions and the list of values, and it maps the first function over the full list of values (using the fmap &lt;code&gt;&amp;lt;$&amp;gt;&lt;/code&gt; operator discussed previously). Then it calls itself with the remainder of the list of functions and the full list of values. When finally called with an empty list of functions, it returns an empty list of values. This is not the official implementation, it's only an example to demonstrate that both functions required by the &lt;code&gt;Applicative&lt;/code&gt; class can be implemented for lists, and hence, lists are an example of an &lt;code&gt;Applicative&lt;/code&gt; type.&lt;/p&gt;

&lt;h2&gt;
  
  
  &lt;code&gt;Parser&lt;/code&gt; as an applicative
&lt;/h2&gt;

&lt;p&gt;Returning to our parser function, we've evaluated the first sub-expression and found that it evaluates to the type &lt;code&gt;Parser (String -&amp;gt; VarDecl)&lt;/code&gt;. We know that &lt;code&gt;Parser&lt;/code&gt; is a functor, so this type certainly looks like an applicative, and indeed it is. Following the parser combinator pattern, the &lt;code&gt;Parser&lt;/code&gt; type might be defined like so:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight haskell"&gt;&lt;code&gt;&lt;span class="kr"&gt;data&lt;/span&gt; &lt;span class="kt"&gt;Parser&lt;/span&gt; &lt;span class="n"&gt;a&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="kt"&gt;Parser&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt; &lt;span class="n"&gt;parse&lt;/span&gt; &lt;span class="o"&gt;::&lt;/span&gt; &lt;span class="kt"&gt;String&lt;/span&gt; &lt;span class="o"&gt;-&amp;gt;&lt;/span&gt; &lt;span class="kt"&gt;Maybe&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;a&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="kt"&gt;String&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The &lt;code&gt;Parser&lt;/code&gt; has a &lt;code&gt;parse&lt;/code&gt; method which attempts to construct a value of type &lt;code&gt;a&lt;/code&gt; by consuming characters from an input string. If successful, the value is returned in a tuple along with the remainder of the input string. Otherwise, it returns &lt;code&gt;Nothing&lt;/code&gt;. Typically &lt;code&gt;Either&lt;/code&gt; would be used instead of &lt;code&gt;Maybe&lt;/code&gt; to enable more informative errors to be returned, but I'm using &lt;code&gt;Maybe&lt;/code&gt; here for simplicity. All parsing errors just result in &lt;code&gt;Nothing&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;The &lt;code&gt;pure&lt;/code&gt; and &lt;code&gt;&amp;lt;*&amp;gt;&lt;/code&gt; functions for this type might be implemented like so:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight haskell"&gt;&lt;code&gt;&lt;span class="n"&gt;pure&lt;/span&gt; &lt;span class="o"&gt;::&lt;/span&gt; &lt;span class="n"&gt;a&lt;/span&gt; &lt;span class="o"&gt;-&amp;gt;&lt;/span&gt; &lt;span class="kt"&gt;Parser&lt;/span&gt; &lt;span class="n"&gt;a&lt;/span&gt;
&lt;span class="n"&gt;pure&lt;/span&gt; &lt;span class="n"&gt;x&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="kt"&gt;Parser&lt;/span&gt; &lt;span class="o"&gt;$&lt;/span&gt; &lt;span class="nf"&gt;\&lt;/span&gt;&lt;span class="n"&gt;input&lt;/span&gt; &lt;span class="o"&gt;-&amp;gt;&lt;/span&gt; &lt;span class="kt"&gt;Just&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;a&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;input&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;

&lt;span class="o"&gt;&amp;lt;*&amp;gt;&lt;/span&gt; &lt;span class="o"&gt;::&lt;/span&gt; &lt;span class="kt"&gt;Parser&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;a&lt;/span&gt; &lt;span class="o"&gt;-&amp;gt;&lt;/span&gt; &lt;span class="n"&gt;b&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="o"&gt;-&amp;gt;&lt;/span&gt; &lt;span class="kt"&gt;Parser&lt;/span&gt; &lt;span class="n"&gt;a&lt;/span&gt; &lt;span class="o"&gt;-&amp;gt;&lt;/span&gt; &lt;span class="kt"&gt;Parser&lt;/span&gt; &lt;span class="n"&gt;b&lt;/span&gt;
&lt;span class="kt"&gt;Parser&lt;/span&gt; &lt;span class="n"&gt;f&lt;/span&gt; &lt;span class="o"&gt;&amp;lt;*&amp;gt;&lt;/span&gt; &lt;span class="kt"&gt;Parser&lt;/span&gt; &lt;span class="n"&gt;g&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="kr"&gt;do&lt;/span&gt;
&lt;span class="kt"&gt;Parser&lt;/span&gt; &lt;span class="n"&gt;f&lt;/span&gt; &lt;span class="o"&gt;&amp;lt;*&amp;gt;&lt;/span&gt; &lt;span class="kt"&gt;Parser&lt;/span&gt; &lt;span class="n"&gt;g&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="kt"&gt;Parser&lt;/span&gt; &lt;span class="o"&gt;$&lt;/span&gt; &lt;span class="nf"&gt;\&lt;/span&gt;&lt;span class="n"&gt;input&lt;/span&gt; &lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;
    &lt;span class="kr"&gt;case&lt;/span&gt; &lt;span class="n"&gt;f&lt;/span&gt; &lt;span class="n"&gt;input&lt;/span&gt; &lt;span class="kr"&gt;of&lt;/span&gt;
        &lt;span class="kt"&gt;Nothing&lt;/span&gt; &lt;span class="o"&gt;-&amp;gt;&lt;/span&gt; &lt;span class="kt"&gt;Nothing&lt;/span&gt;
        &lt;span class="kt"&gt;Just&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;f'&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;input'&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;
            &lt;span class="kr"&gt;case&lt;/span&gt; &lt;span class="n"&gt;g&lt;/span&gt; &lt;span class="n"&gt;input'&lt;/span&gt; &lt;span class="kr"&gt;of&lt;/span&gt;
                &lt;span class="kt"&gt;Nothing&lt;/span&gt; &lt;span class="o"&gt;-&amp;gt;&lt;/span&gt; &lt;span class="kt"&gt;Nothing&lt;/span&gt;
                &lt;span class="kt"&gt;Just&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;val&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;rem&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="o"&gt;-&amp;gt;&lt;/span&gt; &lt;span class="kt"&gt;Just&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;f'&lt;/span&gt; &lt;span class="n"&gt;val&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;rem&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The &lt;code&gt;pure&lt;/code&gt; function is fairly self-explanatory---it simply takes a value &lt;code&gt;x&lt;/code&gt; and uses it to construct a parser that consumes no input and always returns &lt;code&gt;x&lt;/code&gt; along with the full input stream.&lt;/p&gt;

&lt;p&gt;Sequential application is a little more complicated. This function takes two parsers as its arguments: the first is a parser that attempts to construct a function &lt;code&gt;a -&amp;gt; b&lt;/code&gt;; the second is a parser that attempts to construct a value of type &lt;code&gt;a&lt;/code&gt;. It runs the first parser on the input, and if it succeeds to construct the function &lt;code&gt;a -&amp;gt; b&lt;/code&gt;, it continues by then applying the second parser to the remaining input. If the second parser is also successful in constructing a value of type &lt;code&gt;a&lt;/code&gt;, that value is passed to the function &lt;code&gt;a -&amp;gt; b&lt;/code&gt;, resulting in a value of type &lt;code&gt;b&lt;/code&gt;. This final value is then returned in the form of a parser which always returns that &lt;code&gt;b&lt;/code&gt; value without consuming any input. If either of the parsers fail, the whole operation results in &lt;code&gt;Nothing&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;This part had me stumped for a while. I couldn't wrap my head around the idea of a function inside a parser. A type like &lt;code&gt;Parser String&lt;/code&gt; or &lt;code&gt;Parser Int&lt;/code&gt; is intuitive to understand---they're trying to parse strings or integers from their inputs. But how could an unevaluated function be parsed from the text? The key to understanding this is to think of &lt;code&gt;Parser&lt;/code&gt; not as a container, but as a name for a particular kind of computation---namely a computation that has access to, and can consume, a stream of input text. The type passed to &lt;code&gt;Parser&lt;/code&gt; is the type of value you're trying to construct within that context. That is, &lt;code&gt;Parser (a -&amp;gt; b)&lt;/code&gt; is not a parser of functions (which doesn't seem to make much sense), it is a function &lt;code&gt;a -&amp;gt; b&lt;/code&gt; resulting from a computation in the &lt;code&gt;Parser&lt;/code&gt; context.&lt;/p&gt;

&lt;p&gt;With that said, we can now better make sense of our parser function. Again, the sub-expression &lt;code&gt;VarDecl &amp;lt;$&amp;gt; string&lt;/code&gt; results in a value of type &lt;code&gt;Parser (String -&amp;gt; VarDecl)&lt;/code&gt;. We have used the &lt;code&gt;string&lt;/code&gt; function to consume a &lt;code&gt;String&lt;/code&gt; from the input text, and fed this into the &lt;code&gt;VarDecl&lt;/code&gt; constructor, partially applying it and resulting in another function &lt;code&gt;String -&amp;gt; VarDecl&lt;/code&gt;. Because this is part of a computation in the &lt;code&gt;Parser&lt;/code&gt; context (we lifted &lt;code&gt;VarDecl&lt;/code&gt; into that context using fmap &lt;code&gt;&amp;lt;$&amp;gt;&lt;/code&gt;), this resulting function is also in the &lt;code&gt;Parser&lt;/code&gt; context.&lt;/p&gt;

&lt;p&gt;Working our way from the inside out, the next sub-expression is &lt;code&gt;(VarDecl &amp;lt;$&amp;gt; string) &amp;lt;*&amp;gt; string&lt;/code&gt; (including the expression we've already looked at). Here we're using the sequential application operator &lt;code&gt;&amp;lt;*&amp;gt;&lt;/code&gt;. Its first argument is the result of the first expression (of type &lt;code&gt;Parser (String -&amp;gt; VarDecl)&lt;/code&gt;) and its second argument is the &lt;code&gt;string&lt;/code&gt; function which has a type of &lt;code&gt;Parser String&lt;/code&gt;. Let's substitute these types into the type signature for the &lt;code&gt;&amp;lt;*&amp;gt;&lt;/code&gt; function.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight haskell"&gt;&lt;code&gt;&lt;span class="o"&gt;&amp;lt;*&amp;gt;&lt;/span&gt; &lt;span class="o"&gt;::&lt;/span&gt; &lt;span class="kt"&gt;Parser&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="kt"&gt;String&lt;/span&gt; &lt;span class="o"&gt;-&amp;gt;&lt;/span&gt; &lt;span class="kt"&gt;VarDecl&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="o"&gt;-&amp;gt;&lt;/span&gt; &lt;span class="kt"&gt;Parser&lt;/span&gt; &lt;span class="kt"&gt;String&lt;/span&gt; &lt;span class="o"&gt;-&amp;gt;&lt;/span&gt; &lt;span class="kt"&gt;Parser&lt;/span&gt; &lt;span class="kt"&gt;VarDecl&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Thinking about how the &lt;code&gt;&amp;lt;*&amp;gt;&lt;/code&gt; is implemented for the &lt;code&gt;Parser&lt;/code&gt; type, this expression will run the first parser to parse a string and use it to partially apply the &lt;code&gt;VarDecl&lt;/code&gt; constructor as we've already described. Then it will run the second parser to parse another string, and if successful, it will pass that string into the partially applied function, finally arriving at a value of type &lt;code&gt;VarDecl&lt;/code&gt; which it returns still wrapped in the &lt;code&gt;Parser&lt;/code&gt; context. Voilà! We've constructed the &lt;code&gt;VarDecl&lt;/code&gt; type by composing parsers together.&lt;/p&gt;

&lt;p&gt;But hold on, the full function is:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight haskell"&gt;&lt;code&gt;&lt;span class="n"&gt;varDeclP&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="p"&gt;((&lt;/span&gt;&lt;span class="kt"&gt;VarDecl&lt;/span&gt; &lt;span class="o"&gt;&amp;lt;$&amp;gt;&lt;/span&gt; &lt;span class="n"&gt;string&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="o"&gt;&amp;lt;*&amp;gt;&lt;/span&gt; &lt;span class="n"&gt;string&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="o"&gt;&amp;lt;*&lt;/span&gt; &lt;span class="n"&gt;symbol&lt;/span&gt; &lt;span class="s"&gt;";"&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;There is another part to the expression, a &lt;code&gt;symbol&lt;/code&gt; parser which looks for the semicolon that terminates our &lt;code&gt;int x;&lt;/code&gt; expression. It is important for the semicolon to be there, but we don't need its value to construct a &lt;code&gt;VarDecl&lt;/code&gt; record, so how is this parser incorporated into the function?&lt;/p&gt;

&lt;p&gt;This final parser is being applied using an &lt;code&gt;&amp;lt;*&lt;/code&gt; operator we haven't looked at yet. This operator is also a part of the &lt;code&gt;Applicative&lt;/code&gt; class, but it is not part of the minimal definition. The type signature for this operator is:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight haskell"&gt;&lt;code&gt;&lt;span class="o"&gt;&amp;lt;*&lt;/span&gt; &lt;span class="o"&gt;::&lt;/span&gt; &lt;span class="kt"&gt;Applicative&lt;/span&gt; &lt;span class="n"&gt;f&lt;/span&gt; &lt;span class="o"&gt;=&amp;gt;&lt;/span&gt; &lt;span class="n"&gt;f&lt;/span&gt; &lt;span class="n"&gt;a&lt;/span&gt; &lt;span class="o"&gt;-&amp;gt;&lt;/span&gt; &lt;span class="n"&gt;f&lt;/span&gt; &lt;span class="n"&gt;b&lt;/span&gt; &lt;span class="o"&gt;-&amp;gt;&lt;/span&gt; &lt;span class="n"&gt;f&lt;/span&gt; &lt;span class="n"&gt;a&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This is a function which takes two values both in an applicative context, and just seems to return the first one. This initially seems kind of pointless, but take a look at how it might be implemented.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight haskell"&gt;&lt;code&gt;&lt;span class="kt"&gt;Parser&lt;/span&gt; &lt;span class="n"&gt;f&lt;/span&gt; &lt;span class="o"&gt;&amp;lt;*&lt;/span&gt; &lt;span class="kt"&gt;Parser&lt;/span&gt; &lt;span class="n"&gt;g&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="kt"&gt;Parser&lt;/span&gt; &lt;span class="o"&gt;$&lt;/span&gt; &lt;span class="nf"&gt;\&lt;/span&gt;&lt;span class="n"&gt;input&lt;/span&gt; &lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;
    &lt;span class="kr"&gt;case&lt;/span&gt; &lt;span class="n"&gt;f&lt;/span&gt; &lt;span class="n"&gt;input&lt;/span&gt; &lt;span class="kr"&gt;of&lt;/span&gt;
        &lt;span class="kt"&gt;Nothing&lt;/span&gt; &lt;span class="o"&gt;-&amp;gt;&lt;/span&gt; &lt;span class="kt"&gt;Nothing&lt;/span&gt;
        &lt;span class="kt"&gt;Just&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;x&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;rem&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;
            &lt;span class="kr"&gt;case&lt;/span&gt; &lt;span class="n"&gt;g&lt;/span&gt; &lt;span class="n"&gt;rem&lt;/span&gt; &lt;span class="kr"&gt;of&lt;/span&gt;
                &lt;span class="kt"&gt;Nothing&lt;/span&gt; &lt;span class="o"&gt;-&amp;gt;&lt;/span&gt; &lt;span class="kt"&gt;Nothing&lt;/span&gt;
                &lt;span class="kt"&gt;Just&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="kr"&gt;_&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;rem'&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="o"&gt;-&amp;gt;&lt;/span&gt; &lt;span class="kt"&gt;Just&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;x&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;rem'&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Although the value produced by the second parser isn't used, we do nonetheless run both parsers, allowing them both to consume input and possibly fail. If the second parser does fail, the whole expression also fails. This is ideal for our case where we want to parse a semicolon but then throw the parsed value away. Let's plug the types from our parser into the type signature for &lt;code&gt;&amp;lt;*&lt;/code&gt;.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight haskell"&gt;&lt;code&gt;&lt;span class="o"&gt;&amp;lt;*&lt;/span&gt; &lt;span class="o"&gt;::&lt;/span&gt; &lt;span class="kt"&gt;Parser&lt;/span&gt; &lt;span class="kt"&gt;VarDecl&lt;/span&gt; &lt;span class="o"&gt;-&amp;gt;&lt;/span&gt; &lt;span class="kt"&gt;Parser&lt;/span&gt; &lt;span class="kt"&gt;String&lt;/span&gt; &lt;span class="o"&gt;-&amp;gt;&lt;/span&gt; &lt;span class="kt"&gt;Parser&lt;/span&gt; &lt;span class="kt"&gt;VarDecl&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The parser on the left-hand side of the &lt;code&gt;&amp;lt;*&lt;/code&gt; is executed and its resulting value is the value returned from the overall expression. The parser on the right-hand side does have to run successfully, but its resulting value has no effect on the output of the overall expression.&lt;/p&gt;

&lt;h2&gt;
  
  
  The bigger picture
&lt;/h2&gt;

&lt;p&gt;We've looked at how applicatives are used in the parser combinator pattern, but the &lt;code&gt;Applicative&lt;/code&gt; class is intentionally abstract so that it can be used in lots of different contexts. In Haskell, I often find myself able to understand an abstraction well enough to use it in a certain context, but unable to fully grasp the essence of what it aims to express.&lt;/p&gt;

&lt;p&gt;For example, I've been aware for quite a long time that an applicative is "a function inside a functor". That mental model works well enough when thinking about lists or the &lt;code&gt;Maybe&lt;/code&gt; type, because both of those types can be thought of as containers for other values, which is intuitive. However, that understanding tripped me up when it came to learning about parsers; how can a parser be a container for a value, especially when that value is a function? Haskell is unique in that you can often ascertain a lot about what a function does just by looking at its type signature. Of course, this often isn't all the information you need to effectively use it, implementation does matter, but often the essence of an abstraction is best understood by looking at its type.&lt;/p&gt;

&lt;p&gt;Take another look at the type of the sequential application operator:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight haskell"&gt;&lt;code&gt;&lt;span class="o"&gt;&amp;lt;*&amp;gt;&lt;/span&gt; &lt;span class="o"&gt;::&lt;/span&gt; &lt;span class="kt"&gt;Functor&lt;/span&gt; &lt;span class="n"&gt;f&lt;/span&gt; &lt;span class="o"&gt;=&amp;gt;&lt;/span&gt; &lt;span class="n"&gt;f&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;a&lt;/span&gt; &lt;span class="o"&gt;-&amp;gt;&lt;/span&gt; &lt;span class="n"&gt;b&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="o"&gt;-&amp;gt;&lt;/span&gt; &lt;span class="n"&gt;f&lt;/span&gt; &lt;span class="n"&gt;a&lt;/span&gt; &lt;span class="o"&gt;-&amp;gt;&lt;/span&gt; &lt;span class="n"&gt;f&lt;/span&gt; &lt;span class="n"&gt;b&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;It bears a resemblance to the type of the function application operator &lt;code&gt;$&lt;/code&gt;:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight haskell"&gt;&lt;code&gt;&lt;span class="o"&gt;$&lt;/span&gt; &lt;span class="o"&gt;::&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;a&lt;/span&gt; &lt;span class="o"&gt;-&amp;gt;&lt;/span&gt; &lt;span class="n"&gt;b&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="o"&gt;-&amp;gt;&lt;/span&gt; &lt;span class="n"&gt;a&lt;/span&gt; &lt;span class="o"&gt;-&amp;gt;&lt;/span&gt; &lt;span class="n"&gt;b&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;They seem to be expressing the same thing, except the former is in a functorial context. The function application operator &lt;code&gt;$&lt;/code&gt; is a controversial one, because in a simple expression, it doesn't do anything useful. For example, the following expressions are equivalent:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight haskell"&gt;&lt;code&gt;&lt;span class="n"&gt;f&lt;/span&gt; &lt;span class="n"&gt;x&lt;/span&gt; &lt;span class="o"&gt;==&lt;/span&gt; &lt;span class="n"&gt;f&lt;/span&gt; &lt;span class="o"&gt;$&lt;/span&gt; &lt;span class="n"&gt;x&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The only purpose served by the operator is in longer, more complex expressions where it can be used to disambiguate the precedence of terms. The reason for this is because there is no question of how a function &lt;code&gt;a -&amp;gt; b&lt;/code&gt; can be mapped over a value &lt;code&gt;a&lt;/code&gt;---this is a pure function and a pure value, so Haskell knows how to evaluate it. This is the essence of applicatives as an abstraction.&lt;/p&gt;

&lt;p&gt;The sequential application operator &lt;code&gt;&amp;lt;*&amp;gt;&lt;/code&gt; &lt;em&gt;is&lt;/em&gt; serving a very similar purpose to the function application operator &lt;code&gt;$&lt;/code&gt;, but in the former case, Haskell doesn't know how to apply the function to the argument, because they're both in an applicative context. The &lt;code&gt;&amp;lt;*&amp;gt;&lt;/code&gt; operator leverages the applicative type to gain further information about &lt;em&gt;how&lt;/em&gt; to map the function over the value.&lt;/p&gt;

&lt;p&gt;This is incredibly powerful; we're able to express the composition of potentially very complex logic in terms of simple functions, because the complexity is abstracted away in the type. In the language of category theory, we're able to move into another context (like a parser context) and express morphisms in that context using the syntax and semantics of functions.&lt;/p&gt;

&lt;p&gt;After improving my understanding of applicatives, the question occurred to me: "then what is a monad?" That could warrant its own post, monads serve a similar purpose, the difference essentially being that monads can be chained together with the results of one term in the chain depending on the results of the previous terms---this isn't possible with applicatives. In cases where that sort of behaviour isn't needed, applicatives are a more natural fit.&lt;/p&gt;

</description>
      <category>haskell</category>
      <category>applicatives</category>
      <category>parsing</category>
    </item>
    <item>
      <title>Parsing left-recursion by recursive descent</title>
      <dc:creator>Hadrian Hughes</dc:creator>
      <pubDate>Mon, 25 Mar 2024 00:00:00 +0000</pubDate>
      <link>https://dev.to/hadrianhughes/parsing-left-recursion-by-recursive-descent-98f</link>
      <guid>https://dev.to/hadrianhughes/parsing-left-recursion-by-recursive-descent-98f</guid>
      <description>&lt;p&gt;I've recently been building a parser for a programming language I'm designing. I'll likely be making future posts about the project as I make more progress, but suffice it to say, the language aims to bridge the divide between the functional and procedural paradigms as discussed in my post &lt;a href="https://www.hadrianhughes.dev/tale-of-two-paradigms"&gt;A Tale of Two Paradigms&lt;/a&gt;. I'm using a Haskell library called &lt;a href="https://hackage.haskell.org/package/megaparsec"&gt;Megaparsec&lt;/a&gt;, which follows the parser combinator pattern to help with building recursive descent parsers.&lt;/p&gt;

&lt;h2&gt;
  
  
  A recurring problem
&lt;/h2&gt;

&lt;p&gt;This library is great to work with, and building parsers this way is very intuitive, but I found myself repeatedly running into the same problem: trying to parse left-recursive parts of the grammar led to an infinite recursive loop. It took me a while to properly understand what was happening, but the problem can be formulated as follows.&lt;/p&gt;

&lt;p&gt;Any time a rule contains itself as its first term, the parser will fall into infinite recursion. For example, take the following parser function:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight haskell"&gt;&lt;code&gt;&lt;span class="n"&gt;expression&lt;/span&gt; &lt;span class="o"&gt;::&lt;/span&gt; &lt;span class="kt"&gt;Parser&lt;/span&gt; &lt;span class="kt"&gt;Expression&lt;/span&gt;
&lt;span class="n"&gt;expression&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="kt"&gt;Expression&lt;/span&gt; &lt;span class="o"&gt;&amp;lt;$&amp;gt;&lt;/span&gt; &lt;span class="n"&gt;expression&lt;/span&gt; &lt;span class="o"&gt;&amp;lt;*&amp;gt;&lt;/span&gt; &lt;span class="n"&gt;term&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;code&gt;Expression&lt;/code&gt; represents a type defined as part of the language's abstract syntax tree (AST), and &lt;code&gt;term&lt;/code&gt; would be some other parser function. The &lt;code&gt;expression&lt;/code&gt; function first attempts to parse an &lt;code&gt;expression&lt;/code&gt;, then attempts to parse a &lt;code&gt;term&lt;/code&gt;, then passes the results of these two components to the data constructor for the &lt;code&gt;Expression&lt;/code&gt; type. Abstractly, this is a valid rule. The problem is that the first thing the function does is call itself, with no base case to break it out of this loop.&lt;/p&gt;

&lt;p&gt;The problem becomes clearer if we express it in a more procedural style:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight javascript"&gt;&lt;code&gt;&lt;span class="kd"&gt;function&lt;/span&gt; &lt;span class="nf"&gt;expression&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
    &lt;span class="nf"&gt;expression&lt;/span&gt;&lt;span class="p"&gt;();&lt;/span&gt;
    &lt;span class="nf"&gt;term&lt;/span&gt;&lt;span class="p"&gt;();&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The function immediately calls itself, and as such the program will run forever (or until the call stack overflows).&lt;/p&gt;

&lt;p&gt;This problem appears frequently when parsing expressions that can be chained. For example, in my language there are structs (data structures with values assigned to predefined fields), and accessing struct fields is achieved using a dot followed by the name of the field. For example, given a struct &lt;code&gt;person&lt;/code&gt; that contains a field &lt;code&gt;name&lt;/code&gt;, we would access the field using the expression &lt;code&gt;person.name&lt;/code&gt;. This simple case would be straightforward to parse. First we would define a type &lt;code&gt;StructAccess&lt;/code&gt; to represent this kind of expression.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight haskell"&gt;&lt;code&gt;&lt;span class="kr"&gt;data&lt;/span&gt; &lt;span class="kt"&gt;StructAccess&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="kt"&gt;StructAccess&lt;/span&gt; &lt;span class="kt"&gt;Text&lt;/span&gt; &lt;span class="kt"&gt;Text&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This type takes 2 arguments of type &lt;code&gt;Text&lt;/code&gt;. The first represents the name of the struct being accessed, and the second represents the field being selected. The parser for this kind of expression would look like this:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight haskell"&gt;&lt;code&gt;&lt;span class="n"&gt;structAccess&lt;/span&gt; &lt;span class="o"&gt;::&lt;/span&gt; &lt;span class="kt"&gt;Parser&lt;/span&gt; &lt;span class="kt"&gt;StructAccess&lt;/span&gt;
&lt;span class="n"&gt;structAccess&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="kt"&gt;StructAccess&lt;/span&gt; &lt;span class="o"&gt;&amp;lt;$&amp;gt;&lt;/span&gt; &lt;span class="n"&gt;identifier&lt;/span&gt; &lt;span class="o"&gt;&amp;lt;*&amp;gt;&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;dot&lt;/span&gt; &lt;span class="o"&gt;*&amp;gt;&lt;/span&gt; &lt;span class="n"&gt;identifier&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;And for the expression &lt;code&gt;person.name&lt;/code&gt;, it would yield an AST that looks like something like this:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight haskell"&gt;&lt;code&gt;&lt;span class="kt"&gt;StructAccess&lt;/span&gt; &lt;span class="s"&gt;"person"&lt;/span&gt; &lt;span class="s"&gt;"name"&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;However, we ideally want to be able to chain this operation. For example, let's extend the definition of a person to also include an &lt;code&gt;address&lt;/code&gt; field, which is itself a struct:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight typescript"&gt;&lt;code&gt;&lt;span class="kd"&gt;type&lt;/span&gt; &lt;span class="nx"&gt;Address&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
    &lt;span class="na"&gt;street&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="nb"&gt;String&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
    &lt;span class="na"&gt;town&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="nb"&gt;String&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
    &lt;span class="na"&gt;postCode&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="nb"&gt;String&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;

&lt;span class="kd"&gt;type&lt;/span&gt; &lt;span class="nx"&gt;Person&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
    &lt;span class="na"&gt;name&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="nb"&gt;String&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
    &lt;span class="na"&gt;address&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="nx"&gt;Address&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;To access a person's &lt;code&gt;postCode&lt;/code&gt; the expression should be &lt;code&gt;person.address.postCode&lt;/code&gt;. In this expression, we are actually first accessing the address field on the person struct using &lt;code&gt;person.address&lt;/code&gt;, and this yields another struct; then we access the postCode field on this address struct by appending the previous expression with &lt;code&gt;.postCode&lt;/code&gt;. Thus, we arrive at the full expression &lt;code&gt;person.address.postCode&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;To achieve this, we need to change the &lt;code&gt;StructAccess&lt;/code&gt; type to a general &lt;code&gt;Expr&lt;/code&gt; type.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight haskell"&gt;&lt;code&gt;&lt;span class="kr"&gt;data&lt;/span&gt; &lt;span class="kt"&gt;Expr&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="kt"&gt;StructAccess&lt;/span&gt; &lt;span class="kt"&gt;Expr&lt;/span&gt; &lt;span class="kt"&gt;Text&lt;/span&gt;
          &lt;span class="o"&gt;|&lt;/span&gt; &lt;span class="kt"&gt;Identifier&lt;/span&gt; &lt;span class="kt"&gt;Text&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This new &lt;code&gt;Expr&lt;/code&gt; type is an enum which can represent either a struct access operation, or an identifier (a string that references a struct by name). The specific &lt;code&gt;StructAccess&lt;/code&gt; case takes another &lt;code&gt;Expr&lt;/code&gt; as its first argument, meaning the left-hand side of the dot can be either a struct referenced by name, or another struct access operation. That is, we can chain the operation.&lt;/p&gt;

&lt;p&gt;The AST for this expression would now look something like this:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight haskell"&gt;&lt;code&gt;&lt;span class="kt"&gt;StructAccess&lt;/span&gt;
    &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="kt"&gt;StructAccess&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="kt"&gt;Identifier&lt;/span&gt; &lt;span class="s"&gt;"person"&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="s"&gt;"address"&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
    &lt;span class="s"&gt;"postCode"&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;To facilitate this we'd need to extend the &lt;code&gt;structAccess&lt;/code&gt; parser like so:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight haskell"&gt;&lt;code&gt;&lt;span class="n"&gt;identifierExpr&lt;/span&gt; &lt;span class="o"&gt;::&lt;/span&gt; &lt;span class="kt"&gt;Parser&lt;/span&gt; &lt;span class="kt"&gt;Expr&lt;/span&gt;
&lt;span class="n"&gt;identifierExpr&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="kt"&gt;Identifier&lt;/span&gt; &lt;span class="o"&gt;&amp;lt;$&amp;gt;&lt;/span&gt; &lt;span class="n"&gt;identifier&lt;/span&gt;

&lt;span class="n"&gt;structAccess&lt;/span&gt; &lt;span class="o"&gt;::&lt;/span&gt; &lt;span class="kt"&gt;Parser&lt;/span&gt; &lt;span class="kt"&gt;Expr&lt;/span&gt;
&lt;span class="n"&gt;structAccess&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="kt"&gt;StructAccess&lt;/span&gt; &lt;span class="o"&gt;&amp;lt;$&amp;gt;&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;try&lt;/span&gt; &lt;span class="n"&gt;structAccess&lt;/span&gt; &lt;span class="o"&gt;&amp;lt;|&amp;gt;&lt;/span&gt; &lt;span class="n"&gt;identifierExpr&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="o"&gt;&amp;lt;*&amp;gt;&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;dot&lt;/span&gt; &lt;span class="o"&gt;*&amp;gt;&lt;/span&gt; &lt;span class="n"&gt;identifier&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The parser now attempts to parse a &lt;code&gt;structAccess&lt;/code&gt; first (in this case, the sub-expression &lt;code&gt;person.address&lt;/code&gt;), and only accept an &lt;code&gt;identifier&lt;/code&gt; if this fails. However, this first attempt will never fail, because it will get caught in an infinite recursion. We could use parenthesis to solve this (the expression for accessing the &lt;code&gt;postCode&lt;/code&gt; would become &lt;code&gt;(person.address).postCode&lt;/code&gt;) but this isn't ideal.&lt;/p&gt;

&lt;p&gt;I was stumped on this problem for a while before arriving at a solution I'm quite happy with.&lt;/p&gt;

&lt;h2&gt;
  
  
  Flatten the grammar
&lt;/h2&gt;

&lt;p&gt;As long as we are using a recursive descent parser, there is simply no way to parse a left-recursive grammar such as this. I realised that to overcome the problem, I would have to change the structure of the AST to something that eliminates the left-recursion. I defined a new type and parser like this:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight haskell"&gt;&lt;code&gt;&lt;span class="kr"&gt;data&lt;/span&gt; &lt;span class="kt"&gt;FlatStructAccess&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="kt"&gt;FlatStructAccess&lt;/span&gt; &lt;span class="kt"&gt;Text&lt;/span&gt; &lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="kt"&gt;Text&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;

&lt;span class="n"&gt;structAccess&lt;/span&gt; &lt;span class="o"&gt;::&lt;/span&gt; &lt;span class="kt"&gt;Parser&lt;/span&gt; &lt;span class="kt"&gt;FlatStructAccess&lt;/span&gt;
&lt;span class="n"&gt;structAccess&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="kr"&gt;do&lt;/span&gt;
    &lt;span class="n"&gt;structName&lt;/span&gt; &lt;span class="o"&gt;&amp;lt;-&lt;/span&gt; &lt;span class="n"&gt;identifier&lt;/span&gt;
    &lt;span class="n"&gt;fields&lt;/span&gt; &lt;span class="o"&gt;&amp;lt;-&lt;/span&gt; &lt;span class="n"&gt;some&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;dot&lt;/span&gt; &lt;span class="o"&gt;*&amp;gt;&lt;/span&gt; &lt;span class="n"&gt;identifier&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
    &lt;span class="n"&gt;return&lt;/span&gt; &lt;span class="o"&gt;$&lt;/span&gt; &lt;span class="kt"&gt;FlatStructAccess&lt;/span&gt; &lt;span class="n"&gt;structName&lt;/span&gt; &lt;span class="n"&gt;fields&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This parser first looks for an identifier, then looks for one or more instances of field selection using the dot operator; it then passes these results to the data constructor for &lt;code&gt;FlatStructAccess&lt;/code&gt;. For the expression &lt;code&gt;person.address.postCode&lt;/code&gt;, the resulting AST would look like this:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight haskell"&gt;&lt;code&gt;&lt;span class="kt"&gt;FlatStructAccess&lt;/span&gt; &lt;span class="s"&gt;"person"&lt;/span&gt; &lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="s"&gt;"address"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="s"&gt;"postCode"&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;By eliminating left-recursion, this function is able to successfully parse the expression. However, this wasn't the AST I wanted to end up with. I wanted each &lt;code&gt;StructAccess&lt;/code&gt; to select a single field from a struct---chaining the operation would result in a nested AST as outlined earlier. I would have to restructure the AST I had, represented by &lt;code&gt;FlatStructAccess&lt;/code&gt;, into the one I wanted, and I had a feeling that would be tedious to figure out. On the contrary, it turns out that Haskell's standard &lt;code&gt;foldl&lt;/code&gt; function would do it in one line.&lt;/p&gt;

&lt;p&gt;&lt;code&gt;foldl&lt;/code&gt; has the signature:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight haskell"&gt;&lt;code&gt;&lt;span class="n"&gt;foldl&lt;/span&gt; &lt;span class="o"&gt;::&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;a&lt;/span&gt; &lt;span class="o"&gt;-&amp;gt;&lt;/span&gt; &lt;span class="n"&gt;b&lt;/span&gt; &lt;span class="o"&gt;-&amp;gt;&lt;/span&gt; &lt;span class="n"&gt;a&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="o"&gt;-&amp;gt;&lt;/span&gt; &lt;span class="n"&gt;a&lt;/span&gt; &lt;span class="o"&gt;-&amp;gt;&lt;/span&gt; &lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="n"&gt;b&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt; &lt;span class="o"&gt;-&amp;gt;&lt;/span&gt; &lt;span class="n"&gt;a&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;For its first argument, it accepts a function that takes an &lt;code&gt;a&lt;/code&gt; and a &lt;code&gt;b&lt;/code&gt; and returns another &lt;code&gt;a&lt;/code&gt;. It's second argument is an &lt;code&gt;a&lt;/code&gt; which will be fed into this function, partially applying it, and its third argument is a list of &lt;code&gt;b&lt;/code&gt;, the first of which will be passed into the partially applied function to result in a new &lt;code&gt;a&lt;/code&gt;. This new &lt;code&gt;a&lt;/code&gt; is then fed back into the function, partially applying it again, and this partially applied function is applied to the next &lt;code&gt;b&lt;/code&gt; in the list, and so on until the full list has been iterated over, culminating in a final result of type &lt;code&gt;a&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;A simple use case for &lt;code&gt;foldl&lt;/code&gt; would be to calculate the sum of a list of numbers. In this case the specific signature would be:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight haskell"&gt;&lt;code&gt;&lt;span class="n"&gt;foldl&lt;/span&gt; &lt;span class="o"&gt;::&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="kt"&gt;Int&lt;/span&gt; &lt;span class="o"&gt;-&amp;gt;&lt;/span&gt; &lt;span class="kt"&gt;Int&lt;/span&gt; &lt;span class="o"&gt;-&amp;gt;&lt;/span&gt; &lt;span class="kt"&gt;Int&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="o"&gt;-&amp;gt;&lt;/span&gt; &lt;span class="kt"&gt;Int&lt;/span&gt; &lt;span class="o"&gt;-&amp;gt;&lt;/span&gt; &lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="kt"&gt;Int&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt; &lt;span class="o"&gt;-&amp;gt;&lt;/span&gt; &lt;span class="kt"&gt;Int&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;And it would be applied like &lt;code&gt;foldl (+) 0 [1,2,3]&lt;/code&gt;. The result of this expression would be &lt;code&gt;6&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;For our use case, &lt;code&gt;Expr&lt;/code&gt; will be substituted for &lt;code&gt;a&lt;/code&gt; and &lt;code&gt;Text&lt;/code&gt; will be substituted for &lt;code&gt;b&lt;/code&gt;.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight haskell"&gt;&lt;code&gt;&lt;span class="n"&gt;foldl&lt;/span&gt; &lt;span class="o"&gt;::&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="kt"&gt;Expr&lt;/span&gt; &lt;span class="o"&gt;-&amp;gt;&lt;/span&gt; &lt;span class="kt"&gt;Text&lt;/span&gt; &lt;span class="o"&gt;-&amp;gt;&lt;/span&gt; &lt;span class="kt"&gt;Expr&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="o"&gt;-&amp;gt;&lt;/span&gt; &lt;span class="kt"&gt;Expr&lt;/span&gt; &lt;span class="o"&gt;-&amp;gt;&lt;/span&gt; &lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="kt"&gt;Text&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt; &lt;span class="o"&gt;-&amp;gt;&lt;/span&gt; &lt;span class="kt"&gt;Expr&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Remember that data constructors are just functions, and the &lt;code&gt;StructAccess&lt;/code&gt; constructor takes 2 arguments of type &lt;code&gt;Expr&lt;/code&gt; and &lt;code&gt;Text&lt;/code&gt; respectively. &lt;code&gt;StructAccess&lt;/code&gt; is a data constructor for the &lt;code&gt;Expr&lt;/code&gt; type, so that means the type signature for &lt;code&gt;StructAccess&lt;/code&gt; is &lt;code&gt;Expr -&amp;gt; Text -&amp;gt; Expr&lt;/code&gt;---the same as the first argument expected by &lt;code&gt;foldl&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;For the expression &lt;code&gt;person.address.postCode&lt;/code&gt;, &lt;code&gt;foldl&lt;/code&gt; will take an initial &lt;code&gt;Expr&lt;/code&gt; (namely &lt;code&gt;Identifier "person"&lt;/code&gt;) and use it to partially apply the &lt;code&gt;StructAccess&lt;/code&gt; constructor. It will then take the first item in the list of &lt;code&gt;fields&lt;/code&gt; (&lt;code&gt;"address"&lt;/code&gt;) and pass it to the partially applied function, resulting in &lt;code&gt;StructAccess (Identifier "person") "address"&lt;/code&gt;. This &lt;code&gt;Expr&lt;/code&gt; will then be used to partially apply &lt;code&gt;StructAccess&lt;/code&gt; again, and then the final field (&lt;code&gt;"postCode"&lt;/code&gt;) will be passed to the partially applied function, resulting in the final result: &lt;code&gt;StructAccess (StructAccess (Identifier "person") "address") "postCode"&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;The final version of the &lt;code&gt;structAccess&lt;/code&gt; parser looks like this:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight haskell"&gt;&lt;code&gt;&lt;span class="n"&gt;structAccess&lt;/span&gt; &lt;span class="o"&gt;::&lt;/span&gt; &lt;span class="kt"&gt;Parser&lt;/span&gt; &lt;span class="kt"&gt;Expr&lt;/span&gt;
&lt;span class="n"&gt;structAccess&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="kr"&gt;do&lt;/span&gt;
    &lt;span class="n"&gt;structName&lt;/span&gt; &lt;span class="o"&gt;&amp;lt;-&lt;/span&gt; &lt;span class="n"&gt;identifier&lt;/span&gt;
    &lt;span class="n"&gt;fields&lt;/span&gt; &lt;span class="o"&gt;&amp;lt;-&lt;/span&gt; &lt;span class="n"&gt;some&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;dot&lt;/span&gt; &lt;span class="o"&gt;*&amp;gt;&lt;/span&gt; &lt;span class="n"&gt;identifier&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
    &lt;span class="n"&gt;return&lt;/span&gt; &lt;span class="o"&gt;$&lt;/span&gt; &lt;span class="n"&gt;foldl&lt;/span&gt; &lt;span class="kt"&gt;StructAccess&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="kt"&gt;Identifier&lt;/span&gt; &lt;span class="n"&gt;structName&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="n"&gt;fields&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;By bootstrapping the &lt;code&gt;StructAccess&lt;/code&gt; constructor with our &lt;code&gt;structName&lt;/code&gt; and then folding it across our &lt;code&gt;fields&lt;/code&gt;, we can easily transform our flat AST into the recursive one we want.&lt;/p&gt;

&lt;p&gt;Megaparsec actually used to provide a function called &lt;code&gt;chainl1&lt;/code&gt; (documented &lt;a href="https://hackage.haskell.org/package/megaparsec-4.0.0/docs/Text-Megaparsec.html"&gt;here&lt;/a&gt;), which is an abstraction for this approach. This has since been deprecated and replaced with a helper module called &lt;a href="https://hackage.haskell.org/package/megaparsec-4.0.0/docs/Text-Megaparsec-Expr.html"&gt;Text.Megaparsec.Expr&lt;/a&gt;. I found the approach of this helper module more difficult to wrap my head around, but I may try to rework my solution to use this abstraction in the future.&lt;/p&gt;

&lt;h2&gt;
  
  
  Intermediate representations
&lt;/h2&gt;

&lt;p&gt;My central takeaway from this experience is that the AST your parser targets needn't be the one you keep. In cases like this, it makes sense to parse to an intermediate representation before reworking the result into the structure you actually want. The purpose of the parser is to transform a string of characters into a meaningful data structure. To whatever extent you can parse directly to the desired AST, you might as well do it, but you can otherwise get to the target AST in multiple steps.&lt;/p&gt;

</description>
      <category>parsing</category>
      <category>haskell</category>
      <category>recursion</category>
    </item>
    <item>
      <title>On function composition in JavaScript</title>
      <dc:creator>Hadrian Hughes</dc:creator>
      <pubDate>Wed, 06 Mar 2024 00:00:00 +0000</pubDate>
      <link>https://dev.to/hadrianhughes/on-function-composition-in-javascript-4ok3</link>
      <guid>https://dev.to/hadrianhughes/on-function-composition-in-javascript-4ok3</guid>
      <description>&lt;p&gt;In 2020, there was a proposal to add a "pipe" operator to JavaScript. It is currently in the draft stage, but its syntax has changed substantially from the original proposal. It most closely represents the pipe operator from the language &lt;a href="https://hacklang.org/"&gt;Hack&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;The new operator (&lt;code&gt;|&amp;gt;&lt;/code&gt;) would not fundamentally add new functionality to JavaScript, but would provide an alternative syntax for chaining function calls. The following expressions would be equivalent:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight javascript"&gt;&lt;code&gt;&lt;span class="nx"&gt;x&lt;/span&gt; &lt;span class="o"&gt;|&amp;gt;&lt;/span&gt; &lt;span class="nf"&gt;f&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="o"&gt;%&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="o"&gt;|&amp;gt;&lt;/span&gt; &lt;span class="nf"&gt;g&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="o"&gt;%&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="o"&gt;==&lt;/span&gt; &lt;span class="nf"&gt;g&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nf"&gt;f&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;x&lt;/span&gt;&lt;span class="p"&gt;))&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The most obvious advantage of the left-hand expression is that it represents chained function execution as a clear pipeline of function calls (hence the name), from left to right, which is more intuitive and readable than unravelling a cluster of nested function calls from the inside out. Particularly in cases where lots of functions with long names are being composed, the expression can get quite unwieldy. E.g. something like &lt;code&gt;mapStructure(validate(JSON.parse(json)))&lt;/code&gt;. In this case, the expression would most likely be split into multiple smaller ones, with intermediate values stored in variables for clarity, like&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight javascript"&gt;&lt;code&gt;&lt;span class="kd"&gt;const&lt;/span&gt; &lt;span class="nx"&gt;obj&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nx"&gt;JSON&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;parse&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;json&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
&lt;span class="kd"&gt;const&lt;/span&gt; &lt;span class="nx"&gt;validated&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nf"&gt;validate&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;obj&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
&lt;span class="kd"&gt;const&lt;/span&gt; &lt;span class="nx"&gt;mapped&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nf"&gt;mapStructure&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;validated&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;But the pipe operator would provide an alternative syntax that arguably makes it clearer what is happening because variables are not introduced into the scope which might be used multiple times. The "pipelined" version of the above would be&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight javascript"&gt;&lt;code&gt;&lt;span class="nx"&gt;json&lt;/span&gt; &lt;span class="o"&gt;|&amp;gt;&lt;/span&gt; &lt;span class="nx"&gt;JSON&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;parse&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="o"&gt;%&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="o"&gt;|&amp;gt;&lt;/span&gt; &lt;span class="nf"&gt;validate&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="o"&gt;%&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="o"&gt;|&amp;gt;&lt;/span&gt; &lt;span class="nf"&gt;mapStructure&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="o"&gt;%&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;However, the original proposal would have more closely resembled the F# forward pipe operator. The previous snippet in the F# style would be&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight javascript"&gt;&lt;code&gt;&lt;span class="nx"&gt;json&lt;/span&gt; &lt;span class="o"&gt;|&amp;gt;&lt;/span&gt; &lt;span class="nx"&gt;JSON&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;parse&lt;/span&gt; &lt;span class="o"&gt;|&amp;gt;&lt;/span&gt; &lt;span class="nx"&gt;validate&lt;/span&gt; &lt;span class="o"&gt;|&amp;gt;&lt;/span&gt; &lt;span class="nx"&gt;mapStructure&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;There are pros and cons of each, but I have to say, I prefer the F# version. The placeholder operator &lt;code&gt;%&lt;/code&gt; introduces indirection and bloat where the purpose of the proposal is to do the opposite. But regardless of the specifics of the implementation, finding out about this proposal got me thinking about composition in JavaScript more generally, and why this proposal has only come about now.&lt;/p&gt;

&lt;h2&gt;
  
  
  Methods vs functions
&lt;/h2&gt;

&lt;p&gt;There is already a mechanism in JavaScript for the chaining of &lt;em&gt;certain&lt;/em&gt; behaviours that follows a similar structure: object methods.&lt;/p&gt;

&lt;p&gt;JavaScript does not have classes, but it uses a prototypal inheritance model to associate pieces of functionality with certain types of object - these are methods. For example, we might create an object type called &lt;code&gt;Person&lt;/code&gt; and attach a &lt;code&gt;greet&lt;/code&gt; method to it like so:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight javascript"&gt;&lt;code&gt;&lt;span class="kd"&gt;function&lt;/span&gt; &lt;span class="nf"&gt;Person&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;name&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
    &lt;span class="k"&gt;this&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;name&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nx"&gt;name&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;

&lt;span class="nx"&gt;Person&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;prototype&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;greet&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="kd"&gt;function&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
    &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="s2"&gt;`Hello, &lt;/span&gt;&lt;span class="p"&gt;${&lt;/span&gt;&lt;span class="k"&gt;this&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;name&lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;&lt;span class="s2"&gt;.`&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Now if I create an instance of &lt;code&gt;Person&lt;/code&gt; for myself&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight javascript"&gt;&lt;code&gt;&lt;span class="kd"&gt;const&lt;/span&gt; &lt;span class="nx"&gt;me&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="k"&gt;new&lt;/span&gt; &lt;span class="nc"&gt;Person&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="s1"&gt;Hadrian&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;the &lt;code&gt;greet&lt;/code&gt; method will use my name without having to take an argument&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight javascript"&gt;&lt;code&gt;&lt;span class="nx"&gt;me&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;greet&lt;/span&gt;&lt;span class="p"&gt;();&lt;/span&gt; &lt;span class="c1"&gt;// =&amp;gt; "Hello, Hadrian."&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This means that a method is essentially a partially applied function. The &lt;code&gt;greet&lt;/code&gt; example above is similar to a function which takes a name, then returns &lt;em&gt;another function&lt;/em&gt; which greets that name.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight javascript"&gt;&lt;code&gt;&lt;span class="kd"&gt;const&lt;/span&gt; &lt;span class="nx"&gt;greet&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nx"&gt;name&lt;/span&gt; &lt;span class="o"&gt;=&amp;gt;&lt;/span&gt; &lt;span class="p"&gt;()&lt;/span&gt; &lt;span class="o"&gt;=&amp;gt;&lt;/span&gt; &lt;span class="s2"&gt;`Hello, &lt;/span&gt;&lt;span class="p"&gt;${&lt;/span&gt;&lt;span class="nx"&gt;name&lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;&lt;span class="s2"&gt;.`&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

&lt;span class="kd"&gt;const&lt;/span&gt; &lt;span class="nx"&gt;greetMe&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nf"&gt;greet&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="s1"&gt;Hadrian&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
&lt;span class="nf"&gt;greetMe&lt;/span&gt;&lt;span class="p"&gt;();&lt;/span&gt; &lt;span class="c1"&gt;// =&amp;gt; "Hello, Hadrian."&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The &lt;code&gt;greet&lt;/code&gt; method returns a string, and in JavaScript, strings are also objects with associated methods. Therefore, we could chain the &lt;code&gt;greet&lt;/code&gt; method with a method from the &lt;code&gt;String&lt;/code&gt; prototype.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight javascript"&gt;&lt;code&gt;&lt;span class="kd"&gt;const&lt;/span&gt; &lt;span class="nx"&gt;isGreeting&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nx"&gt;me&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;greet&lt;/span&gt;&lt;span class="p"&gt;().&lt;/span&gt;&lt;span class="nf"&gt;startsWith&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="s1"&gt;Hello&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt; &lt;span class="c1"&gt;// true&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The &lt;code&gt;Array&lt;/code&gt; prototype methods are some of the most commonly used, and they lend themselves to being chained together particularly well because they are methods on &lt;code&gt;Array&lt;/code&gt; which also return an &lt;code&gt;Array&lt;/code&gt;. We might perform a series of array transformations by chaining methods, like so:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight javascript"&gt;&lt;code&gt;&lt;span class="kd"&gt;const&lt;/span&gt; &lt;span class="nx"&gt;people&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="p"&gt;[&lt;/span&gt;
  &lt;span class="p"&gt;{&lt;/span&gt; &lt;span class="na"&gt;name&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="s1"&gt;John&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt; &lt;span class="p"&gt;},&lt;/span&gt;
  &lt;span class="p"&gt;{&lt;/span&gt; &lt;span class="na"&gt;name&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="s1"&gt;Jane&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt; &lt;span class="p"&gt;},&lt;/span&gt;
  &lt;span class="p"&gt;{&lt;/span&gt; &lt;span class="na"&gt;name&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="s1"&gt;Harry&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt; &lt;span class="p"&gt;},&lt;/span&gt;
  &lt;span class="p"&gt;{&lt;/span&gt; &lt;span class="na"&gt;name&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="s1"&gt;Jane&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt; &lt;span class="p"&gt;}&lt;/span&gt;
&lt;span class="p"&gt;];&lt;/span&gt;

&lt;span class="c1"&gt;// Return a list of unique names that start with 'J'&lt;/span&gt;
&lt;span class="kd"&gt;const&lt;/span&gt; &lt;span class="nx"&gt;uniqueJNames&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nx"&gt;people&lt;/span&gt;
    &lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;map&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;person&lt;/span&gt; &lt;span class="o"&gt;=&amp;gt;&lt;/span&gt; &lt;span class="nx"&gt;person&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;name&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
    &lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;filter&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;name&lt;/span&gt; &lt;span class="o"&gt;=&amp;gt;&lt;/span&gt; &lt;span class="nx"&gt;name&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;startsWith&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="s1"&gt;J&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="p"&gt;))&lt;/span&gt;
    &lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;reduce&lt;/span&gt;&lt;span class="p"&gt;((&lt;/span&gt;&lt;span class="nx"&gt;acc&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nx"&gt;name&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="o"&gt;=&amp;gt;&lt;/span&gt; &lt;span class="nx"&gt;acc&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;includes&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;name&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;?&lt;/span&gt; &lt;span class="nx"&gt;acc&lt;/span&gt; &lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="p"&gt;[...&lt;/span&gt;&lt;span class="nx"&gt;acc&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nx"&gt;name&lt;/span&gt;&lt;span class="p"&gt;],&lt;/span&gt; &lt;span class="p"&gt;[]);&lt;/span&gt; &lt;span class="c1"&gt;// =&amp;gt; ['John', 'Jane']&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;As long as the behaviour you want to compose is encoded in prototype methods, JavaScript allows you to easily create clear, pipeline-esque chains of functionality - but that's a big if.&lt;/p&gt;

&lt;h2&gt;
  
  
  Why now?
&lt;/h2&gt;

&lt;p&gt;JavaScript is not the most principled language. In most cases, if you don't like a programming language, you can just use a different one; even in the case of Java, which is king of the JVM, there are other languages that can nonetheless exist in that environment, like Clojure and Scala.&lt;/p&gt;

&lt;p&gt;On the other hand, JavaScript is &lt;em&gt;the&lt;/em&gt; language of the browser, and as such, when the programming zeitgeist moves on to a new paradigm, pressure grows for JavaScript to incorporate elements of that paradigm. As a result, JavaScript is a bit of a Frankenstein. As previously mentioned, JavaScript doesn't have classes, but it does feature class syntax which gives the programmer the option of writing code in a way that &lt;em&gt;feels&lt;/em&gt; object-oriented. In truth it is syntactic sugar over the existing prototypal inheritance model.&lt;/p&gt;

&lt;p&gt;In recent years, certain aspects of functional programming have become popular, like lambda expressions, immutability and functions as first-class entities. ES6 formally introduced these concepts into JavaScript with new syntax, like arrow functions and the &lt;code&gt;const&lt;/code&gt; and &lt;code&gt;let&lt;/code&gt; keywords, and they have become central elements of the language - so much so that &lt;code&gt;var&lt;/code&gt; is rarely seen and arrow functions might be more widely used than the traditional &lt;code&gt;function&lt;/code&gt; syntax.&lt;/p&gt;

&lt;p&gt;Prototypal inheritance, by comparison, has fallen out of favour. Although standard prototype methods like the aforementioned &lt;code&gt;Array&lt;/code&gt; methods are used as much as ever, it's rare to see custom methods being attached to prototypes in a modern codebase. Instead, functionality is typically encoded into ordinary functions. This explains why the proposal for a pipe operator has only appeared quite recently: prototypal inheritance and the optional class syntax are JavaScript's current options for composition, and we're not using them. However, technically speaking, the pipe operator is not for function composition, but function application.&lt;/p&gt;

&lt;h2&gt;
  
  
  What is really missing?
&lt;/h2&gt;

&lt;p&gt;As previously mentioned, JavaScript's implementation of lambda expressions (which it calls arrow functions) are used very widely - arguably a little too widely. Although lambda expressions are a feature of functional languages, these languages tend not to promote using them too frequently; they are a tool for encoding particularly unique logic that is unlikely to be repeated. It is usually better to represent complex logic as an expression of simpler functions - by composing them.&lt;/p&gt;

&lt;p&gt;Often the syntax for lambda expressions is ugly, and this is my own conjecture, but I suspect it is intentional to discourage using them. The epitome of this can be found in Python:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight python"&gt;&lt;code&gt;&lt;span class="n"&gt;inc&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="k"&gt;lambda&lt;/span&gt; &lt;span class="n"&gt;x&lt;/span&gt; &lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="n"&gt;x&lt;/span&gt; &lt;span class="o"&gt;+&lt;/span&gt; &lt;span class="mi"&gt;1&lt;/span&gt;
&lt;span class="nf"&gt;inc&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="c1"&gt;# =&amp;gt; 2
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;em&gt;If you really want a lambda expression you'd better spell it out.&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;In JavaScript, even if we want to compose functions, arrow functions are how we have to do it because there is no built-in way to compose functions independently of their inputs. As previously mentioned, the proposed pipe operator is inspired by Hack, but it is not too dissimilar to the F# forward pipe. But F# has another operator specifically for &lt;em&gt;composing&lt;/em&gt; functions. Using this operator we could encapsulate the JSON example from earlier into a named function like so:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight fsharp"&gt;&lt;code&gt;&lt;span class="k"&gt;let&lt;/span&gt; &lt;span class="n"&gt;handleJson&lt;/span&gt; &lt;span class="p"&gt;=&lt;/span&gt; &lt;span class="nn"&gt;JSON&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;parse&lt;/span&gt; &lt;span class="o"&gt;&amp;gt;&amp;gt;&lt;/span&gt; &lt;span class="n"&gt;validate&lt;/span&gt; &lt;span class="o"&gt;&amp;gt;&amp;gt;&lt;/span&gt; &lt;span class="n"&gt;mapStructure&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;There is no need to make any reference to the &lt;code&gt;json&lt;/code&gt; variable that will be passed into the function - the functions can be composed independently from their inputs. To do the same thing in JavaScript would require an arrow function, meaning the argument that will be ultimately passed to the function has to be handled explicitly:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight javascript"&gt;&lt;code&gt;&lt;span class="kd"&gt;const&lt;/span&gt; &lt;span class="nx"&gt;handleJson&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nx"&gt;json&lt;/span&gt; &lt;span class="o"&gt;=&amp;gt;&lt;/span&gt; &lt;span class="nf"&gt;mapStructure&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nf"&gt;validate&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;JSON&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;parse&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;json&lt;/span&gt;&lt;span class="p"&gt;)));&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In my opinion, the proposed pipe operator wouldn't add much utility to JavaScript, but a true composition operator would be a welcome addition.&lt;/p&gt;

&lt;h2&gt;
  
  
  Existing solutions
&lt;/h2&gt;

&lt;p&gt;There are JavaScript libraries which attempt to solve this problem. For example, Ramda includes a &lt;code&gt;pipe&lt;/code&gt; function which composes functions just like the F# compose operator. For example, to repeat the previous example of parsing and mapping a JSON structure, the equivalent using Ramda would be the following snippet.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight javascript"&gt;&lt;code&gt;&lt;span class="kd"&gt;const&lt;/span&gt; &lt;span class="nx"&gt;handleJson&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nx"&gt;R&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;pipe&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;JSON&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;parse&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nx"&gt;validate&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nx"&gt;mapStructure&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This does result in a similarly clean structure that resembles a pipeline - it works well. However, it isn't obvious in which direction the functions are evaluated. It so happens that the functions will be evaluated from left to right, but there is nothing about the syntax that makes that obvious. This wouldn't be any less confusing to someone with a background in a functional language like Haskell, because functional languages vary in their direction of composition. In Haskell, composed functions are evaluated from right to left, like so:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight haskell"&gt;&lt;code&gt;&lt;span class="n"&gt;handleJson&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;mapStructure&lt;/span&gt; &lt;span class="o"&gt;.&lt;/span&gt; &lt;span class="n"&gt;validate&lt;/span&gt; &lt;span class="o"&gt;.&lt;/span&gt; &lt;span class="kt"&gt;JSON&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="n"&gt;parse&lt;/span&gt;
&lt;span class="c1"&gt;-- equivalent to&lt;/span&gt;
&lt;span class="c1"&gt;-- handleJson json = mapStructure (validate (JSON.parse json))&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;One advantage of the F# composition operator is that it resembles an arrow, making the flow of execution abundantly clear.&lt;/p&gt;

&lt;p&gt;At the end of the day, JavaScript is not a functional language; it's a hodgepodge of different paradigms, one of them being functional. Ideally, a language would have strong principles, meaning updates and feature proposals would rarely be necessary. But JavaScript has a specific role in web development that incentivises it to change with the times - if a new feature would improve the way we currently use the language, then it is a good change. With that said, the pipe operator proposal in its current state is a marginal improvement, if an improvement at all. I think a true composition operator would be a much more valuable addition to the language.&lt;/p&gt;

</description>
      <category>javascript</category>
      <category>functional</category>
      <category>composition</category>
      <category>pipe</category>
    </item>
    <item>
      <title>A Tale of Two Paradigms</title>
      <dc:creator>Hadrian Hughes</dc:creator>
      <pubDate>Sat, 24 Feb 2024 00:00:00 +0000</pubDate>
      <link>https://dev.to/hadrianhughes/a-tale-of-two-paradigms-43e3</link>
      <guid>https://dev.to/hadrianhughes/a-tale-of-two-paradigms-43e3</guid>
      <description>&lt;p&gt;Recently I've been thinking about the handling of "side effects" in programming languages. Most (basically all) of the programming languages we use in industry don't include a notion of side effects in their semantics. In procedural and object-oriented languages, a program's behaviour is broken down into procedures or methods, respectively, which consist of statements to be executed. Each of these statements may or may not perform an operation that would be considered a side effect, like logging a message to the console, requesting input from the user, interacting with a web API - basically anything that affects or depends upon something in the world outside the program.&lt;/p&gt;

&lt;p&gt;Advocates of functional programming often point to this (correctly, I think) as a fundamental weakness of the most widely used languages, and one of the biggest strengths of functional programming languages like Haskell. In the latter, a program consists entirely of functions, and these functions simply map their arguments to some output and do nothing more. Detractors are then quick to point out (also correctly, I think) that side effects are not a problem, they are the reason we write code. If a language were to disallow I/O altogether, we would have no way of interacting with it, and it would be rendered completely useless. This is true, and this is why I think "side effects" are really more accurately termed, simply "effects".&lt;/p&gt;

&lt;p&gt;However, Haskell does have support for effects like I/O, but these kinds of operations are encoded by specific types like the &lt;code&gt;IO&lt;/code&gt; type. The function signature &lt;code&gt;foo :: IO a&lt;/code&gt; lets the compiler know that when executed, the function &lt;code&gt;foo&lt;/code&gt; will perform some effect involving I/O which, if successful, will return a value of type &lt;code&gt;a&lt;/code&gt;. That is, &lt;code&gt;foo&lt;/code&gt; does not return an &lt;code&gt;a&lt;/code&gt;, it returns an instruction for performing an effect whose "happy path" produces an &lt;code&gt;a&lt;/code&gt;. This kind of explicit identification of an effect allows the compiler to ensure that each of its possible outcomes are handled safely.&lt;/p&gt;

&lt;h2&gt;
  
  
  The problem with procedural languages
&lt;/h2&gt;

&lt;p&gt;While Haskell can't guarantee that effects won't produce errors (the real world is unpredictable), it can guarantee that functions are referentially transparent, meaning any function call can be replaced by the output it produces, without affecting the program's behaviour. That is, if a function returns an &lt;code&gt;Int&lt;/code&gt;, each instance where that function is called can be treated &lt;em&gt;as if it is&lt;/em&gt; an &lt;code&gt;Int&lt;/code&gt;. This principle means that functions can &lt;em&gt;always&lt;/em&gt; be composed with other functions, and the result will &lt;em&gt;always&lt;/em&gt; be predictable; as long as the types match up, the functions compose.&lt;/p&gt;

&lt;p&gt;Even in procedural languages that have strong type systems, like Rust, we don't get these same guarantees. A function might say that it returns &lt;code&gt;i32&lt;/code&gt;, but that result might be dependent on an API call that could fail or result in different values at different times. Continuing with the example of Rust, we hope that if the function could fail then it would have a return type of &lt;code&gt;Result&amp;lt;i32&amp;gt;&lt;/code&gt; (Rust offers the &lt;code&gt;Result&lt;/code&gt; type to encapsulate operations that could fail), but that is down to the discretion of the programmer who wrote it - they could just as easily return an erroneous value that is still of type &lt;code&gt;i32&lt;/code&gt;, like &lt;code&gt;0&lt;/code&gt;.&lt;/p&gt;

&lt;h2&gt;
  
  
  The problem with functional languages
&lt;/h2&gt;

&lt;p&gt;All of this to say, I like Haskell and functional programming in general. But the problem is that for the most part, nobody uses them, and I can't really blame them. I've been building side projects and generally playing around with Haskell for a few years now, and I still don't feel that I have as strong an understanding of it as I do of languages that I've used for a fraction of the time. Haskell is steeped in esoteric mathematics, and while it is relevant and interesting, it is also dense and difficult. And furthermore, while it is possible to write working Haskell programs without being able to properly explain why a monad is "just a monoid in the category of endofunctors", trying to convince software engineers to pick up a language so foreign and unintuitive is difficult. The problem is that it is because of its rigorous mathematical backbone that Haskell is so safe.&lt;/p&gt;

&lt;p&gt;Procedural semantics result in code that expresses what the computer should &lt;em&gt;do&lt;/em&gt;, while functional semantics result in code that describes what things &lt;em&gt;are&lt;/em&gt;; the former is more imperative while the latter is more declarative. Neither of these approaches is necessarily superior, but as an engineer, when you know what you want your program to do, having to deconstruct the problem into a kind of library of abstractions which you then recompose into a working program, seems tortuously indirect. From the perspective of practicality, I think this is a point in favour procedural languages (or imperative languages more broadly).&lt;/p&gt;

&lt;p&gt;We only become more dependent on software, not less, and I think that the lack of a way of handling effects as what they truly are - dependencies on the fuzzy outside world that are highly likely to fail - is a pressing deficiency that modern languages need to tackle. While Haskell does this, it realistically isn't going to be adopted broadly any time soon, nor is anything like it. However, there doesn't seem to be any reason why correctly representing effects in a type system would be incompatible with an imperative style, and I wonder if there isn't a way for us to reap the benefits of both paradigms.&lt;/p&gt;

</description>
      <category>procedural</category>
      <category>functional</category>
      <category>sideeffects</category>
      <category>haskell</category>
    </item>
    <item>
      <title>Software development is not like surgery</title>
      <dc:creator>Hadrian Hughes</dc:creator>
      <pubDate>Mon, 19 Feb 2024 00:00:00 +0000</pubDate>
      <link>https://dev.to/hadrianhughes/software-development-is-not-like-surgery-1i1a</link>
      <guid>https://dev.to/hadrianhughes/software-development-is-not-like-surgery-1i1a</guid>
      <description>&lt;p&gt;Pair and mob programming are often seen as the gold standard for collaboration. Multiple developers sit around a computer (or on a video call) and combine their efforts to work on a single problem, which reduces the time needed to solve it and allows for immediate feedback---two heads are better than one.&lt;/p&gt;

&lt;p&gt;In fact, a previous colleague once told me that he thinks we should be pair or mob programming all the time. He presented his argument as a simple syllogism:&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Premise 1:&lt;/strong&gt;     In surgery, a simple instance of human error could be catastrophic for the patient, so surgeons are expected to work as part of a team to decrease their chances of making a mistake.&lt;br&gt;&lt;br&gt;
&lt;strong&gt;Premise 2:&lt;/strong&gt;    As software takes over more and more of the systems we all rely on, the consequences of a mistake in software development could be similarly catastrophic.&lt;br&gt;&lt;br&gt;
&lt;strong&gt;Conclusion:&lt;/strong&gt; Software developers should always be mob or pair programming to prevent these kinds of mistakes.&lt;/p&gt;

&lt;p&gt;I think the argument is a sound one. It's worth mentioning that each person in an operating theatre has a different role, which isn't typically the case when mob programming, but reducing errors is certainly another major reason for the approach---I wouldn't feel nearly as confident going into surgery if I knew the surgeon would be acting alone.&lt;/p&gt;

&lt;p&gt;And it's true that increasingly, a bug in a piece of software can be more than a minor annoyance, and can instead have dire consequences. The recent publicity around the Horizon scandal in the UK has made that clear: a bug in the Post Office's accounting software led to hundreds of postmasters being wrongfully convicted of serious crimes.&lt;/p&gt;

&lt;p&gt;But there is a crucial difference between surgery and software that informs why human error is necessarily so dangerous in the former, but not in the latter. If a surgeon makes a mistake that causes damage, that mistake cannot be taken back. It might be possible to fix the damage, but there is no backtracking---the action is final. In an ideal world, the surgeon would make their changes in an isolated environment, like a draft state, then they would hand their work over to another surgeon for review. When the team has taken their time to search for errors and ensure that everything has gone to plan, they would "commit" their changes and they would be applied to the patient for real (&lt;em&gt;you see where I'm going&lt;/em&gt;). In such a world, if a surgeon felt that their best work happened when they worked alone, they would be able to do so without consequence; some surgeons might still work in groups, but only if they felt that it was helpful.&lt;/p&gt;

&lt;p&gt;Maybe technology will one day make this kind of workflow a reality, but as things currently are, surgeons live in an imperfect world where their changes are always necessarily final. In software on the other hand, we do live in this ideal world. Because of tools like Git, every developer has their own, isolated environment where no matter how much damage they wreak, users of their software will be completely unaffected. It's only once their changes are deployed into production that any mistakes bear fruit (hopefully after a period of thorough peer review where they are caught and fixed). For this reason, even if a developer has worked on a feature completely alone, there is still ample opportunity for their changes to be reviewed by their teammates asynchronously.&lt;/p&gt;

&lt;p&gt;My point here is not to suggest that we shouldn't be pairing or mobbing, but that we have the luxury of choosing without putting users of our software at risk. To speak for myself, I am one of those aforementioned people whose best work happens alone. Being surrounded by teammates while trying to reason about a problem creates pressure that distracts me from the task, like someone looking over your shoulder while you type an email. On the other hand, I'm more than happy to pair on a problem with a teammate if they feel it will help them---we should be flexible and consider the differing working styles of our teammates.&lt;/p&gt;

&lt;p&gt;This does of course mean that we have a responsibility to perform robust, in-depth peer reviews before our code reaches users. Creating well-structured, intentional commits with meaningful messages is crucial to ensuring that the teammate who reviews your code is able to properly understand it, even when the pull request is large. However, I'd argue that these sorts of practices have benefits beyond enabling flexible styles of teamwork.&lt;/p&gt;

&lt;p&gt;During a pairing session, valuable feedback might be given, but it isn't captured. The solution to a problem might be well-understood by the people who worked on it, but down the line a new team member might revisit that same section of code, and will not have any of that context. Git commits and pull requests are captured and stored, enabling communication with future team members, even after the author of the feedback has left the team.&lt;/p&gt;

&lt;p&gt;This kind of communication is invisible until it's needed, which I suspect is one of the reasons why pair programming is often pushed for by project managers. The latter is the most visible form of collaboration, which assures those in less hands-on roles that teamwork is indeed happening. But I'd suggest that asynchronous collaboration and communication is more important to ensure continued code quality over long periods of time and despite team changes.&lt;/p&gt;

&lt;p&gt;As more and more aspects of our lives are influenced by software, it is absolutely the responsibility of dev teams to ensure that good practices are followed to avoid introducing bugs that could have serious consequences for users. But the intangible nature of our work gives us a kind of flexibility of working styles not enjoyed in many other fields, and we should take advantage of this flexibility to enable developers to contribute fully to collaborative practices while working in the way that works best for them.&lt;/p&gt;

</description>
      <category>pairprogramming</category>
      <category>collaboration</category>
      <category>git</category>
      <category>codereview</category>
    </item>
    <item>
      <title>Bulletproof React: Understanding The Functional Reactive Approach</title>
      <dc:creator>Hadrian Hughes</dc:creator>
      <pubDate>Tue, 21 Apr 2020 20:39:19 +0000</pubDate>
      <link>https://dev.to/hadrianhughes/bulletproof-react-understanding-the-functional-reactive-approach-33kd</link>
      <guid>https://dev.to/hadrianhughes/bulletproof-react-understanding-the-functional-reactive-approach-33kd</guid>
      <description>&lt;p&gt;The principles of functional programming are becoming more in fashion every day. More and more traditionally imperative languages are implementing lambda functions, immutability and lazy evaluation. It's exciting to see, and even more encouraging to see that React is at the forefront of these changes.&lt;/p&gt;

&lt;p&gt;React has always encouraged functional principles in some capacity; Redux has long been the most popular approach to building large scale apps. However, the advent of React hooks has made it clear that this preference for functional over imperative is very intentional, and it's here to stay. With all that said, I still hear the complaint that Redux is confusing, or seems "magical". There are also plenty of developers who think Redux is made obsolete by React's Context API, and while there's some truth to this, there are still some huge benefits to be gained by using the Redux approach, so I'd like to dedicate a post to demystifying just how it works and to outlining those benefits.&lt;/p&gt;

&lt;p&gt;The most obvious benefit of using Redux would be that it moves all of your app state to a single source of truth, making it much easier to ensure that components stay in sync with one another. But there's more. Let's start by laying out all the key components of the Redux architecture.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fi%2Fswzkvy0624myne44uldn.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fi%2Fswzkvy0624myne44uldn.png" alt="Redux Diagram" width="698" height="554"&gt;&lt;/a&gt;&lt;em&gt;Notice there is no 'store' entity in the diagram because the store is a transient value passed to the view from the reducer.&lt;/em&gt;&lt;/p&gt;

&lt;h2&gt;
  
  
  The Store
&lt;/h2&gt;

&lt;p&gt;At the core of everything in a Redux app is the store. It's easy to think of the store as a container for all of your state which you can update, but the store is in fact immutable. It's a value passed through your app just like arguments to a function, and the only way to "change" the value is to call the function again with different arguments.&lt;/p&gt;

&lt;p&gt;To better visualise this, let's create a very simple functional reactive app in JavaScript.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight javascript"&gt;&lt;code&gt;&lt;span class="c1"&gt;// &amp;lt;button id="myButton"&amp;gt;&amp;lt;/button&amp;gt; defined in HTML&lt;/span&gt;

&lt;span class="kd"&gt;function&lt;/span&gt; &lt;span class="nf"&gt;myApp&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;state&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
  &lt;span class="kd"&gt;function&lt;/span&gt; &lt;span class="nf"&gt;dispatch&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
    &lt;span class="nf"&gt;myApp&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;state&lt;/span&gt; &lt;span class="o"&gt;+&lt;/span&gt; &lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
  &lt;span class="p"&gt;}&lt;/span&gt;

  &lt;span class="kd"&gt;const&lt;/span&gt; &lt;span class="nx"&gt;btn&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nb"&gt;document&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;getElementById&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="s1"&gt;myButton&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
  &lt;span class="nx"&gt;btn&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;innerHTML&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nx"&gt;state&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
  &lt;span class="nx"&gt;btn&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;onclick&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nx"&gt;dispatch&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;

&lt;span class="nf"&gt;myApp&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;We define our app as a function &lt;code&gt;myApp&lt;/code&gt; which accepts our state as its argument. Within the context of &lt;code&gt;myApp&lt;/code&gt; we define a closure called &lt;code&gt;dispatch&lt;/code&gt;, which simply calls &lt;code&gt;myApp&lt;/code&gt; again with updated state (the previous state + 1). We then use our state as the button's text label, and bind &lt;code&gt;dispatch&lt;/code&gt; to the button's &lt;code&gt;onclick&lt;/code&gt; listener. Finally, we bootstrap the app with a starting state value of 0. Now every time we click the button, its value will increase by 1 as &lt;code&gt;myApp&lt;/code&gt; reruns with the updated state.&lt;/p&gt;

&lt;p&gt;Simple, right? There's no magic here - this is functional reactive programming in its most basic form.&lt;/p&gt;

&lt;p&gt;To bring it back to Redux, the &lt;code&gt;state&lt;/code&gt; argument in our example would be the store in Redux. It's immutable - or more to the point, mutating it would have no effect because the app has already consumed it and finished running - and we have to use a dispatcher function to make changes to it. Redux also exposes a &lt;code&gt;dispatch&lt;/code&gt; function which we either pass down to components via props, or we use the react-redux higher-order component &lt;code&gt;connect&lt;/code&gt; to avoid props drilling. However, Redux's dispatcher function doesn't directly rerun the app, but the extra step is part of what makes it so powerful.&lt;/p&gt;

&lt;h2&gt;
  
  
  Actions And The Reducer
&lt;/h2&gt;

&lt;p&gt;When the &lt;code&gt;dispatch&lt;/code&gt; function is called following a user interaction, it is passed an &lt;em&gt;action&lt;/em&gt;. An action consists of a &lt;em&gt;type&lt;/em&gt; and a &lt;em&gt;payload&lt;/em&gt;. This action is then passed through a &lt;em&gt;reducer function&lt;/em&gt;. This is where the magic happens. The following is a simple example of a reducer function:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight javascript"&gt;&lt;code&gt;&lt;span class="kd"&gt;const&lt;/span&gt; &lt;span class="nx"&gt;initialState&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

&lt;span class="kd"&gt;function&lt;/span&gt; &lt;span class="nf"&gt;reducer&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;state&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nx"&gt;initialState&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nx"&gt;action&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
  &lt;span class="k"&gt;switch &lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;action&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;type&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
    &lt;span class="k"&gt;case&lt;/span&gt; &lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="s1"&gt;ADD&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
      &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="nx"&gt;state&lt;/span&gt; &lt;span class="o"&gt;+&lt;/span&gt; &lt;span class="nx"&gt;action&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;payload&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
    &lt;span class="k"&gt;case&lt;/span&gt; &lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="s1"&gt;SUBTRACT&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
      &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="nx"&gt;state&lt;/span&gt; &lt;span class="o"&gt;-&lt;/span&gt; &lt;span class="nx"&gt;action&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;payload&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
    &lt;span class="nl"&gt;default&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
      &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="nx"&gt;state&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
  &lt;span class="p"&gt;}&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Our reducer function accepts two arguments: the current state and the action passed to the dispatcher function. We check the action type and apply a transformation based on it. If the type is &lt;code&gt;ADD&lt;/code&gt;, we return the current state plus the action payload; if the type is &lt;code&gt;SUBTRACT&lt;/code&gt;, we return the current state minus the action payload. This returned value will become the app's new state.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight javascript"&gt;&lt;code&gt;&lt;span class="kd"&gt;const&lt;/span&gt; &lt;span class="nx"&gt;myAddAction&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
  &lt;span class="na"&gt;type&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="s1"&gt;ADD&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
  &lt;span class="na"&gt;payload&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="mi"&gt;3&lt;/span&gt;
&lt;span class="p"&gt;};&lt;/span&gt;

&lt;span class="nf"&gt;reducer&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;5&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nx"&gt;myAddAction&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt; &lt;span class="c1"&gt;// This would perform 5 + 3 to return 8&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Transforming our state using a reducer function means the state can only be transformed in a finite number of ways, which are all immediately visible when you view this function. No matter what we do, we can't multiply or divide the state without adding a new case to the reducer's switch statement. This is very powerful: no more tracking down where a logic error is coming from. If a state update happens it &lt;strong&gt;must&lt;/strong&gt; be happening in the reducer function; the only question is where the dispatcher function was called from, which is easy to track down using a stack trace.&lt;/p&gt;

&lt;h2&gt;
  
  
  Side Effects
&lt;/h2&gt;

&lt;p&gt;It's time to go a little deeper into functional terminology (but only a little). Our app is now more deterministic thanks to all state updates being centralised in one function. However, how will our app communicate with the outside world?&lt;/p&gt;

&lt;p&gt;In functional programming, any computation which doesn't consist of a function returning an expression based solely on its arguments is called a &lt;em&gt;side effect&lt;/em&gt;. An app without side effects is useless; at the very least we need a way for our app to receive input and give output, and since both of these things rely on conditions being met in the outside world (e.g. the code being run in a browser with a DOM API for us to interact with) they would be considered side effects. However, just because our apps rely on side effects doesn't mean we should pretend they don't exist. Thinking proactively about where the side effects in your app are allows you to reduce the number of them you create, and to manage them safely.&lt;/p&gt;

&lt;p&gt;Thankfully, React deals with IO for us and allows us to write pure computations safely behind the abstraction of the virtual DOM, but what if we want to get some data from a remote API over HTTP? Typically we'd just place this in a &lt;code&gt;useEffect&lt;/code&gt; hook in one of our components, but this is less than ideal. For example, what if we have two of the same component on one page, and both of the instances perform the HTTP request? One of them would be completely redundant. We can program around this using finicky conditionals, but who wants that? Wouldn't it be the icing on the cake to not have to go through the ordeal?&lt;/p&gt;

&lt;p&gt;We can solve this by using a Redux middleware. A middleware sits between the dispatcher function and the reducer function. An interaction causes &lt;code&gt;dispatch&lt;/code&gt; to be called with an action; the action is then passed through any middlewares we set up, before finally reaching the reducer.&lt;/p&gt;

&lt;p&gt;Let's say we're building an app which includes a list of users. On the initial page load we might dispatch an action to fetch the list of users from an API:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight javascript"&gt;&lt;code&gt;&lt;span class="p"&gt;{&lt;/span&gt; &lt;span class="nl"&gt;type&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="s1"&gt;FETCH_USERS&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt; &lt;span class="p"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This isn't an action type which is recognised by the reducer, so it won't trigger a state update. Instead, we tell a middleware to wait for any actions with a type of &lt;code&gt;FETCH_USERS&lt;/code&gt; and then perform a get request to the remote API. When a response comes back, the middleware calls the dispatcher function again with a new action:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight javascript"&gt;&lt;code&gt;&lt;span class="p"&gt;{&lt;/span&gt;
  &lt;span class="nl"&gt;type&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="s1"&gt;SET_USERS&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
  &lt;span class="nx"&gt;payload&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="nx"&gt;users&lt;/span&gt; &lt;span class="c1"&gt;// 'users' is the response body&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This subsequent &lt;code&gt;SET_USERS&lt;/code&gt; action is picked up by the reducer and the app reruns with the new state which includes the fetched list of users. No searching for the component responsible for fetching a piece of data, we know it always happens in a middleware.&lt;/p&gt;

&lt;p&gt;The most popular Redux middleware libraries are redux-saga and redux-thunk. They use very different approaches but both have their pros and cons.&lt;/p&gt;

&lt;h2&gt;
  
  
  In Summary
&lt;/h2&gt;

&lt;p&gt;So what have we gained? In short, transparency and determinism. Each aspect of our app is now clearly defined and has a dedicated place. The view is handled by React, but we can now be sure that it is composed of only pure functions which receive their props and return markup. &lt;strong&gt;All&lt;/strong&gt; state transformations are triggered by actions and performed by the reducer function. All side effects (besides IO which is handled by React) are isolated within middlewares where nothing else depends on their success.&lt;/p&gt;

&lt;p&gt;Using this approach, our apps can scale indefinitely with minimal runtime errors and without logic errors becoming impossible to track down and manage.&lt;/p&gt;

</description>
      <category>react</category>
      <category>functional</category>
      <category>redux</category>
      <category>javascript</category>
    </item>
  </channel>
</rss>
