<?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>Brady Ouren's home page feed.</title>
        <link>http://brdyorn.com</link>
        <description><![CDATA[Brady Ouren's home page feed.]]></description>
        <atom:link href="http://brdyorn.com/feed.xml" rel="self"
                   type="application/rss+xml" />
        <lastBuildDate>Sat, 07 Oct 2017 00:00:00 UT</lastBuildDate>
        <item>
    <title>The Codegen Hammer</title>
    <link>http://brdyorn.com/posts/2017-10-07-the-codegen-hammer.html</link>
    <description><![CDATA[<div class="info">
  <!-- Posted on Oct  7, 2017 -->
  
</div>

<h1 class="section-block blog">The Codegen Hammer</h1>
<div class="post-body">
  <p>If you must build a Single Page App, it would be nice to avoid some of the work generally required in a separate codebase. Personally, I look for these attributes to justify the overhead:</p>
<ul>
<li>Easy to build on - if it takes slightly longer to bootstrap, that’s fine.</li>
<li>Hard to break - interfaces are shared and nearly 1-to-1*</li>
<li>Remove Redundancy - (more code is more maintenance)</li>
</ul>
<p>The below is an extended description of the process I talked about at Purescript LA. (slides <a href="/slides/bridge-talk.html">here</a>)</p>
<p>The 2 goals for minimum viability in my mind are:</p>
<ol style="list-style-type: decimal">
<li>provide correct interfaces for domain-specific queries to build on.</li>
<li>ensure handling all responses from the server.</li>
</ol>
<h2 id="a-big-hammer">A Big Hammer</h2>
<p>Codegen can be a bit dangerous to wield, but I’ll argue here for certain cases where it makes sense and the benefit outweighs the cost.</p>
<p>Anything you are serializing across a network should be considered for codegen. If you’re using haskell for your client code, by all means, share your types! For the rest of us using Purescript, we have the fantastic work of <a href="https://github.com/eskimor/purescript-bridge">purescript-bridge</a>. If you happen to be using Servant you could further utilize <a href="https://github.com/eskimor/servant-purescript">servant-purescript</a>. However, my experience was with a Yesod API. Either way, you’ll depend on the generic json deriving of Aeson (haskell) and <a href="https://github.com/eskimor/purescript-argonaut-generic-codecs/">argonaut’s generic codecs</a> which are directly compatible with aeson.</p>
<h2 id="forms-are-a-subset-of-your-model">Forms are a subset of your model</h2>
<p>The low-hanging fruit of this approach is form interactions. Your forms will likely be different than your database representations, so this is a nice place to set up types to describe the frontend <em>input</em>. Say one of our pages is submitting an email of someone who should be invited to the platform. The database representation might include a token, inviter’s id, date invited, etc, but you only need an email and a personal note attached.</p>
<div class="sourceCode"><pre class="sourceCode haskell"><code class="sourceCode haskell"><span class="kw">data</span> <span class="dt">CuratorForm</span> <span class="fu">=</span> <span class="dt">CuratorForm</span> 
  {<span class="ot"> email ::</span> <span class="dt">EmailAddress</span>
  ,<span class="ot"> message ::</span> <span class="dt">Text</span> }</code></pre></div>
<p>This is what the haskell backend expects as a POST so if our form is directly using this type in purescript we can be certain we won’t screw up and send the wrong things.</p>
<p>I’ll gloss over the form implementation here because it’s pretty similar to what’s covered in “<a href="https://leanpub.com/purescript">Purescript by Example</a>” and covered in detail a bit futher <a href="/posts/2017-10-07-a-writer-purescript-form.html">here</a></p>
<div class="sourceCode"><pre class="sourceCode haskell"><code class="sourceCode haskell">initialState <span class="fu">=</span> { form<span class="fu">:</span> curatorForm }

curatorForm <span class="fu">=</span> <span class="dt">CuratorForm</span> { email<span class="fu">:</span> <span class="st">&quot;&quot;</span>, message<span class="fu">:</span> <span class="dt">Nothing</span> }

render state <span class="fu">=</span> <span class="kw">do</span>
  <span class="co">-- ...</span>
  div_ <span class="fu">$</span> Form.renderForm state<span class="fu">.</span>form <span class="dt">NewCurator</span> <span class="kw">do</span>
    void <span class="fu">$</span> Form.textField <span class="st">&quot;message&quot;</span> <span class="st">&quot;A Note&quot;</span> _message Form.optional
    Form.textField <span class="st">&quot;email&quot;</span>   <span class="st">&quot;Email&quot;</span>  _email   (Form.nonBlank <span class="fu">&lt;=&lt;</span> Form.emailValidator)</code></pre></div>
<p>Something worth noting here is the 3rd arguments to <code>textField</code>. These lens’ are generated from purescript-bridge (along with Prisms for <code>CreateResponse</code>) and they’re used to access and set values in the form where <code>state.form</code> is giving us the <code>CuratorForm</code> which is also generated from our haskell types. The only thing here that’s actually locally defined is the <code>NewCurator</code> input event. That’s all that should be needed to hook this form into your state.</p>
<div class="sourceCode"><pre class="sourceCode haskell"><code class="sourceCode haskell">  <span class="co">-- the CuratorForm is the &#39;form&#39; field of our state.</span>
  response <span class="ot">&lt;-</span> post (apiUrl <span class="fu">&lt;&gt;</span> <span class="st">&quot;/admin/curators&quot;</span>) (encodeJson state<span class="fu">.</span>form)
  <span class="kw">let</span> <span class="dt">Tuple</span> typ msg <span class="fu">=</span> handleCreateResponse <span class="st">&quot;admin.curator&quot;</span> response
  return <span class="fu">$</span> flashMessage typ msg</code></pre></div>
<p>We’re able to move a lot of code out or generalize it away here because create’s are pretty simple. There’s another type we’re generating called <code>CreateResponse</code>. The <code>handleCreateResponse</code> function will take care of retrieving the status and a message. (the first argument string is a dumb little i18n translation “index”).</p>
<div class="sourceCode"><pre class="sourceCode haskell"><code class="sourceCode haskell"><span class="co">--  Success, Warning, Failure are for determining the message color..</span>
<span class="ot">handleCreateResponse ::</span> <span class="dt">TranslationIndex</span> <span class="ot">-&gt;</span> <span class="dt">Json</span> <span class="ot">-&gt;</span> <span class="dt">Tuple</span> <span class="dt">Message</span> <span class="dt">String</span>
handleCreateResponse idx res <span class="fu">=</span>
  <span class="kw">case</span> decodeJson res<span class="fu">.</span>response <span class="kw">of</span>
    <span class="dt">Left</span> e <span class="ot">-&gt;</span> <span class="dt">Tuple</span> <span class="dt">Failure</span> e
    <span class="dt">Right</span> cr <span class="ot">-&gt;</span> 
      <span class="kw">let</span> msg <span class="fu">=</span> Msg.t idx cr <span class="co">-- lookup the message based on the response type</span>
      <span class="kw">in</span>
        <span class="kw">case</span> cr <span class="kw">of</span>
          <span class="dt">CreateSuccess</span> _ <span class="ot">-&gt;</span> <span class="dt">Tuple</span> <span class="dt">Success</span> msg
          <span class="dt">NotUnique</span> <span class="ot">-&gt;</span> <span class="dt">Tuple</span> <span class="dt">Warning</span> msg
          <span class="dt">CreateFailure</span> t <span class="ot">-&gt;</span> <span class="dt">Tuple</span> <span class="dt">Failure</span> msg</code></pre></div>
<p>Here’s what it looks like on the haskell side:</p>
<div class="sourceCode"><pre class="sourceCode haskell"><code class="sourceCode haskell"><span class="kw">data</span> <span class="dt">CreateResponse</span>
  <span class="fu">=</span> <span class="dt">CreateSuccess</span> <span class="dt">Int64</span>
  <span class="fu">|</span> <span class="dt">CreateFailure</span> <span class="dt">Text</span>
  <span class="fu">|</span> <span class="dt">NotUnique</span>
  <span class="kw">deriving</span> (<span class="dt">Generic</span>, <span class="dt">Typeable</span>, <span class="dt">Show</span>)</code></pre></div>
<p>This can change based on the backend needs and you’ll be forced to handle those cases in the frontend.</p>
<h2 id="your-haskell-api">Your Haskell API</h2>
<p>The codegen will have to fit somewhere in your build-chain; I put mine in the application settings fetch</p>
<div class="sourceCode"><pre class="sourceCode haskell"><code class="sourceCode haskell"><span class="ot">getAppSettings ::</span> <span class="dt">IO</span> <span class="dt">AppSettings</span>
getAppSettings <span class="fu">=</span> <span class="kw">do</span>
  CodeGen.main 
  loadEnv
  loadYamlSettings [configSettingsYml] [] useEnv</code></pre></div>
<p>This will:</p>
<ul>
<li>generate the code in “frontend/src” (Will show where this is specified later)</li>
<li>populate ENV from a <code>.env</code> file</li>
<li>read the app settings from a yaml and return it</li>
</ul>
<p><em>brent rambo thumbs up</em></p>
<h2 id="gen">Gen</h2>
<p>The process of defining “bridges” from haskell to purescript is relatively straightforward. One “gotcha” is in that “.purs” files are generated in the same module name as where they’re <em>defined</em> in your haskell. Perhaps that’s what you expected, but I’d have preferred they get generated into the same file. I’m using a forked version to provide newtype unwrapping and lens for each record field. (PR <a href="https://github.com/eskimor/purescript-bridge/pull/31">here</a>)</p>
<p>This next bit could all be found in the <a href="https://github.com/gonimo/gonimo-back/blob/master/app/PSGenerator.hs">example</a> or readme of <a href="https://www.stackage.org/nightly-2017-10-07/package/purescript-bridge-0.11.0.0">purescript-bridge</a>, but I’ll briefly explain the context for each of these code blocks.</p>
<p>In your CodeGen module you’ll need to specify which types are going to be generated in purescript.</p>
<div class="sourceCode"><pre class="sourceCode haskell"><code class="sourceCode haskell"><span class="co">-- Your list of types to provide</span>
<span class="ot">myTypes ::</span> [<span class="dt">SumType</span> <span class="ch">&#39;Haskell]</span>
myTypes <span class="fu">=</span> [
    mkSumType (<span class="dt">Proxy</span><span class="ot"> ::</span> <span class="dt">Proxy</span> <span class="dt">CuratorForm</span>)
  , mkSumType (<span class="dt">Proxy</span><span class="ot"> ::</span> <span class="dt">Proxy</span> <span class="dt">EventForm</span>)
  , mkSumType (<span class="dt">Proxy</span><span class="ot"> ::</span> <span class="dt">Proxy</span> <span class="dt">CreateResponse</span>)
  <span class="co">-- ...</span>
  ]</code></pre></div>
<p>There will be types you’ll need to be specific about; one’s without direct purescript primitives. For example, the <code>Int64</code> of a primary id database column will need to fall to an <code>Int</code> type in purescript:</p>
<div class="sourceCode"><pre class="sourceCode haskell"><code class="sourceCode haskell"><span class="kw">import </span><span class="dt">Language.PureScript.Bridge.PSTypes</span> (psInt)

<span class="co">-- delegate to a primitive</span>
<span class="ot">int64Bridge ::</span> <span class="dt">BridgePart</span>
int64Bridge <span class="fu">=</span> typeName <span class="fu">^==</span> <span class="st">&quot;Int64&quot;</span> <span class="fu">&gt;&gt;</span> return psInt</code></pre></div>
<p>This is saying: “Purescript already knows how to handle this but it’s called something else”</p>
<p>The other case might involve delegating a type you’ve defined in purescript. This is not great because you can break your dependent code if you change these. This isn’t <em>bad</em> based on how most of the world does frontend development, it’s actually exactly how you’d make promises with a javascript app to decode consistently. I think we can do better though.</p>
<div class="sourceCode"><pre class="sourceCode haskell"><code class="sourceCode haskell"><span class="ot">psDateTime ::</span> <span class="dt">TypeInfo</span> <span class="ch">&#39;PureScript</span>
psDateTime <span class="fu">=</span> <span class="dt">TypeInfo</span> {
    _typePackage <span class="fu">=</span> <span class="st">&quot;&quot;</span>
  , _typeModule <span class="fu">=</span> <span class="st">&quot;Types&quot;</span>
  , _typeName <span class="fu">=</span> <span class="st">&quot;DateStamp&quot;</span>
  , _typeParameters <span class="fu">=</span> []
  }

<span class="ot">utcTimeBridge ::</span> <span class="dt">BridgePart</span>
utcTimeBridge <span class="fu">=</span> typeName <span class="fu">^==</span> <span class="st">&quot;UTCTime&quot;</span> <span class="fu">&gt;&gt;</span> return psDateTime</code></pre></div>
<p>The above example is saying: you’ll find a type <em>named</em> <code>DateStamp</code> in the purescript <em>module</em> <code>Types</code> and it doesn’t require an external <em>package</em>. Use this when generating fields with type <code>UTCTime</code>.</p>
<p>This is about it for the haskell side and you’ll write out the types to a file like so:</p>
<div class="sourceCode"><pre class="sourceCode haskell"><code class="sourceCode haskell"><span class="co">-- defaultBridge, buildBridge, etc are provided by </span>
<span class="co">-- Language.PureScript.Bridge</span>

<span class="ot">main ::</span> <span class="dt">IO</span> ()
main <span class="fu">=</span> writePSTypes <span class="st">&quot;frontend/src/&quot;</span> (buildBridge mainBridge) myTypes
  <span class="kw">where</span>
    mainBridge <span class="fu">=</span> defaultBridge <span class="fu">&lt;|&gt;</span> int64Bridge <span class="fu">&lt;|&gt;</span> utcTimeBridge</code></pre></div>
<h2 id="gen-crafted-types-for-your-enjoyment">Gen-Crafted types for your enjoyment</h2>
<p>Below are some examples of the output!</p>
<div class="sourceCode"><pre class="sourceCode haskell"><code class="sourceCode haskell"><span class="co">-- src/App/Form.purs</span>
derive <span class="kw">instance</span><span class="ot"> genericCuratorForm ::</span> <span class="dt">Generic</span> <span class="dt">CuratorForm</span>
derive <span class="kw">instance</span><span class="ot"> newtypeCuratorForm ::</span> <span class="dt">Newtype</span> <span class="dt">CuratorForm</span> _

_email <span class="fu">=</span> _Newtype <span class="fu">&lt;&lt;&lt;</span> prop (<span class="dt">SProxy</span><span class="ot"> ::</span> <span class="dt">SProxy</span> <span class="st">&quot;email&quot;</span>)
_message <span class="fu">=</span> _Newtype <span class="fu">&lt;&lt;&lt;</span> prop (<span class="dt">SProxy</span><span class="ot"> ::</span> <span class="dt">SProxy</span> <span class="st">&quot;message&quot;</span>)

<span class="co">-- src/App/Crud.purs</span>
<span class="kw">data</span> <span class="dt">CreateResponse</span> <span class="fu">=</span>
    <span class="dt">CreateSuccess</span> <span class="dt">Int</span>
  <span class="fu">|</span> <span class="dt">CreateFailure</span> <span class="dt">String</span>
  <span class="fu">|</span> <span class="dt">FailedUniquenessConstraint</span> 
derive <span class="kw">instance</span><span class="ot"> genericCreateResponse ::</span> <span class="dt">Generic</span> <span class="dt">CreateResponse</span>

<span class="ot">_CreateSuccess ::</span> <span class="dt">Prism&#39;</span> <span class="dt">CreateResponse</span> <span class="dt">Int</span>
_CreateSuccess <span class="fu">=</span> prism&#39; <span class="dt">CreateSuccess</span> f
  <span class="kw">where</span>
    f (<span class="dt">CreateSuccess</span> a) <span class="fu">=</span> <span class="dt">Just</span> <span class="fu">$</span> a
    f _ <span class="fu">=</span> <span class="dt">Nothing</span>

<span class="ot">_CreateFailure ::</span> <span class="dt">Prism&#39;</span> <span class="dt">CreateResponse</span> <span class="dt">String</span>
_CreateFailure <span class="fu">=</span> prism&#39; <span class="dt">CreateFailure</span> f
  <span class="kw">where</span>
    f (<span class="dt">CreateFailure</span> a) <span class="fu">=</span> <span class="dt">Just</span> <span class="fu">$</span> a
    f _ <span class="fu">=</span> <span class="dt">Nothing</span>

<span class="ot">_FailedUniquenessConstraint ::</span> <span class="dt">Prism&#39;</span> <span class="dt">CreateResponse</span> <span class="dt">Unit</span>
_FailedUniquenessConstraint <span class="fu">=</span> prism&#39; (\_ <span class="ot">-&gt;</span> <span class="dt">FailedUniquenessConstraint</span>) f
  <span class="kw">where</span>
    f <span class="dt">FailedUniquenessConstraint</span> <span class="fu">=</span> <span class="dt">Just</span> unit
    f _ <span class="fu">=</span> <span class="dt">Nothing</span></code></pre></div>
<p>I’ve pasted the entirety of both files I’m using to <a href="https://gist.github.com/tippenein/2e15b695bac673a5acd7a167c2ba4808">this gist</a> and note the naming is slightly different because in <em>real</em> use you’ll have to deal with the travesty of haskell record namespaces.</p>
<h2 id="next-steps">Next Steps</h2>
<p>This is fine and dandy, but it could be much better. Purescript has the tools to <a href="https://pursuit.purescript.org/packages/purescript-sparkle/4.1.0">generate forms from data types</a> and ideally that’s the direction I’d like to move this work.</p>

  <div class="pager">
    <ul class="list-unstyled list-inline">
      
        <li class="previous left">
          <a class="button" href="/posts/2017-10-07-a-writer-purescript-form.html" data-toggle="tooltip" data-placement="top" title="Previous Post">&larr; Previous Post</a>
        </li>
      

      
        <li class="next right">
          <a class="button" href="" data-toggle="tooltip" data-placement="top" title="Next Post">Next Post &rarr;</a>
        </li>
      
    </ul>
  </div>
  <br>
  <br>
  <div id="disqus_thread"></div>
  <script>

  /**
   *  RECOMMENDED CONFIGURATION VARIABLES: EDIT AND UNCOMMENT THE SECTION BELOW TO INSERT DYNAMIC VALUES FROM YOUR PLATFORM OR CMS.
   *  LEARN WHY DEFINING THESE VARIABLES IS IMPORTANT: https://disqus.com/admin/universalcode/#configuration-variables */
  /*
  */
  /* var disqus_config = function () {
      this.page.url = "brdyorn.com/posts/2017-10-07-the-codegen-hammer.html";  // Replace PAGE_URL with your page's canonical URL variable
      this.page.identifier = "posts/2017-10-07-the-codegen-hammer.md"; // Replace PAGE_IDENTIFIER with your page's unique identifier variable
      this.page.title = 'The Codegen Hammer';
  }; */
  (function() { // DON'T EDIT BELOW THIS LINE
      var d = document, s = d.createElement('script');
      s.src = '//brdyorn.disqus.com/embed.js';
      s.setAttribute('data-timestamp', +new Date());
      (d.head || d.body).appendChild(s);
  })();
  </script>
  <noscript>Please enable JavaScript to view the <a href="https://disqus.com/?ref_noscript">comments powered by Disqus.</a></noscript>
</div>

]]></description>
    <pubDate>Sat, 07 Oct 2017 00:00:00 UT</pubDate>
    <guid>http://brdyorn.com/posts/2017-10-07-the-codegen-hammer.html</guid>
    <dc:creator>Brady Ouren</dc:creator>
</item>
<item>
    <title>A Purescript Form</title>
    <link>http://brdyorn.com/posts/2017-10-07-a-writer-purescript-form.html</link>
    <description><![CDATA[<div class="info">
  <!-- Posted on Oct  7, 2017 -->
  
</div>

<h1 class="section-block blog">A Purescript Form</h1>
<div class="post-body">
  <p>What follows is a further look at a portion of <a href="http://www.parsonsmatt.org/2016/01/03/ann_quicklift.html">this post</a> by <span class="citation">@parsonsmatt</span>. WForm, as explained there, is a nice abstraction which is inspired partly by Yesod forms. I found it useful and dropped the implementation in a <a href="https://github.com/tippenein/wform">repo</a> to work on when I have time (please help).</p>
<p>Right now it’s specific to Halogen and bootstrap css, but I don’t see any reason it needs to be. In essence it comes down to 2 type aliases and 1 data type. Along with some helper methods for creating fields, you can get a long way with these basics.</p>
<p>There are also further details around the following example in a related <a href="/posts/2017-10-07-the-codegen-hammer.html">post about codegen</a></p>
<div class="sourceCode"><pre class="sourceCode haskell"><code class="sourceCode haskell"><span class="kw">type</span> <span class="dt">WForm</span> v f a <span class="fu">=</span>
  <span class="dt">ReaderT</span>
    (<span class="dt">Tuple</span> a (<span class="dt">FormAction</span> f a))
    (<span class="dt">Writer</span> (<span class="dt">Array</span> (<span class="dt">HTML</span> v (f <span class="dt">Unit</span>))))
    a

<span class="kw">type</span> <span class="dt">FormAction</span> f a <span class="fu">=</span> <span class="dt">FormInput</span> a <span class="ot">-&gt;</span> <span class="dt">Unit</span> <span class="ot">-&gt;</span> f <span class="dt">Unit</span>
<span class="kw">data</span> <span class="dt">FormInput</span> a
  <span class="fu">=</span> <span class="dt">Submit</span>
  <span class="fu">|</span> <span class="dt">Edit</span> (a <span class="ot">-&gt;</span> a)</code></pre></div>
<p>This provides a nice, general interface for forms!</p>
<p>Using this abstraction, we can define an <code>Input</code> for a component</p>
<div class="sourceCode"><pre class="sourceCode haskell"><code class="sourceCode haskell"><span class="kw">data</span> <span class="dt">Input</span> a
  <span class="fu">=</span> <span class="dt">NewCurator</span> (<span class="dt">Form.FormInput</span> <span class="dt">CuratorForm</span>) a</code></pre></div>
<p>One thing I like about this is the ease of edit actions using the lens’ provided by codegen and the FormInput’s <code>Edit</code> constructor</p>
<p>For example, you might handle a form edit in your eval loop similar to this:</p>
<div class="sourceCode"><pre class="sourceCode haskell"><code class="sourceCode haskell">eval (<span class="dt">NewCurator</span> ev next) <span class="fu">=</span> handleNewCurator ev <span class="fu">$&gt;</span> next
  <span class="kw">where</span>
    handleNewCurator (<span class="dt">Form.Edit</span> f) <span class="fu">=</span> <span class="kw">do</span>
      H.modify (_form <span class="fu">%~</span> f)
    <span class="co">-- ...</span></code></pre></div>
<p>We can apply the edit action directly on the form via our lens’. The errors are handled internally to the WForm writer monad.</p>
<div class="sourceCode"><pre class="sourceCode haskell"><code class="sourceCode haskell"><span class="co">-- we need access to the form from the top level</span>
<span class="co">-- the form itself already has lens&#39; defined (src/App/Form.purs)</span>
<span class="ot">_form ::</span> <span class="dt">Lens&#39;</span> <span class="dt">State</span> <span class="dt">CuratorForm</span>
_form <span class="fu">=</span> lens _<span class="fu">.</span>form _ { form <span class="fu">=</span> _}

<span class="ot">initialState ::</span> <span class="dt">State</span>
initialState <span class="fu">=</span> 
  { form<span class="fu">:</span> <span class="dt">CuratorForm</span> { invitee<span class="fu">:</span> <span class="st">&quot;&quot;</span>, message<span class="fu">:</span> <span class="dt">Nothing</span> } }</code></pre></div>
<p>Between WForm and our generated lens’ we can compose a form quite cleanly:</p>
<div class="sourceCode"><pre class="sourceCode haskell"><code class="sourceCode haskell"><span class="co">-- example of a generated field accessor for out form</span>
_message <span class="fu">=</span> _Newtype <span class="fu">&lt;&lt;&lt;</span> prop (<span class="dt">SProxy</span><span class="ot"> ::</span> <span class="dt">SProxy</span> <span class="st">&quot;message&quot;</span>)

<span class="ot">render ::</span> <span class="dt">State</span> <span class="ot">-&gt;</span> <span class="dt">H.ComponentHTML</span> <span class="dt">Input</span>
render state <span class="fu">=</span>
  div_ <span class="fu">$</span> Form.renderForm state<span class="fu">.</span>form <span class="dt">NewCurator</span> <span class="kw">do</span>
    void <span class="fu">$</span> Form.textField <span class="st">&quot;email&quot;</span> <span class="st">&quot;Email&quot;</span> _invitee (Form.nonBlank <span class="fu">&lt;=&lt;</span> Form.emailValidator)
    Form.textFieldOpt <span class="st">&quot;message&quot;</span> <span class="st">&quot;A Note&quot;</span> _message  Form.optional
    <span class="co">--                name,      label,  lens,     validations</span></code></pre></div>
<p>Some context (and all the flaws) of this example can be found <a href="https://github.com/tippenein/dusk/blob/master/frontend/src/Component/Admin/Curator.purs">here</a></p>
<p>If you think this could be useful and could provide documentation, examples, or code go <a href="https://github.com/tippenein/wform">to github</a></p>

  <div class="pager">
    <ul class="list-unstyled list-inline">
      
        <li class="previous left">
          <a class="button" href="/posts/2017-01-05-reflex-template-haskeleton.html" data-toggle="tooltip" data-placement="top" title="Previous Post">&larr; Previous Post</a>
        </li>
      

      
        <li class="next right">
          <a class="button" href="/posts/2017-10-07-the-codegen-hammer.html" data-toggle="tooltip" data-placement="top" title="Next Post">Next Post &rarr;</a>
        </li>
      
    </ul>
  </div>
  <br>
  <br>
  <div id="disqus_thread"></div>
  <script>

  /**
   *  RECOMMENDED CONFIGURATION VARIABLES: EDIT AND UNCOMMENT THE SECTION BELOW TO INSERT DYNAMIC VALUES FROM YOUR PLATFORM OR CMS.
   *  LEARN WHY DEFINING THESE VARIABLES IS IMPORTANT: https://disqus.com/admin/universalcode/#configuration-variables */
  /*
  */
  /* var disqus_config = function () {
      this.page.url = "brdyorn.com/posts/2017-10-07-a-writer-purescript-form.html";  // Replace PAGE_URL with your page's canonical URL variable
      this.page.identifier = "posts/2017-10-07-a-writer-purescript-form.md"; // Replace PAGE_IDENTIFIER with your page's unique identifier variable
      this.page.title = 'A Purescript Form';
  }; */
  (function() { // DON'T EDIT BELOW THIS LINE
      var d = document, s = d.createElement('script');
      s.src = '//brdyorn.disqus.com/embed.js';
      s.setAttribute('data-timestamp', +new Date());
      (d.head || d.body).appendChild(s);
  })();
  </script>
  <noscript>Please enable JavaScript to view the <a href="https://disqus.com/?ref_noscript">comments powered by Disqus.</a></noscript>
</div>

]]></description>
    <pubDate>Sat, 07 Oct 2017 00:00:00 UT</pubDate>
    <guid>http://brdyorn.com/posts/2017-10-07-a-writer-purescript-form.html</guid>
    <dc:creator>Brady Ouren</dc:creator>
</item>
<item>
    <title>Reflex Template</title>
    <link>http://brdyorn.com/posts/2017-01-05-reflex-template-haskeleton.html</link>
    <description><![CDATA[<div class="info">
  <!-- Posted on Jan  5, 2017 -->
  
</div>

<h1 class="section-block blog">Reflex Template</h1>
<div class="post-body">
  <h2 id="project-bootstrapping">Project Bootstrapping!</h2>
<p>I’m announcing a Reflex FRP bootstrapping template!</p>
<p>You can use it now if you have <a href="https://github.com/fujimura/hi">hi</a> installed.</p>
<pre class="shell"><code>hi some_project --repository git://github.com/tippenein/haskeleton-reflex.git
cd some_project
make</code></pre>
<h2 id="what-it-gives-you">What it gives you</h2>
<ul>
<li>stack for dependencies</li>
<li>small base of common widgets and helpers (which I’ll continue to add to)</li>
<li>a baseline Model/View/Update logic.</li>
</ul>
<p>The intention is to be able to start right in by adding your <code>Action</code>’s and <code>Model</code> attributes and have them already plugged into the simple reflex event fold.</p>
<h2 id="other-options">Other options</h2>
<p>The <a href="https://github.com/reflex-frp/reflex-platform">reflex-platform</a> is the official way supported by reflex for development, so this project is for people who want a reference on a working Stack config or people who are simply too stubborn to move to nix.</p>

  <div class="pager">
    <ul class="list-unstyled list-inline">
      
        <li class="previous left">
          <a class="button" href="/posts/2016-12-17-Norvigs-spell-correct-in-Haskell.html" data-toggle="tooltip" data-placement="top" title="Previous Post">&larr; Previous Post</a>
        </li>
      

      
        <li class="next right">
          <a class="button" href="/posts/2017-10-07-a-writer-purescript-form.html" data-toggle="tooltip" data-placement="top" title="Next Post">Next Post &rarr;</a>
        </li>
      
    </ul>
  </div>
  <br>
  <br>
  <div id="disqus_thread"></div>
  <script>

  /**
   *  RECOMMENDED CONFIGURATION VARIABLES: EDIT AND UNCOMMENT THE SECTION BELOW TO INSERT DYNAMIC VALUES FROM YOUR PLATFORM OR CMS.
   *  LEARN WHY DEFINING THESE VARIABLES IS IMPORTANT: https://disqus.com/admin/universalcode/#configuration-variables */
  /*
  */
  /* var disqus_config = function () {
      this.page.url = "brdyorn.com/posts/2017-01-05-reflex-template-haskeleton.html";  // Replace PAGE_URL with your page's canonical URL variable
      this.page.identifier = "posts/2017-01-05-reflex-template-haskeleton.md"; // Replace PAGE_IDENTIFIER with your page's unique identifier variable
      this.page.title = 'Reflex Template';
  }; */
  (function() { // DON'T EDIT BELOW THIS LINE
      var d = document, s = d.createElement('script');
      s.src = '//brdyorn.disqus.com/embed.js';
      s.setAttribute('data-timestamp', +new Date());
      (d.head || d.body).appendChild(s);
  })();
  </script>
  <noscript>Please enable JavaScript to view the <a href="https://disqus.com/?ref_noscript">comments powered by Disqus.</a></noscript>
</div>

]]></description>
    <pubDate>Thu, 05 Jan 2017 00:00:00 UT</pubDate>
    <guid>http://brdyorn.com/posts/2017-01-05-reflex-template-haskeleton.html</guid>
    <dc:creator>Brady Ouren</dc:creator>
</item>
<item>
    <title>Norvigs spell correct in Haskell</title>
    <link>http://brdyorn.com/posts/2016-12-17-Norvigs-spell-correct-in-Haskell.html</link>
    <description><![CDATA[<div class="info">
  <!-- Posted on Dec 17, 2016 -->
  
</div>

<h1 class="section-block blog">Norvigs spell correct in Haskell</h1>
<div class="post-body">
  <p>Peter Norvig has an <a href="http://norvig.com/spell-correct.html">old post</a> about writing a spell checker which I’ve always loved the succinctness of. I was on a plane for a few hours and wanted to see how this translated from python to haskell. This is the tale of the journey which I did not intend to take.</p>
<h2 id="keeping-the-same-structure">Keeping the same structure</h2>
<p>First step was going through and recreating the main functionality which is mainly lists and sets, so, no big deal.</p>
<h2 id="splitting">Splitting</h2>
<p>We split the raw text into words</p>
<div class="sourceCode"><pre class="sourceCode haskell"><code class="sourceCode haskell">words<span class="ot"> ::</span> <span class="dt">Text</span> <span class="ot">-&gt;</span> [<span class="dt">Text</span>]
words <span class="fu">=</span> T.split (not <span class="fu">.</span> <span class="dt">Char</span><span class="fu">.</span>isAsciiLower) <span class="fu">.</span> T.toLower</code></pre></div>
<p>This code is the intuitive answer to the problem above, however it’s very slow. We’ll look at performance later in this post.</p>
<h2 id="counter-bag">Counter / Bag</h2>
<p>In python, the <code>Counter</code> is implemented as a multiset / “bag”. We’ll create our own with a Map from <code>Text</code> (word) to <code>Int</code> (count)</p>
<div class="sourceCode"><pre class="sourceCode haskell"><code class="sourceCode haskell"><span class="kw">type</span> <span class="dt">Counter</span> <span class="fu">=</span> <span class="dt">Map</span> <span class="dt">Text</span> <span class="dt">Int</span>

<span class="ot">toCounter ::</span> [<span class="dt">Text</span>] <span class="ot">-&gt;</span> <span class="dt">Hist</span>
toCounter <span class="fu">=</span> Map.fromListWith (<span class="fu">+</span>) <span class="fu">.</span> fmap (,<span class="dv">1</span>)

words <span class="ot">&lt;-</span> toCounter <span class="fu">.</span> words <span class="fu">&lt;$&gt;</span> readFile <span class="st">&quot;big.txt&quot;</span></code></pre></div>
<p>There is also a package called <code>multiset</code> but I didn’t know this because the wifi on the plane didn’t work.</p>
<h2 id="probability-and-correction">Probability and Correction</h2>
<p>In order to guess the right way of correcting we need to have probabilities based on the corpus’ word counts.</p>
<div class="sourceCode"><pre class="sourceCode haskell"><code class="sourceCode haskell"><span class="ot">prob ::</span> <span class="dt">Counter</span> <span class="ot">-&gt;</span> <span class="dt">Text</span> <span class="ot">-&gt;</span> <span class="dt">Int</span>
prob counter word <span class="fu">=</span> occurences <span class="ot">`div`</span> totalWords
  <span class="kw">where</span>
    occurences <span class="fu">=</span> fromMaybe <span class="dv">0</span> <span class="fu">$</span> Map.lookup t counter
    totalWords <span class="fu">=</span> Map.size ms

<span class="ot">correction ::</span> <span class="dt">Counter</span> <span class="ot">-&gt;</span> <span class="dt">Text</span> <span class="ot">-&gt;</span> <span class="dt">Text</span>
correction counter word <span class="fu">=</span> maximumBy (\a b <span class="ot">-&gt;</span> p a <span class="ot">`compare`</span> p b) <span class="fu">$</span> candidates counter word
  <span class="kw">where</span> p <span class="fu">=</span> prob counter</code></pre></div>
<div class="sourceCode"><pre class="sourceCode haskell"><code class="sourceCode haskell"><span class="ot">candidates ::</span> <span class="dt">Counter</span> <span class="ot">-&gt;</span> <span class="dt">Text</span> <span class="ot">-&gt;</span> <span class="dt">Set</span> <span class="dt">Text</span>
candidates counter word <span class="fu">=</span> detect
  [ known counter <span class="fu">$</span> Set.singleton t
  , known counter (edits1 word)
  , known counter (edits2 word)
  , Set.fromList [t]
  ]

<span class="ot">detect ::</span> [<span class="dt">Set</span> <span class="dt">Text</span>] <span class="ot">-&gt;</span> <span class="dt">Set</span> <span class="dt">Text</span>
detect <span class="fu">=</span> fromMaybe Set.empty <span class="fu">.</span> head <span class="fu">.</span> filter (not <span class="fu">.</span> Set.null)

<span class="ot">known ::</span> <span class="dt">Counter</span> <span class="ot">-&gt;</span> <span class="dt">Set</span> <span class="dt">Text</span> <span class="ot">-&gt;</span> <span class="dt">Set</span> <span class="dt">Text</span>
known counter <span class="fu">=</span> Set.filter (\w <span class="ot">-&gt;</span> Map.member w counter)</code></pre></div>
<h2 id="edits-permutations">Edits / Permutations</h2>
<p>I initially squished all the logic into single list-comprehensions, but you’ll see I’ve split the heavier functions out.</p>
<div class="sourceCode"><pre class="sourceCode haskell"><code class="sourceCode haskell"><span class="ot">edits1 ::</span> <span class="dt">Text</span> <span class="ot">-&gt;</span> [<span class="dt">Text</span>]
edits1 w <span class="fu">=</span> nub&#39; <span class="fu">$</span> mconcat [transposes&#39;, deletes&#39;, replaces&#39;, inserts]
  <span class="kw">where</span>
    alphabet    <span class="fu">=</span> fmap T.singleton [<span class="ch">&#39;a&#39;</span><span class="fu">..</span><span class="ch">&#39;z&#39;</span>]
    splits      <span class="fu">=</span> zip (T.inits w) (T.tails w)
    deletes&#39;    <span class="fu">=</span> deletes splits
    transposes&#39; <span class="fu">=</span> transposes splits
    replaces&#39;   <span class="fu">=</span> replaces splits
    inserts     <span class="fu">=</span> [l <span class="fu">&lt;&gt;</span> c <span class="fu">&lt;&gt;</span> r <span class="fu">|</span> (l,r) <span class="ot">&lt;-</span> splits, c <span class="ot">&lt;-</span> alphabet]</code></pre></div>
<p>The <code>splits</code> gets its own type for cleanliness:</p>
<div class="sourceCode"><pre class="sourceCode haskell"><code class="sourceCode haskell"><span class="kw">type</span> <span class="dt">Splits</span> <span class="fu">=</span> [(<span class="dt">Text</span>, <span class="dt">Text</span>)]</code></pre></div>
<p>Instead of <code>if R</code> or <code>if len(R)&lt;1</code> and such like we have in python, I used a <code>guard</code> to skip over splits with contents fitting a certain criteria (e.g (l,r) where r is not empty)</p>
<div class="sourceCode"><pre class="sourceCode haskell"><code class="sourceCode haskell"><span class="ot">unSplit ::</span> (<span class="dt">Monad</span> f, <span class="dt">Alternative</span> f) <span class="ot">=&gt;</span> (<span class="dt">Text</span>, <span class="dt">Text</span>) <span class="ot">-&gt;</span> f (<span class="dt">Text</span>,<span class="dt">Text</span>)
unSplit <span class="fu">=</span> unSplitWith (<span class="fu">/=</span> <span class="st">&quot;&quot;</span>)

<span class="ot">unSplitWith ::</span> (<span class="dt">Monad</span> f, <span class="dt">Alternative</span> f) <span class="ot">=&gt;</span> (<span class="dt">Text</span> <span class="ot">-&gt;</span> <span class="dt">Bool</span>) <span class="ot">-&gt;</span> (<span class="dt">Text</span>, <span class="dt">Text</span>) <span class="ot">-&gt;</span> f (<span class="dt">Text</span>,<span class="dt">Text</span>)
unSplitWith f (l, r) <span class="fu">=</span> guard (f r) <span class="fu">&gt;&gt;</span> pure (l, r)

<span class="co">-- | swap the 1st and 2nd letters across our list of splits (&quot;derp&quot; -&gt; &quot;edrp&quot;)</span>
<span class="ot">transposes ::</span> <span class="dt">Splits</span> <span class="ot">-&gt;</span> [<span class="dt">Text</span>]
transposes splits <span class="fu">=</span>
  [l <span class="fu">&lt;&gt;</span> swap&#39; r <span class="fu">|</span> x <span class="ot">&lt;-</span> splits, (l,r) <span class="ot">&lt;-</span> unSplitWith (\a <span class="ot">-&gt;</span> T.length a <span class="fu">&gt;</span> <span class="dv">1</span>) x]
  <span class="kw">where</span>
    swap&#39; w <span class="fu">=</span> T.intercalate <span class="st">&quot;&quot;</span> [two, one&#39;, rest]
      <span class="kw">where</span>
        two  <span class="fu">=</span> T.take <span class="dv">1</span> <span class="fu">$</span> T.drop <span class="dv">1</span> w
        one&#39;  <span class="fu">=</span> T.take <span class="dv">1</span> w
        rest <span class="fu">=</span> T.tail <span class="fu">$</span> T.tail w

<span class="co">-- | remove a letter across all splits &quot;derp&quot; -&gt; [&quot;drp&quot;,&quot;dep&quot;,&quot;der&quot;]</span>
<span class="ot">deletes ::</span> <span class="dt">Splits</span> <span class="ot">-&gt;</span> [<span class="dt">Text</span>]
deletes splits <span class="fu">=</span>
  [l <span class="fu">&lt;&gt;</span> T.tail r <span class="fu">|</span> x <span class="ot">&lt;-</span> splits, (l,r) <span class="ot">&lt;-</span> unSplit x]

<span class="co">-- | try replacing a letter with one from the alphabet in each spot. This one is very large</span>
<span class="ot">replaces ::</span> <span class="dt">Splits</span> <span class="ot">-&gt;</span> [<span class="dt">Text</span>]
replaces splits <span class="fu">=</span> [l <span class="fu">&lt;&gt;</span> c <span class="fu">&lt;&gt;</span> T.tail r <span class="fu">|</span> x <span class="ot">&lt;-</span> splits, (l,r) <span class="ot">&lt;-</span> unSplit x, c <span class="ot">&lt;-</span> alphabet]</code></pre></div>
<p>I think this comes out reasonably concise.</p>
<div class="sourceCode"><pre class="sourceCode haskell"><code class="sourceCode haskell"><span class="ot">edits2 ::</span> <span class="dt">Text</span> <span class="ot">-&gt;</span> [<span class="dt">Text</span>]
edits2 w <span class="fu">=</span> nub&#39; [ e2 <span class="fu">|</span> e1 <span class="ot">&lt;-</span> edits1 w, e2 <span class="ot">&lt;-</span> edits1 e1 ]

<span class="co">-- Prelude&#39;s nub is prrrrrretty bad, so we use this instead.</span>
<span class="ot">nub&#39; ::</span> [<span class="dt">Text</span>] <span class="ot">-&gt;</span> [<span class="dt">Text</span>]
nub&#39; <span class="fu">=</span> Set.toList <span class="fu">.</span> Set.fromList</code></pre></div>
<h2 id="performance">Performance</h2>
<p>The performance of the implementation I came to is… really bad. The time taken to guess even short words was ~4 seconds. This was unacceptable considering the python version is nearly instant.</p>
<p>After asking around on irc and slack, two main problems were pointed out.</p>
<ul>
<li>The <code>words</code> function was extremely inefficient (thanks to <span class="citation">@mwutton</span> for pointing this out)</li>
<li>The Map and Set in <code>containers</code> package are not optimized for this sort of bagging. (thanks to <span class="citation">@yaron</span>)</li>
</ul>
<p>In order to speed up the <code>words</code> implementation, we just shove the logic into <code>Data.Text</code>’s implementation (which is <a href="https://hackage.haskell.org/package/text-1.2.2.1/docs/src/Data-Text.html#words">nasty</a>). This buys us ~1 second off the ridiculous 4 seconds.. So, I went further.</p>
<p>Since I wasn’t using any order-specific functions on Sets or Maps I just replaced the <code>containers</code> dependency with <code>unordered-containers</code> and changed the import statements to use them. Bam! This nearly halved the time! But it’s still real bad at 1 second.</p>
<p>I used the <code>profiteur</code> tool to visualize the performance issues a bit while going through this process, which just basically confirmed that Set/Map operations and <code>words</code> were awful, like we already knew. <img src="http://i.imgur.com/BkHfS6m.png" alt="profiling" /></p>
<p>It seems as though python’s <code>Counter</code> shouldn’t be all that different than ours (an unordered hash set) but the haskell version lags behind. I kept the code as intuitive as I knew how and it wasn’t quite enough for this type of problem.</p>
<h2 id="lessons">Lessons</h2>
<ol style="list-style-type: decimal">
<li>Always use <code>unordered-containers</code> unless you for some reason need to keep the ordering of your data structures.</li>
<li>Sometimes pre-processing is worth the effort. You can try as hard as you want to optimize the function, but at some point you have to call it a loss.</li>
</ol>
<p>I’d welcome any comments about how this could be improved further. The result was not encouraging but despite this, I did learn some things along the way.</p>
<p>The full code is <a href="https://github.com/tippenein/spelling-hs">here</a></p>
<p>A literate haskell file to follow along is <a href="https://github.com/tippenein/spelling-hs/blob/master/spelling.lhs">here</a></p>

  <div class="pager">
    <ul class="list-unstyled list-inline">
      
        <li class="previous left">
          <a class="button" href="/posts/2016-08-06-upgrading-servant-client-from-zero-four.html" data-toggle="tooltip" data-placement="top" title="Previous Post">&larr; Previous Post</a>
        </li>
      

      
        <li class="next right">
          <a class="button" href="/posts/2017-01-05-reflex-template-haskeleton.html" data-toggle="tooltip" data-placement="top" title="Next Post">Next Post &rarr;</a>
        </li>
      
    </ul>
  </div>
  <br>
  <br>
  <div id="disqus_thread"></div>
  <script>

  /**
   *  RECOMMENDED CONFIGURATION VARIABLES: EDIT AND UNCOMMENT THE SECTION BELOW TO INSERT DYNAMIC VALUES FROM YOUR PLATFORM OR CMS.
   *  LEARN WHY DEFINING THESE VARIABLES IS IMPORTANT: https://disqus.com/admin/universalcode/#configuration-variables */
  /*
  */
  /* var disqus_config = function () {
      this.page.url = "brdyorn.com/posts/2016-12-17-Norvigs-spell-correct-in-Haskell.html";  // Replace PAGE_URL with your page's canonical URL variable
      this.page.identifier = "posts/2016-12-17-Norvigs-spell-correct-in-Haskell.md"; // Replace PAGE_IDENTIFIER with your page's unique identifier variable
      this.page.title = 'Norvigs spell correct in Haskell';
  }; */
  (function() { // DON'T EDIT BELOW THIS LINE
      var d = document, s = d.createElement('script');
      s.src = '//brdyorn.disqus.com/embed.js';
      s.setAttribute('data-timestamp', +new Date());
      (d.head || d.body).appendChild(s);
  })();
  </script>
  <noscript>Please enable JavaScript to view the <a href="https://disqus.com/?ref_noscript">comments powered by Disqus.</a></noscript>
</div>

]]></description>
    <pubDate>Sat, 17 Dec 2016 00:00:00 UT</pubDate>
    <guid>http://brdyorn.com/posts/2016-12-17-Norvigs-spell-correct-in-Haskell.html</guid>
    <dc:creator>Brady Ouren</dc:creator>
</item>
<item>
    <title>Upgrading Servant Clients</title>
    <link>http://brdyorn.com/posts/2016-08-06-upgrading-servant-client-from-zero-four.html</link>
    <description><![CDATA[<div class="info">
  <!-- Posted on Aug  6, 2016 -->
  
</div>

<h1 class="section-block blog">Upgrading Servant Clients</h1>
<div class="post-body">
  <p>A few things have changed with Servant’s client deriving between <code>0.4</code> and <code>0.7</code>. I’ll document here what I did to upgrade.</p>
<h3 id="follow-the-types">Follow the types</h3>
<p>First thing you’ll notice after building your project with the 0.7 version of servant client is some failing functions. Let’s follow the types and do what they tell us.</p>
<p>The first error is that BaseUrl takes an extra “path” argument. It’s just a string; ghc tells us this.</p>
<div class="sourceCode"><pre class="sourceCode haskell"><code class="sourceCode haskell">makeBaseUrl <span class="fu">=</span> <span class="kw">do</span>
  h <span class="ot">&lt;-</span> Config.domain <span class="fu">&lt;$&gt;</span> Config.remoteConfig
  p <span class="ot">&lt;-</span> Config.port <span class="fu">&lt;$&gt;</span> Config.remoteConfig
  <span class="co">-- BaseUrl has 1 extra argument</span>
  <span class="co">-- used to be: pure $ BaseUrl Http h p</span>
  pure <span class="fu">$</span> <span class="dt">BaseUrl</span> <span class="dt">Http</span> h p <span class="st">&quot;&quot;</span></code></pre></div>
<p>Now we use ExceptT instead of EitherT. It’s better, and ghc tells us that’s what it’s expecting.</p>
<div class="sourceCode"><pre class="sourceCode haskell"><code class="sourceCode haskell"><span class="kw">type</span> <span class="dt">Action</span> a <span class="fu">=</span> <span class="dt">ExceptT</span> <span class="dt">ServantError</span> <span class="dt">IO</span> a</code></pre></div>
<p>This type alias has existed as <code>ClientM</code> and <code>Handler</code> (see <a href="https://github.com/haskell-servant/servant/issues/467">this</a> and <a href="https://github.com/haskell-servant/servant/issues/434">this</a>) but I prefer to write this explicitly and forego all the changes that might happen in servant.</p>
<p>The next compiler error says something about an expected Manager argument to one of our bound client functions.</p>
<h3 id="http-manager">Http manager</h3>
<p>There is a new dependency on http-client. Luckily I had structured my code to use this generic <code>run</code> function, so I only had to make manager updates here.</p>
<div class="sourceCode"><pre class="sourceCode haskell"><code class="sourceCode haskell">run action <span class="fu">=</span> <span class="kw">do</span>
  baseUrl <span class="ot">&lt;-</span> makeBaseUrl
  manager <span class="ot">&lt;-</span> newManager defaultManagerSettings
  result <span class="ot">&lt;-</span> runExceptT <span class="fu">$</span> action manager baseUrl
  <span class="kw">case</span> result <span class="kw">of</span>
    <span class="dt">Left</span> message <span class="ot">-&gt;</span> error (show message)
    <span class="dt">Right</span> x <span class="ot">-&gt;</span> pure x</code></pre></div>
<p>Essentially we only needed to pass 2 new arguments to the action (the derived functions from <code>client</code>) and run them inside <code>runExceptT</code>.</p>
<p>The last compiler error you’ll get is an extra argument to <code>client</code> which is just a remnant you can delete. It was previously the BaseUrl argument, but we’ve already moved that to the <code>run</code> function.</p>
<div class="sourceCode"><pre class="sourceCode haskell"><code class="sourceCode haskell">listDocuments&#39; <span class="fu">:&lt;|&gt;</span> createDocument&#39; <span class="fu">=</span>
  <span class="co">-- we no longer pass the url into the `client` deriving function.</span>
  client documentAPI</code></pre></div>
<p>That’s pretty much it. I didn’t really have to look anything up. The compiler didn’t <em>directly</em> tell me how to fix it, but it <em>did</em> tell me which parts of my code had strange arguments, which were then easy to correct.</p>
<p>Matter of fact, the commit where I recently did this is <a href="https://github.com/tippenein/hasken/commit/c3cb78197f0b470f944789a3b0552a42fd369aca#diff-1d9ebc04df2ac4beb0ee8681f4f13c4cR23">here</a> if that’s your sort of thing.</p>

  <div class="pager">
    <ul class="list-unstyled list-inline">
      
        <li class="previous left">
          <a class="button" href="/posts/2016-08-04-typed-fullstack-with-elm-and-haskell.html" data-toggle="tooltip" data-placement="top" title="Previous Post">&larr; Previous Post</a>
        </li>
      

      
        <li class="next right">
          <a class="button" href="/posts/2016-12-17-Norvigs-spell-correct-in-Haskell.html" data-toggle="tooltip" data-placement="top" title="Next Post">Next Post &rarr;</a>
        </li>
      
    </ul>
  </div>
  <br>
  <br>
  <div id="disqus_thread"></div>
  <script>

  /**
   *  RECOMMENDED CONFIGURATION VARIABLES: EDIT AND UNCOMMENT THE SECTION BELOW TO INSERT DYNAMIC VALUES FROM YOUR PLATFORM OR CMS.
   *  LEARN WHY DEFINING THESE VARIABLES IS IMPORTANT: https://disqus.com/admin/universalcode/#configuration-variables */
  /*
  */
  /* var disqus_config = function () {
      this.page.url = "brdyorn.com/posts/2016-08-06-upgrading-servant-client-from-zero-four.html";  // Replace PAGE_URL with your page's canonical URL variable
      this.page.identifier = "posts/2016-08-06-upgrading-servant-client-from-zero-four.md"; // Replace PAGE_IDENTIFIER with your page's unique identifier variable
      this.page.title = 'Upgrading Servant Clients';
  }; */
  (function() { // DON'T EDIT BELOW THIS LINE
      var d = document, s = d.createElement('script');
      s.src = '//brdyorn.disqus.com/embed.js';
      s.setAttribute('data-timestamp', +new Date());
      (d.head || d.body).appendChild(s);
  })();
  </script>
  <noscript>Please enable JavaScript to view the <a href="https://disqus.com/?ref_noscript">comments powered by Disqus.</a></noscript>
</div>

]]></description>
    <pubDate>Sat, 06 Aug 2016 00:00:00 UT</pubDate>
    <guid>http://brdyorn.com/posts/2016-08-06-upgrading-servant-client-from-zero-four.html</guid>
    <dc:creator>Brady Ouren</dc:creator>
</item>
<item>
    <title>A Typed Fullstack With Elm & Haskell</title>
    <link>http://brdyorn.com/posts/2016-08-04-typed-fullstack-with-elm-and-haskell.html</link>
    <description><![CDATA[<div class="info">
  <!-- Posted on Aug  4, 2016 -->
  
</div>

<h1 class="section-block blog">A Typed Fullstack With Elm & Haskell</h1>
<div class="post-body">
  <h3 id="hard-choices">Hard Choices</h3>
<p>Everytime you make a design decision about a system, you have to (or should) consider the possible maintenance implications. Personally, I think typed languages make this much more manageable. We’ll use Haskell and Elm to illustrate this case via a project called <a href="https://github.com/tippenein/hasken">hasken</a>.</p>
<p>This started as a simple CLI communicating with an API, but as is so common, we now want a frontend to display the resources on the web.</p>
<h3 id="what-we-want">What we want</h3>
<p>We want a few reasonable things:</p>
<ol style="list-style-type: decimal">
<li>Our entities should be synchronized between the frontend and backend.</li>
<li>Changes won’t break any existing functionality.</li>
<li>No way of leaving out edge cases</li>
</ol>
<h3 id="synchronizing-changes-between-api-and-frontend">Synchronizing changes between Api and Frontend</h3>
<p>When we have a change or addition to the representation of data, we’ll have to change both back- and frontend. There are a few possible solutions, but I’ve chosen to use <a href="https://github.com/typed-wire/typed-wire">typed-wire</a> which provides us with an intermediate language to define the common entities in.</p>
<pre><code>type Document{
  id : Int;
  title : String;
  content : String;
  tags : List&lt;String&gt;;
}</code></pre>
<p>When we’ve defined our entity, we can generate the code we need to produce and consume this data.</p>
<pre><code>twirec -e Document -i . --elm-out src/Gen --elm-version 0.17</code></pre>
<p>At the moment of this writing, typed wire can also generate a Spock api and json encodings, however, <em>hasken</em> already has a solid <a href="http://haskell-servant.readthedocs.io/en/stable/">servant</a> api defined, so we’ll be discussing how to use the generated elm bindings to have type-safe communication between them.</p>
<p>Note: The Servant side of things will be discussed in a separate post, but the same design principles and ensuing safety will be the same as we’ll see with Elm soon.</p>
<h3 id="maintainability">Maintainability</h3>
<p>Instead of writing a whole lot of tests (which also need maintenance) to ensure the proper manipulation of data between components, let’s encode this information in the types. This way, we’ll know how to fix something before we even write specs.</p>
<p><em>PSA: To be clear, I’m not saying “don’t write tests”; I’m saying “We can get away with far fewer!”</em></p>
<p>When you make changes to an Api, you should feel comfortable updating the frontend to match those changes. Types should help not hinder in this regard. For more context I like <a href="https://www.well-typed.com/blog/2014/04/haskell-gets-static-typing-right/">this</a> sum-up from Well-Typed.</p>
<blockquote>
<p>If you give your program precise types and follow systematic design principles, your program almost writes itself.</p>
</blockquote>
<p>As an example of using a compiler to guide feature implementation, let’s look at actions in Hasken’s interface:</p>
<div class="sourceCode"><pre class="sourceCode haskell"><code class="sourceCode haskell"><span class="kw">type</span> <span class="dt">Action</span>
  <span class="fu">=</span> <span class="dt">FetchDocuments</span>
  <span class="fu">|</span> <span class="dt">ErrorOccurred</span> <span class="dt">String</span>
  <span class="fu">|</span> <span class="dt">DocumentsFetched</span> (<span class="dt">List</span> <span class="dt">Document</span>)</code></pre></div>
<p>This encodes every possible state our app can be in. This is <em>huge</em>! The compiler will force us to deal with every case.</p>
<p>Our <code>model</code> holds the data which we’re trying to represent.</p>
<div class="sourceCode"><pre class="sourceCode haskell"><code class="sourceCode haskell">model <span class="fu">:</span> <span class="dt">Model</span>
model <span class="fu">=</span>
  { documents <span class="fu">=</span> <span class="dt">Right</span> []
  , queryString <span class="fu">=</span> <span class="st">&quot;&quot;</span>
  }</code></pre></div>
<p>At this point you might be thinking.. Isn’t this just redux? Yes! Reactive Programming is just a way of thinking about data flows. That fact isn’t as important as the way we can develop programs in Elm though.</p>
<h3 id="an-example-adding-search">An Example: Adding Search</h3>
<p>The ease of developing this interface shows with an example of adding a feature. Let’s add search.</p>
<p>First we add an Action union-type <code>Search String</code> which just means there is an action which supplies a string and represents “searching”. That’s all we know at the moment, but we want our app to represent this in some way. Now we look to the compiler.</p>
<p>It tells us that our <code>update</code> function doesn’t handle the <code>Search</code> action case.. So we must write it!</p>
<p>Our current update looks something like this:</p>
<div class="sourceCode"><pre class="sourceCode haskell"><code class="sourceCode haskell">update <span class="fu">:</span> <span class="dt">Action</span> <span class="ot">-&gt;</span> <span class="dt">Model</span> <span class="ot">-&gt;</span> (<span class="dt">Model</span>, <span class="dt">Cmd</span> <span class="dt">Action</span>)
update action model <span class="fu">=</span>
  <span class="kw">case</span> action <span class="kw">of</span>
    <span class="dt">FetchDocuments</span> <span class="ot">-&gt;</span>
      model <span class="fu">!</span> [fetchDocuments]
    <span class="dt">ErrorOccurred</span> errorMessage <span class="ot">-&gt;</span>
      { model <span class="fu">|</span> documents <span class="fu">=</span> <span class="dt">Left</span>(<span class="st">&quot;Oops! An error occurred: &quot;</span> <span class="fu">++</span> errorMessage) } <span class="fu">!</span> []
    <span class="dt">DocumentsFetched</span> documents <span class="ot">-&gt;</span>
      { model <span class="fu">|</span> documents <span class="fu">=</span> <span class="dt">Right</span>(documents) } <span class="fu">!</span> []

<span class="co">-- Syntax tip: `model ! [fetchDocuments]` is syntactic sugar for `(model, fetchDocuments)`</span>
<span class="co">-- Type tip: `Right` and `Left` are encoding success and failure. This is called the `Either` type.</span></code></pre></div>
<p>This method returns an updated model with some possible <code>Cmd Action</code>. If we’re going to fix the compilation error, we need to pattern match <code>Search term</code> and tell it how to react.</p>
<div class="sourceCode"><pre class="sourceCode haskell"><code class="sourceCode haskell"><span class="dt">Search</span> term <span class="ot">-&gt;</span> model <span class="fu">!</span> [searchDocs term]</code></pre></div>
<p>Now we define the function to fetch documents:</p>
<div class="sourceCode"><pre class="sourceCode haskell"><code class="sourceCode haskell">getDocs <span class="fu">:</span> <span class="dt">Maybe</span> (<span class="dt">List</span> (<span class="dt">String</span>, <span class="dt">String</span>)) <span class="ot">-&gt;</span> <span class="dt">Cmd</span> <span class="dt">Action</span>
getDocs mquery_params <span class="fu">=</span>
    <span class="kw">let</span> url <span class="fu">=</span> Http.url docUrl (fromMaybe [] q)
        docUrl <span class="fu">=</span> baseUrl <span class="fu">++</span> <span class="st">&quot;/documents&quot;</span>
    <span class="kw">in</span>
      Http.get (Json.list jdecDocument) url
        <span class="fu">|&gt;</span> Task.mapError toString
        <span class="fu">|&gt;</span> Task.perform <span class="dt">ErrorOccurred</span> <span class="dt">DocumentsFetched</span></code></pre></div>
<ol style="list-style-type: decimal">
<li>our chaining of tasks <code>|&gt; ... |&gt; ...</code> deals with encoding the result of the http requests into our action types (<code>ErrorOccured</code> &amp; <code>DocumentsFetched</code>)</li>
<li><code>jdecDocument</code> is the json decoder that was defined in our typed-wire-generated module; we expect a list of those.</li>
<li>query params might be empty, so we deal with that case via a <code>Maybe</code> and our <code>fromMaybe</code> defaults to <code>[]</code> if none are passed.</li>
</ol>
<h3 id="the-view">The view</h3>
<p>The next compiler error will tell us that we don’t have an interface component to <em>trigger</em> the <code>Search</code> action. We’ll be able to succinctly express this in our interface via the <code>view</code> function.</p>
<div class="sourceCode"><pre class="sourceCode haskell"><code class="sourceCode haskell">view <span class="fu">:</span> <span class="dt">Model</span> <span class="ot">-&gt;</span> <span class="dt">Html</span> <span class="dt">Action</span>
view model <span class="fu">=</span>
  div []
    [
      statusMessage model<span class="fu">.</span>documents
    , searchBox model <span class="dt">Search</span>  <span class="co">--- a function to generate markdown for a search box</span>
    , documentList model<span class="fu">.</span>documents
    ]</code></pre></div>
<p>From a high level, this is a very useful abstraction. We can modularize our view “partials” as we see fit and it helps us think about the best way to organize our components.</p>
<p>Now it will compile! We’ve successfully added a feature that we know works.</p>
<h3 id="what-next">What next?</h3>
<p>In the follow up we’ll talk about deploying all this in a sane way, but for now we can plan out the build steps.</p>
<p>I’ve just used a <code>Makefile</code> for now and it looks like:</p>
<pre><code>all:
    gen
    build
    js

gen:
	twirec -e Document -i . --elm-out src/Gen --elm-version 0.17

build:
	elm package install

js:
	elm make src/Main.elm --output=elm.js
</code></pre>
<p>After running this, we’ll have the json encoding module (in <code>src/Gen/</code>) along with a compiled elm.js which we can simply attach to an html node in our index:</p>
<div class="sourceCode"><pre class="sourceCode html"><code class="sourceCode html"><span class="kw">&lt;script</span><span class="ot"> src=</span><span class="st">&quot;./elm.js&quot;</span><span class="ot"> type=</span><span class="st">&quot;text/javascript&quot;</span><span class="kw">&gt;&lt;/script&gt;</span>
<span class="kw">&lt;script&gt;</span>
    <span class="kw">var</span> node <span class="op">=</span> <span class="va">document</span>.<span class="at">getElementById</span>(<span class="st">&#39;content&#39;</span>)<span class="op">;</span>
    <span class="kw">var</span> app <span class="op">=</span> <span class="va">Elm</span>.<span class="va">Main</span>.<span class="at">embed</span>(node)<span class="op">;</span>
<span class="kw">&lt;/script&gt;</span></code></pre></div>
<p>Since these steps won’t work on your machine unless you gather all the dependencies (typed-wire, ghc, elm, etc.), in the next step we’ll put this all in a docker container and show how to deploy it using whichever docker service you’d like.</p>

  <div class="pager">
    <ul class="list-unstyled list-inline">
      
        <li class="previous left">
          <a class="button" href="/posts/2016-07-29-simple-client-with-wreq.html" data-toggle="tooltip" data-placement="top" title="Previous Post">&larr; Previous Post</a>
        </li>
      

      
        <li class="next right">
          <a class="button" href="/posts/2016-08-06-upgrading-servant-client-from-zero-four.html" data-toggle="tooltip" data-placement="top" title="Next Post">Next Post &rarr;</a>
        </li>
      
    </ul>
  </div>
  <br>
  <br>
  <div id="disqus_thread"></div>
  <script>

  /**
   *  RECOMMENDED CONFIGURATION VARIABLES: EDIT AND UNCOMMENT THE SECTION BELOW TO INSERT DYNAMIC VALUES FROM YOUR PLATFORM OR CMS.
   *  LEARN WHY DEFINING THESE VARIABLES IS IMPORTANT: https://disqus.com/admin/universalcode/#configuration-variables */
  /*
  */
  /* var disqus_config = function () {
      this.page.url = "brdyorn.com/posts/2016-08-04-typed-fullstack-with-elm-and-haskell.html";  // Replace PAGE_URL with your page's canonical URL variable
      this.page.identifier = "posts/2016-08-04-typed-fullstack-with-elm-and-haskell.md"; // Replace PAGE_IDENTIFIER with your page's unique identifier variable
      this.page.title = 'A Typed Fullstack With Elm & Haskell';
  }; */
  (function() { // DON'T EDIT BELOW THIS LINE
      var d = document, s = d.createElement('script');
      s.src = '//brdyorn.disqus.com/embed.js';
      s.setAttribute('data-timestamp', +new Date());
      (d.head || d.body).appendChild(s);
  })();
  </script>
  <noscript>Please enable JavaScript to view the <a href="https://disqus.com/?ref_noscript">comments powered by Disqus.</a></noscript>
</div>

]]></description>
    <pubDate>Thu, 04 Aug 2016 00:00:00 UT</pubDate>
    <guid>http://brdyorn.com/posts/2016-08-04-typed-fullstack-with-elm-and-haskell.html</guid>
    <dc:creator>Brady Ouren</dc:creator>
</item>
<item>
    <title>Writing a simple cli with Wreq</title>
    <link>http://brdyorn.com/posts/2016-07-29-simple-client-with-wreq.html</link>
    <description><![CDATA[<div class="info">
  <!-- Posted on Jul 29, 2016 -->
  
</div>

<h1 class="section-block blog">Writing a simple cli with Wreq</h1>
<div class="post-body">
  <h3 id="starter-project">Starter project</h3>
<p>I remember when I started programming in python. I looked for anything I could write as a CLI or automate in some way, so in the spirit of that, I decided to write a bit about doing the same using haskell libraries.</p>
<p>I replaced monosnap functionality (sharing screenshots) with this script awhile back. It’s generically useful and <a href="https://github.com/tippenein/imgup/blob/master/lib/Imgup.hs">here is the whole of it</a> if you’re only interested in the source.</p>
<p>Also, there’s a deeper dive into Wreq <a href="http://www.serpentine.com/wreq/tutorial.html">here</a> if you find this cursory intro lacking</p>
<h3 id="bam-some-code">Bam! Some code</h3>
<p>The important imports:</p>
<div class="sourceCode"><pre class="sourceCode haskell"><code class="sourceCode haskell"><span class="kw">import </span><span class="dt">Data.Monoid</span> ((&lt;&gt;)) <span class="co">-- just for glueing together Text&#39;s</span>
<span class="kw">import </span><span class="dt">Network.Wreq</span>       <span class="co">-- the request library</span>
<span class="kw">import </span><span class="dt">Control.Lens</span>       <span class="co">-- setting and getting params/headers/etc</span>
<span class="kw">import </span><span class="dt">Data.Aeson.Lens</span>    <span class="co">-- same</span></code></pre></div>
<p>Since the main thing this script does is upload a photo anonymously to imgur, we’ll start with that function.</p>
<h3 id="the-request">The Request</h3>
<div class="sourceCode"><pre class="sourceCode haskell"><code class="sourceCode haskell"><span class="ot">uploadAndReturnUrl ::</span> <span class="dt">IO</span> <span class="dt">String</span>
uploadAndReturnUrl <span class="fu">=</span> <span class="kw">do</span>
  imagePath <span class="ot">&lt;-</span> parseArgs
  cid <span class="ot">&lt;-</span> clientId
  <span class="kw">let</span> authHeader <span class="fu">=</span> defaults <span class="fu">&amp;</span> header <span class="st">&quot;Authorization&quot;</span> <span class="fu">.~</span> [<span class="st">&quot;Client-ID&quot;</span> <span class="fu">&lt;&gt;</span> <span class="st">&quot; &quot;</span> <span class="fu">&lt;&gt;</span> cid]
  <span class="kw">let</span> payload <span class="fu">=</span> [ partText <span class="st">&quot;type&quot;</span> <span class="st">&quot;file&quot;</span>
                , partFile <span class="st">&quot;image&quot;</span> imagePath
                ]
                                  
  res <span class="ot">&lt;-</span> postWith authHeader <span class="st">&quot;https://api.imgur.com/3/image.json&quot;</span> payload
  <span class="kw">let</span> guid <span class="fu">=</span> res <span class="fu">^.</span> responseBody <span class="fu">.</span> key <span class="st">&quot;data&quot;</span> <span class="fu">.</span> key <span class="st">&quot;id&quot;</span> <span class="fu">.</span> _String
  return <span class="fu">$</span> <span class="st">&quot;http://imgur.com/&quot;</span> <span class="fu">++</span> T.unpack guid</code></pre></div>
<p>Let’s talk about what might be confusing here. The declaration of <code>authHeader</code>; what is that?</p>
<div class="sourceCode"><pre class="sourceCode haskell"><code class="sourceCode haskell"><span class="co">-- in this context, simply a merge </span>
<span class="ot">(&amp;) ::</span> a <span class="ot">-&gt;</span> (a <span class="ot">-&gt;</span> b) <span class="ot">-&gt;</span> b

<span class="co">-- build the header to combine with the defaults :: Options</span>
<span class="ot">header ::</span> <span class="dt">HeaderName</span> <span class="ot">-&gt;</span> ([<span class="dt">ByteString</span>] <span class="ot">-&gt;</span> f [<span class="dt">ByteString</span>]) <span class="ot">-&gt;</span> <span class="dt">Options</span> <span class="ot">-&gt;</span> <span class="dt">Options</span></code></pre></div>
<p>If you wanted to, you could think of this as an equivalent to the ruby code:</p>
<div class="sourceCode"><pre class="sourceCode ruby"><code class="sourceCode ruby">defaults = {<span class="st">:params</span> =&gt; [], <span class="st">:headers</span> =&gt; []}
defaults[<span class="st">:headers</span>].merge({ <span class="st">:Authorization</span> =&gt; <span class="st">&quot;Client-ID </span><span class="ot">#{</span>cid<span class="ot">}</span><span class="st">&quot;</span> })</code></pre></div>
<p>Fortunately, our code using Lens’ is much more fail-safe. (you could read more <a href="http://lens.github.io/tutorial.html">here</a> or one of the plethora of other lens tutorials online)</p>
<p>The actual post is pretty self explanatory if you know what <code>authHeader</code> and <code>payload</code> are, but here’s the type sig anyway:</p>
<div class="sourceCode"><pre class="sourceCode haskell"><code class="sourceCode haskell"><span class="ot">postWith ::</span> <span class="dt">Postable</span> a <span class="ot">=&gt;</span> <span class="dt">Options</span> <span class="ot">-&gt;</span> <span class="dt">String</span> <span class="ot">-&gt;</span> a <span class="ot">-&gt;</span> <span class="dt">IO</span> (<span class="dt">Response</span> <span class="dt">ByteString</span>)</code></pre></div>
<p>The <code>Postable</code> typeclass refers to our <code>[Part]</code> which we constructed in the payload declaration, nbd.</p>
<h3 id="the-response">The Response</h3>
<div class="sourceCode"><pre class="sourceCode haskell"><code class="sourceCode haskell">res <span class="fu">^.</span> responseBody <span class="fu">.</span> key <span class="st">&quot;data&quot;</span> <span class="fu">.</span> key <span class="st">&quot;id&quot;</span> <span class="fu">.</span> _String</code></pre></div>
<p>We use <code>^.</code> to pull out the image id returned from imgur. Unfortunately, lens’ compose left to right, unlike normal functions in haskell so this is <code>responseBody.data.id</code></p>
<p>The equivalent ruby code might be something like:</p>
<div class="sourceCode"><pre class="sourceCode ruby"><code class="sourceCode ruby">response.body[<span class="st">:data</span>][<span class="st">:id</span>]</code></pre></div>
<p>Again, ours is a bit safer.</p>
<h3 id="wrap-up">Wrap Up</h3>
<p>There’s one other piece which grabs the most recent screenshot.</p>
<div class="sourceCode"><pre class="sourceCode haskell"><code class="sourceCode haskell"><span class="ot">getRecentPath ::</span> <span class="dt">IO</span> FilePath
getRecentPath <span class="fu">=</span> <span class="kw">do</span>
  home <span class="ot">&lt;-</span> getHomeDirectory
  d <span class="ot">&lt;-</span> return (joinPath [home, <span class="st">&quot;Desktop&quot;</span>])
  files <span class="ot">&lt;-</span> globDir1 (compile <span class="st">&quot;Screen Shot*&quot;</span>) d
  <span class="kw">case</span> headMaybe (reverse (sort files)) <span class="kw">of</span> 
    <span class="dt">Nothing</span> <span class="ot">-&gt;</span> error <span class="st">&quot;no recent screenshots&quot;</span>
    <span class="dt">Just</span> a <span class="ot">-&gt;</span> return a</code></pre></div>
<p>This could be improved by returning an <code>Either String FilePath</code> instead of raising an error, but if we stopped and optimized every chance we had in haskell we’d never finish writing what we started.</p>
<p>At the end of all this, we can screen cap and pop over to a terminal:</p>
<pre class="shell"><code>imgup --screenshot | pbcopy</code></pre>
<p>Now we have an imgur link in our copy buffer which (for me) completely replaces monosnap’s functionality.</p>

  <div class="pager">
    <ul class="list-unstyled list-inline">
      
        <li class="previous left">
          <a class="button" href="/posts/2016-06-05-monoidal-sum.html" data-toggle="tooltip" data-placement="top" title="Previous Post">&larr; Previous Post</a>
        </li>
      

      
        <li class="next right">
          <a class="button" href="/posts/2016-08-04-typed-fullstack-with-elm-and-haskell.html" data-toggle="tooltip" data-placement="top" title="Next Post">Next Post &rarr;</a>
        </li>
      
    </ul>
  </div>
  <br>
  <br>
  <div id="disqus_thread"></div>
  <script>

  /**
   *  RECOMMENDED CONFIGURATION VARIABLES: EDIT AND UNCOMMENT THE SECTION BELOW TO INSERT DYNAMIC VALUES FROM YOUR PLATFORM OR CMS.
   *  LEARN WHY DEFINING THESE VARIABLES IS IMPORTANT: https://disqus.com/admin/universalcode/#configuration-variables */
  /*
  */
  /* var disqus_config = function () {
      this.page.url = "brdyorn.com/posts/2016-07-29-simple-client-with-wreq.html";  // Replace PAGE_URL with your page's canonical URL variable
      this.page.identifier = "posts/2016-07-29-simple-client-with-wreq.md"; // Replace PAGE_IDENTIFIER with your page's unique identifier variable
      this.page.title = 'Writing a simple cli with Wreq';
  }; */
  (function() { // DON'T EDIT BELOW THIS LINE
      var d = document, s = d.createElement('script');
      s.src = '//brdyorn.disqus.com/embed.js';
      s.setAttribute('data-timestamp', +new Date());
      (d.head || d.body).appendChild(s);
  })();
  </script>
  <noscript>Please enable JavaScript to view the <a href="https://disqus.com/?ref_noscript">comments powered by Disqus.</a></noscript>
</div>

]]></description>
    <pubDate>Fri, 29 Jul 2016 00:00:00 UT</pubDate>
    <guid>http://brdyorn.com/posts/2016-07-29-simple-client-with-wreq.html</guid>
    <dc:creator>Brady Ouren</dc:creator>
</item>
<item>
    <title>Exploring monoids for sum averages</title>
    <link>http://brdyorn.com/posts/2016-06-05-monoidal-sum.html</link>
    <description><![CDATA[<div class="info">
  <!-- Posted on Jun  5, 2016 -->
  
</div>

<h1 class="section-block blog">Exploring monoids for sum averages</h1>
<div class="post-body">
  <p>In <a href="https://www.youtube.com/watch?v=cMY1KVrJk0w">a talk</a> by Avi Bryant about practical systems for Analytics or Aggregation he drew comparisons to Monoids and Abelian Groups. I thought it would be helpful to work through what he was explaining with haskell, so here we go.</p>
<p>The first thing discussed is a simple summing with a monoid. We need implementations for:</p>
<ul>
<li>mempty: somewhere to start; something that won’t affect the outcome of the sum.</li>
<li>mappend: a way of combining 2 instances together, (we’ll use the infix notation or <code>&lt;&gt;</code>)</li>
<li>mconcat: a way of combining a list of instances together down into a single instance (a fold)</li>
</ul>
<p>The point of this abstraction is to easily allow a fold (reduce) of any data type into itself. It doesn’t <em>have</em> to be commutative, but these monoid instances happen to be. (Abelian groups however, <em>have</em> to be commutative)</p>
<h3 id="part-1---a-simple-sum">Part 1 - A simple Sum</h3>
<div class="sourceCode"><pre class="sourceCode haskell"><code class="sourceCode haskell"><span class="kw">data</span> <span class="dt">Collection</span> <span class="fu">=</span> <span class="dt">Collection</span> {<span class="ot"> theSum ::</span> <span class="dt">Integer</span> }
<span class="kw">instance</span> <span class="dt">Monoid</span> <span class="dt">Collection</span> <span class="kw">where</span>
  mempty <span class="fu">=</span> <span class="dt">Collection</span> <span class="dv">0</span>
  <span class="dt">Collection</span> sum1 <span class="ot">`mappend`</span> <span class="dt">Collection</span> sum2 <span class="fu">=</span> <span class="dt">Collection</span> (sum1 <span class="fu">+</span> sum2)
  mconcat <span class="fu">=</span> foldl&#39; mconcat mempty</code></pre></div>
<p>That isn’t an astounding monoid instance by any means, but it allows us to do simple summing:</p>
<div class="sourceCode"><pre class="sourceCode haskell"><code class="sourceCode haskell">mconcat [<span class="dt">Collection</span> <span class="dv">1</span>, <span class="dt">Collection</span> <span class="dv">10</span>, <span class="dt">Collection</span> <span class="dv">20</span>]
<span class="co">-- &gt; Collection {theSum = 31}</span>

<span class="co">-- &lt;&gt; is just an operator equivalent to mappend</span>
<span class="dt">Collection</span> <span class="dv">1</span> <span class="fu">&lt;&gt;</span> <span class="dt">Collection</span> <span class="dv">2</span>
<span class="co">-- &gt; Collection { theSum = 3 }</span></code></pre></div>
<h3 id="part-2---a-simple-averaging-aggregation">Part 2 - A simple Averaging aggregation</h3>
<p>The next step is to average the sum as we go.</p>
<div class="sourceCode"><pre class="sourceCode haskell"><code class="sourceCode haskell"><span class="kw">data</span> <span class="dt">Collection</span> <span class="fu">=</span> <span class="dt">Collection</span> 
  {<span class="ot"> theSum ::</span> <span class="dt">Integer</span>
  ,<span class="ot"> avg ::</span> <span class="dt">Maybe</span> <span class="dt">Double</span> }</code></pre></div>
<p>What we’d expect with this is <code>Collection 1 1 &lt;&gt; Collection 10 10</code> to equal <code>Collection {sum = 11, avg = 5.5 }</code></p>
<p>Later on we might want to subtract a Collection from this aggregation or weight the averages. These scenarios can be handled by storing a <code>count</code> of <code>Collections</code> seen so far. Ideally we would have an implicit count instead of a repetitive explicit argument, but for now let’s just add count to the data type and write a quickcheck property for counting:</p>
<div class="sourceCode"><pre class="sourceCode haskell"><code class="sourceCode haskell"><span class="co">-- btw, the data type now looks like:</span>
<span class="co">-- { theSum :: Integer, count :: Integer, avg :: Maybe Double }</span>
it <span class="st">&quot;counts consistently&quot;</span> <span class="fu">$</span> property <span class="fu">$</span> \n <span class="ot">-&gt;</span>
  count (mconcat <span class="fu">$</span> replicate n justOnes) <span class="ot">`shouldEqual`</span> n</code></pre></div>
<p>QuickCheck will tell us one error that we probably didn’t consider: What if the count is negative? We shouldn’t allow that, but for now we’re just going to take the absolute value of what quickcheck inputs and test all the positive values of <code>count</code>.</p>
<div class="sourceCode"><pre class="sourceCode haskell"><code class="sourceCode haskell">count (mconcat <span class="fu">$</span> replicate (abs n) justOnes) <span class="ot">`shouldBe`</span> abs n</code></pre></div>
<p>(I’m fighting the urge to tangent on QuickCheck, but I promise to tackle it in a different post)</p>
<p>Now for the instance definition of our new averaging sum-thingy! I’ll skip over the more trivial parts, but the example repo will be available for a complete look <a href="https://github.com/tippenein/commutative-monoid-example">here</a></p>
<div class="sourceCode"><pre class="sourceCode haskell"><code class="sourceCode haskell">
<span class="co">-- The only thing changing here is the mappend definition</span>
<span class="kw">instance</span> <span class="dt">Monoid</span> <span class="dt">Collection</span> <span class="kw">where</span>
  mempty <span class="fu">=</span> <span class="dt">Collection</span> <span class="dv">0</span> <span class="dv">0</span> <span class="dt">Nothing</span>
  <span class="co">-- The cases where average is Nothing are omitted</span>
  (<span class="dt">Collection</span> s1 c1 (<span class="dt">Just</span> avg1)) <span class="ot">`mappend`</span> (<span class="dt">Collection</span> s2 c2 (<span class="dt">Just</span> avg2)) <span class="fu">=</span>
    <span class="dt">Collection</span> (s1 <span class="fu">+</span> s2) (c1 <span class="fu">+</span> c2) average
    <span class="kw">where</span>
      average <span class="fu">=</span> <span class="dt">Just</span> <span class="fu">$</span>
        ((avg1 <span class="fu">*</span> fromInteger c1) <span class="fu">+</span> (avg2 <span class="fu">*</span> fromInteger c2))
          <span class="fu">/</span> (fromInteger c1 <span class="fu">+</span> fromInteger c2)
  mconcat <span class="fu">=</span> foldl&#39; mconcat mempty</code></pre></div>
<p>You might say “That’s just some grade-school weighted average stuff.. childs play!”, and you’d be right!</p>
<h3 id="part-3---the-beauty-of-this-abstraction">Part 3 - The beauty of this abstraction</h3>
<p>Ok, the weighted average is fine.. but what if we also wanted a top 10 aggregation. It turns out we still only need to change a few things to get this aggregation to work.</p>
<p>We might as well drive the implementation with specs since the intention is well defined.</p>
<div class="sourceCode"><pre class="sourceCode haskell"><code class="sourceCode haskell"><span class="co">-- I usually write the intended data type first then use that interface to build specs.</span>
<span class="co">-- so here&#39;s our new fields for the CollectionTops data type</span>
<span class="co">-- { aSum :: Integer, tops :: [Integer] }</span>

topsCollection1 <span class="fu">=</span> <span class="dt">CollectionTops</span> <span class="dv">1</span> (reverse [<span class="dv">1</span><span class="fu">..</span><span class="dv">10</span>])

it <span class="st">&quot;collects the top10&quot;</span> <span class="fu">$</span>
  topsCollection1 <span class="fu">&lt;&gt;</span> mempty <span class="ot">`shouldBe`</span> topsCollection1

it <span class="st">&quot;collects the top10&quot;</span> <span class="fu">$</span> <span class="kw">do</span>
  <span class="kw">let</span> cs <span class="fu">=</span> topsCollection1 <span class="fu">&lt;&gt;</span> <span class="dt">CollectionTops</span> <span class="dv">3000</span> negativeInfinities
  head (tops cs) <span class="ot">`shouldBe`</span> <span class="dv">3000</span>
  (<span class="dv">1</span> <span class="ot">`elem`</span> tops cs) <span class="ot">`shouldBe`</span> <span class="dt">False</span> <span class="co">-- it knocks 1 out of the list</span></code></pre></div>
<div class="sourceCode"><pre class="sourceCode haskell"><code class="sourceCode haskell">negativeInfinities <span class="fu">=</span> replicate <span class="dv">10</span> (<span class="fu">-</span><span class="dv">1</span>)
revSort <span class="fu">=</span> sortBy (flip compare)

<span class="kw">instance</span> <span class="dt">Monoid</span> <span class="dt">CollectionTops</span> <span class="kw">where</span>
  mempty <span class="fu">=</span> <span class="dt">CollectionTops</span> <span class="dv">0</span> negativeInfinities
  <span class="dt">CollectionTops</span> s1 tops1 <span class="ot">`mappend`</span> <span class="dt">CollectionTops</span> s2 tops2 <span class="fu">=</span>
    <span class="dt">CollectionTops</span> {
      aSum <span class="fu">=</span> s1 <span class="fu">+</span> s2
    , tops <span class="fu">=</span> take <span class="dv">10</span> <span class="fu">$</span> revSort ([s1] <span class="fu">++</span> [s2] <span class="fu">++</span> tops1 <span class="fu">++</span> tops2) }
  mconcat <span class="fu">=</span> foldl&#39; mappend mempty</code></pre></div>
<h3 id="part-4---sum-up-pun-intended">Part 4 - Sum up (pun intended)</h3>
<p>In his talk, Avi obviously goes further than this, however, this post is already becoming too long. Other uses hinted at include <a href="https://en.wikipedia.org/wiki/Skewness">skewness</a>, <a href="https://en.wikipedia.org/wiki/Kurtosis">kurtosis</a>, histograms, and unique visitors. The above implementations are intended to give an intuition about commutative monoids as a tool for aggregation.</p>
<p>To sum up…</p>
<ul>
<li>we need 3 functions for a monoid instance: mempty, mappend, and mconcat.</li>
<li>If you can define mappend, the other 2 should be easy (I’ve noticed that mconcat is mostly just used to provide a faster implementation of the standard <code>foldr mappend mempty</code>).</li>
<li>The monoid laws ensure associativity, but we have to be explicit about our commutative intentions.</li>
</ul>
<p>I hope this calms your nerves about monoids and perhaps provides a bit of intuition about what <em>is</em> or <em>could be</em> a monoid.</p>

  <div class="pager">
    <ul class="list-unstyled list-inline">
      
        <li class="previous left">
          <a class="button" href="/posts/2016-04-18-simple-enum-generation.html" data-toggle="tooltip" data-placement="top" title="Previous Post">&larr; Previous Post</a>
        </li>
      

      
        <li class="next right">
          <a class="button" href="/posts/2016-07-29-simple-client-with-wreq.html" data-toggle="tooltip" data-placement="top" title="Next Post">Next Post &rarr;</a>
        </li>
      
    </ul>
  </div>
  <br>
  <br>
  <div id="disqus_thread"></div>
  <script>

  /**
   *  RECOMMENDED CONFIGURATION VARIABLES: EDIT AND UNCOMMENT THE SECTION BELOW TO INSERT DYNAMIC VALUES FROM YOUR PLATFORM OR CMS.
   *  LEARN WHY DEFINING THESE VARIABLES IS IMPORTANT: https://disqus.com/admin/universalcode/#configuration-variables */
  /*
  */
  /* var disqus_config = function () {
      this.page.url = "brdyorn.com/posts/2016-06-05-monoidal-sum.html";  // Replace PAGE_URL with your page's canonical URL variable
      this.page.identifier = "posts/2016-06-05-monoidal-sum.md"; // Replace PAGE_IDENTIFIER with your page's unique identifier variable
      this.page.title = 'Exploring monoids for sum averages';
  }; */
  (function() { // DON'T EDIT BELOW THIS LINE
      var d = document, s = d.createElement('script');
      s.src = '//brdyorn.disqus.com/embed.js';
      s.setAttribute('data-timestamp', +new Date());
      (d.head || d.body).appendChild(s);
  })();
  </script>
  <noscript>Please enable JavaScript to view the <a href="https://disqus.com/?ref_noscript">comments powered by Disqus.</a></noscript>
</div>

]]></description>
    <pubDate>Sun, 05 Jun 2016 00:00:00 UT</pubDate>
    <guid>http://brdyorn.com/posts/2016-06-05-monoidal-sum.html</guid>
    <dc:creator>Brady Ouren</dc:creator>
</item>
<item>
    <title>Using Template Haskell to generate an Enum</title>
    <link>http://brdyorn.com/posts/2016-04-18-simple-enum-generation.html</link>
    <description><![CDATA[<div class="info">
  <!-- Posted on Apr 18, 2016 -->
  
</div>

<h1 class="section-block blog">Using Template Haskell to generate an Enum</h1>
<div class="post-body">
  <h3 id="a-simple-useful-case-for-template-haskell">A simple useful case for Template Haskell</h3>
<div class="sourceCode"><pre class="sourceCode haskell"><code class="sourceCode haskell"><span class="ot">{-# LANGUAGE TemplateHaskell #-}</span>

<span class="kw">import </span><span class="dt">Language.Haskell.TH</span>

<span class="ot">declareAnimals ::</span> [<span class="dt">String</span>] <span class="ot">-&gt;</span> <span class="dt">Q</span> [<span class="dt">Dec</span>]
declareAnimals animals <span class="fu">=</span>
  return [<span class="dt">DataD</span> constraints name vars cons derives]
    <span class="kw">where</span>
      constraints <span class="fu">=</span> []
      name        <span class="fu">=</span> mkName <span class="st">&quot;Animal&quot;</span>
      vars        <span class="fu">=</span> []
      cons        <span class="fu">=</span> map (\a <span class="ot">-&gt;</span> <span class="dt">NormalC</span> (mkName a) fields) animals
      fields      <span class="fu">=</span> []
      derives     <span class="fu">=</span> [<span class="ch">&#39;&#39;</span><span class="dt">Show</span>, <span class="ch">&#39;&#39;</span><span class="dt">Eq</span>, <span class="ch">&#39;&#39;</span><span class="dt">Ord</span>, <span class="ch">&#39;&#39;</span><span class="dt">Enum</span>, <span class="ch">&#39;&#39;</span><span class="dt">Read</span>]</code></pre></div>
<div class="sourceCode"><pre class="sourceCode haskell"><code class="sourceCode haskell">animals <span class="fu">=</span> [<span class="st">&quot;Aardvark&quot;</span>, <span class="st">&quot;Bobcat&quot;</span>, <span class="st">&quot;Quokka&quot;</span>]
<span class="fu">$</span>(declareAnimals animals)

<span class="co">-- data Signal = Aardvark | Bobcat | Quokka</span></code></pre></div>
<p>If you only cared about getting an enum type, this is where you can jump off.</p>
<h3 id="digging-into-the-types">Digging into the types</h3>
<p>If we look further at the types involved here, we can learn more about what this is doing.</p>
<p>At a high level, we’re simply building a haskell AST and introducing it into our code-base. You can think of this as meta-programming but if you ask me it’s more like playing with legos.</p>
<p>We construct a <code>data</code> declaration with <code>DataD</code></p>
<div class="sourceCode"><pre class="sourceCode haskell"><code class="sourceCode haskell"><span class="dt">DataD</span><span class="ot"> ::</span> <span class="dt">Cxt</span> <span class="ot">-&gt;</span> <span class="dt">Name</span> <span class="ot">-&gt;</span> [<span class="dt">TyVarBndr</span>] <span class="ot">-&gt;</span> [<span class="dt">Con</span>] <span class="ot">-&gt;</span> [<span class="dt">Name</span>] <span class="ot">-&gt;</span> <span class="dt">Dec</span></code></pre></div>
<p>or if we spread this out and document each piece.</p>
<div class="sourceCode"><pre class="sourceCode haskell"><code class="sourceCode haskell"><span class="dt">DataD</span><span class="ot"> ::</span> <span class="dt">Cxt</span>          <span class="co">-- constraints (eg. Num a =&gt; a -&gt; a)</span>
      <span class="ot">-&gt;</span> <span class="dt">Name</span>         <span class="co">-- the type name</span>
      <span class="ot">-&gt;</span> [<span class="dt">TyVarBndr</span>]  <span class="co">-- type variable bindings</span>
      <span class="ot">-&gt;</span> [<span class="dt">Con</span>]        <span class="co">-- constructors</span>
      <span class="ot">-&gt;</span> [<span class="dt">Name</span>]       <span class="co">-- deriving types (eg. Eq, Ord, etc)</span>
      <span class="ot">-&gt;</span> <span class="dt">Dec</span></code></pre></div>
<p>simple <code>Name</code> constructor</p>
<div class="sourceCode"><pre class="sourceCode haskell"><code class="sourceCode haskell"><span class="ot">mkName ::</span> <span class="dt">String</span> <span class="ot">-&gt;</span> <span class="dt">Name</span></code></pre></div>
<p>build a normal Constructor</p>
<div class="sourceCode"><pre class="sourceCode haskell"><code class="sourceCode haskell"><span class="dt">NormalC</span><span class="ot"> ::</span> <span class="dt">Name</span> <span class="ot">-&gt;</span> [<span class="dt">StrictType</span>] <span class="ot">-&gt;</span> <span class="dt">Con</span></code></pre></div>
<p>The <code>derives</code> need to have the double-tick in order to be read as a syntax builder rather than an actual deriving statement. The same goes for type constraints and such.</p>
<p>You can look at all this documentation on the <a href="https://hackage.haskell.org/package/template-haskell-2.10.0.0/docs/Language-Haskell-TH-Syntax.html">Language.Haskell.TH</a> page</p>

  <div class="pager">
    <ul class="list-unstyled list-inline">
      
        <li class="previous left">
          <a class="button" href="/posts/2016-03-27-parser-combinators2.html" data-toggle="tooltip" data-placement="top" title="Previous Post">&larr; Previous Post</a>
        </li>
      

      
        <li class="next right">
          <a class="button" href="/posts/2016-06-05-monoidal-sum.html" data-toggle="tooltip" data-placement="top" title="Next Post">Next Post &rarr;</a>
        </li>
      
    </ul>
  </div>
  <br>
  <br>
  <div id="disqus_thread"></div>
  <script>

  /**
   *  RECOMMENDED CONFIGURATION VARIABLES: EDIT AND UNCOMMENT THE SECTION BELOW TO INSERT DYNAMIC VALUES FROM YOUR PLATFORM OR CMS.
   *  LEARN WHY DEFINING THESE VARIABLES IS IMPORTANT: https://disqus.com/admin/universalcode/#configuration-variables */
  /*
  */
  /* var disqus_config = function () {
      this.page.url = "brdyorn.com/posts/2016-04-18-simple-enum-generation.html";  // Replace PAGE_URL with your page's canonical URL variable
      this.page.identifier = "posts/2016-04-18-simple-enum-generation.md"; // Replace PAGE_IDENTIFIER with your page's unique identifier variable
      this.page.title = 'Using Template Haskell to generate an Enum';
  }; */
  (function() { // DON'T EDIT BELOW THIS LINE
      var d = document, s = d.createElement('script');
      s.src = '//brdyorn.disqus.com/embed.js';
      s.setAttribute('data-timestamp', +new Date());
      (d.head || d.body).appendChild(s);
  })();
  </script>
  <noscript>Please enable JavaScript to view the <a href="https://disqus.com/?ref_noscript">comments powered by Disqus.</a></noscript>
</div>

]]></description>
    <pubDate>Mon, 18 Apr 2016 00:00:00 UT</pubDate>
    <guid>http://brdyorn.com/posts/2016-04-18-simple-enum-generation.html</guid>
    <dc:creator>Brady Ouren</dc:creator>
</item>
<item>
    <title>Parser Combinatorz part2</title>
    <link>http://brdyorn.com/posts/2016-03-27-parser-combinators2.html</link>
    <description><![CDATA[<div class="info">
  <!-- Posted on Mar 27, 2016 -->
  
</div>

<h1 class="section-block blog">Parser Combinatorz part2</h1>
<div class="post-body">
  <h3 id="prt2">P▲rT2</h3>
<p>In the <a href="/posts/2016-03-26-parser-combinators.html">previous post</a> I showed how to use <a href="https://www.stackage.org/package/parsec">parsec</a> to parse data in a format like this:</p>
<p><code>&quot;1%400:3.2 6%some_description|100:1&quot;</code></p>
<h3 id="why-not-regex">Why not regex?</h3>
<p>I certainly could’ve used a regex pattern like <code>\d\%(\w*\|)?(\d+):(\d+\.?\d?)</code></p>
<p>…but, there are some scenarios where this falls apart quite quickly:</p>
<ul>
<li>if we learn about other formats of data that can be included</li>
<li>if we have other parsing tasks that need similar matchers?</li>
<li>if we need to morph the data in some way before matching</li>
<li>if the list of possible separators are very large. (<code>\d\%|\$$|\&amp;|...</code>)</li>
</ul>
<h3 id="an-example-to-prove-im-not-making-this-up">An example to prove I’m not making this up</h3>
<p>I had never encountered the acronym FFR until I started working in financial software. It stands for Fixed Format Response, but that’s not really important. The important part is that the FFR we’re dealing with has ~100 different signals which indicate a specific type of data.</p>
<p>So, we’ll create a data type deriving <code>Enum</code> to describe how we expect to split the data up.</p>
<div class="sourceCode"><pre class="sourceCode haskell"><code class="sourceCode haskell">
<span class="kw">data</span> <span class="dt">Signal</span>
  <span class="fu">=</span> <span class="dt">AD02</span> <span class="fu">|</span> <span class="dt">AD11</span> <span class="fu">|</span> <span class="dt">AH11</span> <span class="fu">|</span> <span class="dt">AM01</span> <span class="fu">|</span>
    <span class="dt">AO01</span> <span class="fu">|</span> <span class="dt">AR01</span> <span class="fu">|</span> <span class="dt">AS01</span> <span class="fu">|</span> <span class="dt">AT11</span> <span class="fu">|</span> <span class="dt">BR01</span> <span class="fu">|</span>
    <span class="co">-- ... more of these removed for reading clarity</span>
    <span class="dt">UA11</span> <span class="fu">|</span> <span class="dt">UF11</span> <span class="fu">|</span> <span class="dt">VH01</span> <span class="fu">|</span> <span class="dt">VS01</span> <span class="fu">|</span> <span class="dt">WS01</span> <span class="fu">|</span>
    <span class="dt">YI01</span> <span class="fu">|</span> <span class="dt">ZC01</span>
  <span class="kw">deriving</span> (<span class="dt">Show</span>, <span class="dt">Enum</span>, <span class="dt">Ord</span>, <span class="dt">Eq</span>, <span class="dt">Read</span>)

<span class="ot">allSignals ::</span> [<span class="dt">String</span>]
allSignals <span class="fu">=</span> map show [<span class="dt">AD02</span> <span class="fu">..</span>]</code></pre></div>
<p>Note: The syntax for <code>allSignals</code> is just enumerating all the constructors. (The space is significant <code>[YourFirstEnum ..]</code>)</p>
<div class="sourceCode"><pre class="sourceCode haskell"><code class="sourceCode haskell"><span class="co">-- notice we&#39;re reusing this from the previous parser</span>
anythingUntil p <span class="fu">=</span> manyTill anyToken p

<span class="ot">anySignal ::</span> <span class="dt">Parser</span> (<span class="dt">Signal</span>, <span class="dt">String</span>)
anySignal <span class="fu">=</span> <span class="kw">do</span>
  signal <span class="ot">&lt;-</span> signalParser
  content <span class="ot">&lt;-</span> anythingUntil (endOfLineOrInput <span class="fu">&lt;|&gt;</span> signalLookahead)
  return (toSignal signal, content)

signalLookahead <span class="fu">=</span> lookAhead signalParser <span class="fu">*&gt;</span> return ()

<span class="ot">signalParser ::</span> <span class="dt">Parser</span> <span class="dt">String</span>
signalParser <span class="fu">=</span> choice <span class="fu">$</span> fmap try <span class="fu">$</span> string <span class="fu">&lt;$&gt;</span> allSignals</code></pre></div>
<p>We’re going to use the <code>anySignal</code> parser to pull out many pieces of content from a string, but the interesting part is the <code>signalParser</code> itself. <code>choice</code> and <code>&lt;|&gt;</code> are the same, but we need to choose between <em>all</em> the signals so we pass a list of Parsers. If it helps, it looks a bit like this if you were to expand it:</p>
<div class="sourceCode"><pre class="sourceCode haskell"><code class="sourceCode haskell">choice [(try <span class="fu">$</span> string <span class="st">&quot;AD02&quot;</span>), (try <span class="fu">$</span> string <span class="st">&quot;AD11&quot;</span>), <span class="fu">...</span>]</code></pre></div>
<p>Another thing to note is the <code>signalLookahead</code>. We need to avoid eating up the next signal and just use it to signal the end of input.</p>
<p>Once again, there’s a freeze of the jupyter notebook if you’d like to see it in the full context (<a href="/slides/ffrparse">here</a>)</p>
<h3 id="further-processing">Further processing</h3>
<p>There are many more things we can do with our data in this format, but the first thing I would do is consume the data into some Map like this:</p>
<div class="sourceCode"><pre class="sourceCode haskell"><code class="sourceCode haskell"><span class="kw">type</span> <span class="dt">SignalMap</span> <span class="fu">=</span> <span class="dt">Map.Map</span> <span class="dt">Signal</span> <span class="dt">String</span></code></pre></div>
<p>From here we’d want to inspect what each signal has inside of it, so we can take from this <code>Map</code> and further parse the string content.</p>
<h3 id="credit">Credit</h3>
<p>Thanks a bunch to both of these resources (which are both far better and more comprehensive than this):</p>
<ul>
<li><a href="https://github.com/JakeWheat/intro_to_parsing" class="uri">https://github.com/JakeWheat/intro_to_parsing</a></li>
<li><a href="http://unbui.lt/#!/post/haskell-parsec-basics/" class="uri">http://unbui.lt/#!/post/haskell-parsec-basics/</a></li>
</ul>

  <div class="pager">
    <ul class="list-unstyled list-inline">
      
        <li class="previous left">
          <a class="button" href="/posts/2016-03-26-parser-combinators.html" data-toggle="tooltip" data-placement="top" title="Previous Post">&larr; Previous Post</a>
        </li>
      

      
        <li class="next right">
          <a class="button" href="/posts/2016-04-18-simple-enum-generation.html" data-toggle="tooltip" data-placement="top" title="Next Post">Next Post &rarr;</a>
        </li>
      
    </ul>
  </div>
  <br>
  <br>
  <div id="disqus_thread"></div>
  <script>

  /**
   *  RECOMMENDED CONFIGURATION VARIABLES: EDIT AND UNCOMMENT THE SECTION BELOW TO INSERT DYNAMIC VALUES FROM YOUR PLATFORM OR CMS.
   *  LEARN WHY DEFINING THESE VARIABLES IS IMPORTANT: https://disqus.com/admin/universalcode/#configuration-variables */
  /*
  */
  /* var disqus_config = function () {
      this.page.url = "brdyorn.com/posts/2016-03-27-parser-combinators2.html";  // Replace PAGE_URL with your page's canonical URL variable
      this.page.identifier = "posts/2016-03-27-parser-combinators2.md"; // Replace PAGE_IDENTIFIER with your page's unique identifier variable
      this.page.title = 'Parser Combinatorz part2';
  }; */
  (function() { // DON'T EDIT BELOW THIS LINE
      var d = document, s = d.createElement('script');
      s.src = '//brdyorn.disqus.com/embed.js';
      s.setAttribute('data-timestamp', +new Date());
      (d.head || d.body).appendChild(s);
  })();
  </script>
  <noscript>Please enable JavaScript to view the <a href="https://disqus.com/?ref_noscript">comments powered by Disqus.</a></noscript>
</div>

]]></description>
    <pubDate>Sun, 27 Mar 2016 00:00:00 UT</pubDate>
    <guid>http://brdyorn.com/posts/2016-03-27-parser-combinators2.html</guid>
    <dc:creator>Brady Ouren</dc:creator>
</item>

    </channel>
</rss>
