<?xml version="1.0" encoding="utf-8"?>
<feed xmlns="http://www.w3.org/2005/Atom">
    <title>chromatic leaves - All posts</title>
    <link href="http://chromaticleaves.com/rss.xml" rel="self" />
    <link href="http://chromaticleaves.com" />
    <id>http://chromaticleaves.com/rss.xml</id>
    <author>
        <name>Eric Rasmussen</name>
        <email>eric@chromaticleaves.com</email>
    </author>
    <updated>2015-01-29T00:00:00Z</updated>
    <entry>
    <title>Nix in Two Days</title>
    <link href="http://chromaticleaves.com/posts/nix-in-2-days.html" />
    <id>http://chromaticleaves.com/posts/nix-in-2-days.html</id>
    <published>2015-01-29T00:00:00Z</published>
    <updated>2015-01-29T00:00:00Z</updated>
    <summary type="html"><![CDATA[<p>Software developer proverb:</p>
<blockquote>
<p>There are two hard problems in software development: packaging, and deployment.</p>
</blockquote>
<h4 id="the-deployment-dilemma">The deployment dilemma</h4>
<p>If you write code, sooner or later you’ll probably need to:</p>
<ul>
<li>leverage other people’s code</li>
<li>declare external dependencies</li>
<li>run your code somewhere other than your dev machine</li>
</ul>
<p>It turns out this is kind of a hard problem, and new solutions are being invented all the time:</p>
<table>
<thead>
<tr class="header">
<th align="left">Misleading Google Search Results</th>
</tr>
</thead>
<tbody>
<tr class="odd">
<td align="left"><a href="https://www.google.com/#q=deployment+methods">deployment methods</a></td>
<td align="left">108,000,000</td>
</tr>
<tr class="even">
<td align="left"><a href="https://www.google.com/#q=package+managers">package managers</a></td>
<td align="left">9,080,000</td>
</tr>
</tbody>
</table>
<p>Should I use virtual machines? Containers? Do I need configuration management tools? Should I be looking into hosted services in The Cloud? There are no easy answers to these questions, and it takes a lot of time and practice to become familiar with their tradeoffs and choose an appropriate strategy for your project.</p>
<p>But regardless of what you choose, there’s one thing they almost always have in common: packages.</p>
<p>Somewhere along the line your deployment strategy will be improved by being able to install something (build or runtime dependencies, your own code, or even automation tools themselves) if it’s already been packaged up in a way that’s reproducible and reliable.</p>
<p>We’ll show you how you can incorporate the Nix package manager into your workflow in two days with minimal disruption and time. You can start taking advantage of its benefits almost immediately (such as installing multiple packages at once that have conflicting versions or dependencies), but still use it alongside any package managers you’re already using.</p>
<h4 id="package-managers">Package managers</h4>
<p>If you haven’t spent time with Nix, you’re probably wondering why you need a new package manager. We already have apt/yum/homebrew/etc., all with their own approaches, and the whole situation starts to feel a little like…</p>
<div class="figure">
<img src="/images/xkcd_standards.png" title="Standards (xkcd.com)" />
</div>
<p><a href="http://xkcd.com/927/">Standards (xkcd.com)</a></p>
<p>So why bother learning Nix?</p>
<p>Because it <em>is</em> different! It’s based on functional programming concepts and a model that affords it several advantages. Thankfully, the basic features and concepts have already been <a href="http://nixos.org/nix/">well</a> <a href="https://www.domenkozar.com/2014/03/11/why-puppet-chef-ansible-arent-good-enough-and-we-can-do-better/">covered</a> <a href="http://lethalman.blogspot.com/2014/07/nix-pill-1-why-you-should-give-it-try.html">elsewhere</a>.</p>
<p>I’m hoping that if you’ve made it this far, you already have some interest in it. If you’re skeptical about getting started right away, I recommend spending some time reading the above links to get a better sense of what Nix offers.</p>
<p>The “two days” recommendation is a suggestion for pacing so you don’t need to dive too deep down the Nix rabbit hole on the first day you try it out, but the actual steps we’ll go over could be run through much faster if desired.</p>
<h4 id="day-1-installation">Day 1: Installation</h4>
<p>Good news! It’s not going to take a day to install Nix (the quickstart install takes a few minutes at most), but we’ll go at a slower pace here so you can spend time learning the basic tools and some of the concepts too.</p>
<p>One of Nix’s defining features is the packages it builds will not depend on global install directories (<code>/bin</code>, <code>/usr</code>, <code>/lib</code>, etc), and the packages will be placed in the <code>/nix/store</code>. This makes it easy to use alongside existing package managers, because it will not influence or depend on your globally installed packages.<sup><a href="#footnote1">1</a></sup></p>
<p>For Linux or Mac OS X users, the official installation instructions are available on <a href="http://nixos.org/nix/" class="uri">http://nixos.org/nix/</a>. Here’s the short version as of January 2015:</p>
<pre class="console"><code>$ curl https://nixos.org/nix/install | sh
$ source ~/.nix-profile/etc/profile.d/nix.sh</code></pre>
<p>The first step will set up the <code>/nix/store</code> and install utilities like <code>nix-env</code> that you will use to manage Nix. If you’re concerned about relying on <code>curl</code> for the install you can read the <a href="http://nixos.org/nix/manual/#chap-installation">installation chapter</a> of the manual for further options.</p>
<p>The second step will source a shell script that will export your <code>$NIX_PATH</code> and modify your user’s <code>$PATH</code> so it can find utilities installed by Nix.</p>
<p>To search for packages, you can use <code>nix-env -q</code> and grep to filter the results. Here’s a quick example that will run a query (flag <code>q</code>) for packages available (flag <code>a</code>) on your platform, including the package’s attribute path (flag <code>P</code>). We’ll grep for the <code>cowsay</code> package, because who wouldn’t want <code>cowsay</code>:</p>
<pre class="console"><code>nix-env -qaP | grep -i cowsay
nixpkgs.cowsay                    cowsay-3.03</code></pre>
<p>Now you can either install by name (from the right hand column in our search results):</p>
<pre class="console"><code>nix-env -i cowsay-3.03</code></pre>
<p>Or by attribute path (as shown in the left hand column of our earlier search results). Note that we have to add the flag <code>A</code> to indicate we’re installing by attribute:</p>
<pre class="console"><code>nix-env -iA nixpkgs.cowsay</code></pre>
<p>Congratulations! You’ve installed your first package with Nix. If you aren’t sure what to do next, try out <code>nix-env -i nix-repl</code>. This will install the <code>nix-repl</code> utility that will let you write Nix expressions and interact with Nix in a shell. Examples and getting started instructions for <code>nix-repl</code> are available <a href="https://github.com/edolstra/nix-repl">here</a>.</p>
<p>You’re now free to install packages without breaking system packages, without obscure failures due to changed or missing global dependencies<sup><a href="#footnote2">2</a></sup>, and without dependency hell.<sup><a href="#footnote3">3</a></sup></p>
<h4 id="day-2-myenvfun">Day 2: myEnvFun</h4>
<p>There are a lot of Nix features that have improved my development workflow, and it’s very hard to pick just one to cover here. But time and time again, one of the most useful for me has been <code>myEnvFun</code>, which also shows how we can go beyond typical definitions of “package” to solve common development problems.</p>
<blockquote>
<p>Note: the “Fun” in <code>myEnvFun</code> is for functional. The Nix and NixOS communities make no claims or guarantees of enjoyment derived from using it.</p>
</blockquote>
<p>One of the (many) complications in software development is identifying and isolating all of the tools you need to work on a particular project. This isn’t always the case: I usually want <code>tmux</code> and my favorite editor available regardless of what project I’m working on. But other times you might have projects that require conflicting versions of software, like two or more haskell projects using two or more versions of the compiler <code>ghc</code>.</p>
<p>What we’d like to do is define and codify these different environments as package sets containing all the tools we need, preferably giving us some quick and easy way to switch between them.</p>
<p>We can do this through a special file <code>~/.nixpkgs/config.nix</code>, which may contain package overrides you’ve specified for your user. Here’s how you can create the file for the first time if you don’t already have one:</p>
<pre class="console"><code>mkdir -p ~/.nixpkgs
touch ~/.nixpkgs/config.nix</code></pre>
<p>Next we’ll use the built-in <code>packageOverrides</code> to define one or more new <code>myEnvFun</code> environments. The below example is written in the Nix language. We won’t explain all of the syntax here, but we’re defining two new packages that can be installed; one that will allow us to use <code>ghc</code> at version 7.6, and one at 8.3.</p>
<pre class="sourceCode perl"><code class="sourceCode perl"><span class="co"># ~/.nixpkgs/config.nix</span>
{
  <span class="co"># ~/.nixpkgs/config.nix lets us override the Nix package set</span>
  <span class="co"># using packageOverrides. In this case we extend it by adding</span>
  <span class="co"># new packages using myEnvFun.</span>
  packageOverrides = pkgs : with pkgs; {
        ghc76 = pkgs.myEnvFun {
	  name = <span class="kw">&quot;</span><span class="st">ghc76</span><span class="kw">&quot;</span>;
	  buildInputs = [ ghc.ghc763 ];
	};
        ghc78 = pkgs.myEnvFun {
	  name = <span class="kw">&quot;</span><span class="st">ghc78</span><span class="kw">&quot;</span>;
	  buildInputs = [ ghc.ghc783 ];
	};

   };
}</code></pre>
<p>Here’s how we can install the environments from our snippet above:</p>
<pre class="console"><code># nix-env will look for ~/.nixpkgs/config.nix and, if it exists, use the package
# overrides you&#39;ve defined there
nix-env -i env-ghc76
nix-env -i env-ghc78</code></pre>
<p>Once they’re installed, there’s no need to reinstall them unless you uninstall them or make a change (for instance, maybe adding a new package to <code>buildInputs</code>).</p>
<p>Let’s load up our new <code>ghc76</code> environment first:</p>
<pre><code>$ load-env-ghc76
env-ghc76 loaded

ghc76:[vagrant@nixos:~]$ ghci
GHCi, version 7.6.3: http://www.haskell.org/ghc/  :? for help
Loading package ghc-prim ... linking ... done.
Loading package integer-gmp ... linking ... done.
Loading package base ... linking ... done.
Prelude&gt;
Leaving GHCi.

ghc76:[vagrant@nixos:~]$ exit</code></pre>
<p>When you’re done you can exit back to your normal shell, which won’t have <code>ghci</code> installed (unless you specifically installed it for your user). Want to try out the environment with <code>ghc 7.8.3</code> instead?</p>
<pre class="console"><code>$ load-env-ghc78
env-ghc78 loaded

ghc78:[vagrant@nixos:~]$ ghci
GHCi, version 7.8.3: http://www.haskell.org/ghc/  :? for help
Loading package ghc-prim ... linking ... done.
Loading package integer-gmp ... linking ... done.
Loading package base ... linking ... done.
Prelude&gt;
Leaving GHCi.

ghc78:[vagrant@nixos:~]$ exit</code></pre>
<p>In practice, taking a few minutes to define these package sets has proven to be a fairly straightforward and reliable to keep project dependencies isolated. Perhaps best of all, you can keep your <code>config.nix</code> in a repo somewhere and use it on any machine where you need to reproduce those environments.</p>
<p>Want to start writing your own? Here are some tips:</p>
<ul>
<li>myEnvFun prepends “env-” to the “name” you give your environment</li>
<li>ex. if you create a myEnvFun with name = “dev”, you can install with <code>nix-env -i env-dev</code></li>
<li>Nix lists are space delimited. want git and tmux? <code>buildInputs = [ git tmux ]</code>;</li>
<li>installing the env adds a script to your path called load-env-name</li>
<li>for our dev example we can now call <code>load-env-dev</code> to load the environment</li>
</ul>
<p>Want to see it in action? Here’s a fancy <a href="/images/myenvfun.gif">animated gif</a> demonstrating the environment switching.</p>
<h4 id="learning-more">Learning more</h4>
<p>The Nix/NixOS community is growing, and they’ve been developing solutions and novel approaches to a great many packaging and deployment problems. There’s Nix the language (in order to write your own packages you should learn how to write Nix expressions), NixOS the Linux distribution (which lets you write NixOS modules, providing a config management-like layer), and a whole lot more.</p>
<p>Here are some resources for getting started:</p>
<ul>
<li><a href="http://nixos.org/nix/manual/">Nix Manual</a></li>
<li><a href="http://nixos.org/docs/papers.html">Nix Papers</a></li>
<li><a href="https://nixos.org/wiki/Main_Page">Nix Wiki</a></li>
<li><a href="http://lethalman.blogspot.com/2014/07/nix-pill-1-why-you-should-give-it-try.html">Nix pills</a></li>
<li><a href="https://twitter.com/NixOsTips">NixOS Tips (Twitter)</a></li>
</ul>
<hr />
<p><sub><a id="footnote1">1.</a>Note that this only applies to where software is installed. If you install <code>cowsay</code> via <code>apt-get</code> and <code>nix-env</code> then your user’s <code>$PATH</code> will determine which one is used.</sub></p>
<p><sub><a id="footnote2">2.</a>Unless you’re on OS X, where builds still require some globals that may change or cause breakage when upgrading to newer versions of OS X. There’s a ##nix-darwin channel on freenode working to address this if you want to contribute.</sub></p>
<p><sub><a id="footnote3">3.</a>If you’re using the Nix <em>unstable</em> channels there are other kinds of build failures you may encounter, like unintentional backwards incompatibilities in upgraded packages (ex. foo only works because of a bug in bar, bar is upgraded with bug fix, foo stops building until the package maintainers can address it)</sub></p>]]></summary>
</entry>
<entry>
    <title>White paper: Compile Time TDD Coverage with Idris</title>
    <link href="http://chromaticleaves.com/posts/idris-and-dependent-types.html" />
    <id>http://chromaticleaves.com/posts/idris-and-dependent-types.html</id>
    <published>2014-05-03T00:00:00Z</published>
    <updated>2014-05-03T00:00:00Z</updated>
    <summary type="html"><![CDATA[<p>Recent research-based advances in computering have shown that people want more TDD and expend most of their time coming up with components of code called “units” so that they can test them for quality assurance.</p>
<p>But guess what?</p>
<blockquote>
<p><em>They’re doing it. Wrong.</em></p>
</blockquote>
<p>A crack team of compiler inventors has been in stealth mode for literally months preparing a new way to TDD without having to make up units all the time.</p>
<p>The Idris compiler (industry buzzword for a linting tool) is so advanced you can:</p>
<ul>
<li>check all the dynamic types just once at compile time</li>
<li>evaluate all possible test cases before the code even runs</li>
<li>help the compiler write tests before you even write the code</li>
</ul>
<h4 id="how-the-breakthrough-works">How the breakthrough works</h4>
<p>Have you ever written code to access an array index and you just <em>knew</em> it wouldn’t fail, but you still had to account for that possibility? In the early days of computing (circa 2009 when node.js was created) everyone tried to make up for this uncertainty by writing unit tests.</p>
<p>But the Idris compiler doesn’t mess around: you can just say it won’t fail, <em>so it won’t</em>.</p>
<p>This is made possible through the magic of dependent types, a type of type even more dynamic than dynamic types, because they let types depend on values. Types are no longer mindless declarations like Int or String or Whatever in dependent typing. You can have particular values, non-empty containers, and more complex relationships all inside the type signature.</p>
<p>Behold, examples:</p>
<pre><code>-- tell the compiler that concatenating vectors of size n and m makes a new
-- vector of size n + m. The compiler checks the cases for you!
concatVectors : Vect n a -&gt; Vect m a -&gt; Vect (n + m) a

-- repeat values of some type &quot;a&quot; `n` many times in a vector. The size of the
-- returned vector is guaranteed to be the size of `n`
replicate : (n: Nat) -&gt; a -&gt; Vect n a

-- no out of bounds access here! you can only look up an index in a vector of
-- size `n` if you call it with a number between 0 and `n`
index : Fin n -&gt; Vect n a -&gt; a</code></pre>
<p>Best of all: the dynamic checks only happen once before your program ever runs!</p>
<p>This works through a process known as mathematical proofing, where the compiler knows enough about your code to ensure coverage instead of just guessing at it with a handful of tests. If you try to express something the compiler doesn’t know how to check already, you can switch to an interactive theorem proving mode, letting you dynamically solve problems before the code ever runs.</p>
<p>Let’s recap. Idris and dependent types make it possible to:</p>
<ol style="list-style-type: decimal">
<li>Write type signatures that depend on values</li>
<li>Enforce those relationships at compile time instead of runtime</li>
<li>Write proofs to show you can only create/modify data in ways that preserve those relationships</li>
</ol>
<h4 id="interactive-proving">Interactive proving</h4>
<p>Imagine you’re building a next gen full stack web app where users can earn and redeem special tokens whenever they recommend your app to a friend. You want to make a stack-like structure that lets you track the number of recommendations and the number of redemptions, but always ensure the number of redemptions is less than or equal to the number of recommendations (in Idris, the type for a relation <code>n &lt;= m</code> is <code>LTE n m</code>).</p>
<p>First you define some data:</p>
<pre><code>data User = MkUser String

data Redeem = MkRedeem Int

data Earn = Recommend User

Action : Type
Action = Either Redeem Earn

data History : Type where
  MkHist :  (user     : User)               -&gt;
            (redeemed : Nat)                -&gt;
            (offset   : Nat)                -&gt;
            (earned   : Nat)                -&gt;
            LTE (redeemed + offset) earned  -&gt;
            Vect (redeemed + earned) Action -&gt;
            History
</code></pre>
<p>We know that our users can always recommend the app to friends, so let’s write a function to update their history when they make a recommendation:</p>
<pre><code>recommendApp : History -&gt; User -&gt; History
recommendApp (MkHist u r o e p v) friend =
  MkHist u r (S o) (S e) p v&#39;
    where a  : Action
          a  = Right $ Recommend friend
          v&#39; : Vect (r + (S e)) Action
          v&#39; = rewrite (sym $ plusSuccRightSucc r e) in a :: v</code></pre>
<p>Anytime you see something of type <code>Nat</code> (a natural number, or a whole number greater than or equal to 0), you can take the successor of that number with <code>S</code>. For any natural number <code>n</code>, <code>S n</code> is equivalent to <code>n + 1</code>.</p>
<p>But when you run this, Idris finds an issue!</p>
<pre><code>Can&#39;t unify
        LTE (plus r o) e
with
        LTE (plus r (S o)) (S e)

Specifically:
        Can&#39;t unify
                e
        with
                S e</code></pre>
<p>It’s telling us that having proved <code>(r + o) &lt;= e</code> isn’t the same as proving <code>(r + o + 1) &lt;= e + 1</code>. Notice how Idris came up with this test all on its own even though we didn’t write any units!</p>
<p>But if we have a valid <code>LTE</code> relationsip then it’s pretty clear you can add one to each side and show the relationship holds.</p>
<p>This is where dynamic testing comes in. Except instead of writing a bunch of unit tests in a separate file somewhere you can just put a variable with a question mark right in your code to show we have no idea what we’re doing. Idris calls variables prefixed with a question mark “metavariables”, and by convention we use <em>?wtf</em>, <em>?notagain</em>, or <em>?sendhelp</em>.</p>
<pre><code>recommendApp : History -&gt; User -&gt; History
recommendApp (MkHist u r o e p v) friend =
  MkHist u r (S o) (S e) ?wtf v&#39;
    where a  : Action
          a  = Right $ Recommend friend
          v&#39; : Vect (r + (S e)) Action
          v&#39; = rewrite (sym $ plusSuccRightSucc r e) in a :: v
</code></pre>
<p>Now if you load this up in the Idris interpreter and enter the command <code>:p wtf</code> it will tell you what it is you’re trying to do, even if you were just making things up. We’ll also type <code>intros</code> to have it take all of the arguments as givens and show us what we’re solving for (the goal):</p>
<pre><code>-main.wtf&gt; intros
----------              Other goals:              ----------
{hole6},{hole5},{hole4},{hole3},{hole2},{hole1},{hole0}
----------              Assumptions:              ----------
 u : User
 r : Nat
 o : Nat
 e : Nat
 p : LTE (plus r o) e
 v : Vect (plus r e) (Either Redeem Earn)
 friend : User
----------                 Goal:                  ----------
{hole7} : LTE (plus r (S o)) (S e)</code></pre>
<p>If we know that <code>p = LTE (plus r o) e</code> is a given, one way to solve the goal is to show that <code>LTE (plus r (S o)) (S e)</code> can be rewritten as <code>p</code>. But it’s kind of hard to do that without first breaking down <code>plus r (S o)</code>, so let’s rewrite it in the form <code>S (r + o)</code> instead. There’s a built-in proof called <code>plusSuccRightSucc</code> that lets us do just that, so we’ll use the <code>rewrite</code> tactic:</p>
<pre><code>-main.wtf&gt; rewrite (plusSuccRightSucc r o)
----------              Other goals:              ----------
{hole7},{hole6},{hole5},{hole4},{hole3},{hole2},{hole1},{hole0}
----------              Assumptions:              ----------
 u : User
 r : Nat
 o : Nat
 e : Nat
 p : LTE (plus r o) e
 v : Vect (plus r e) (Either Redeem Earn)
 friend : User
----------                 Goal:                  ----------
{hole8} : LTE (S (plus r o)) (S e)</code></pre>
<p>Notice how the goal has been updated for us based on the rewrite.</p>
<p>Now if only we had a way to prove that <code>LTE n m</code> implies <code>LTE (S n) (S m)</code> we could solve for this. Good news! The very definition of <code>LTE</code> contains a constructor <code>lteSucc</code> that proves just this. We’ll use the <code>mrefine</code> tactic to rewrite the relationship for us (unlike <code>rewrite</code>, <code>mrefine</code> will use pattern matching so we don’t need to supply the variables explicitly):</p>
<pre><code>-main.wtf&gt; mrefine lteSucc

----------              Assumptions:              ----------
 u : User
 r : Nat
 o : Nat
 e : Nat
 p : LTE (plus r o) e
 v : Vect (plus r e) (Either Redeem Earn)
 friend : User
----------                 Goal:                  ----------
{__pi_arg516} : LTE (plus r o) e</code></pre>
<p>If the goal you’re solving for is in the same form as one of the assumptions, you can use the <code>trivial</code> tactic to complete the proof, and <code>qed</code> to see the results:</p>
<pre><code>-main.wtf&gt; trivial
wtf: No more goals.
-main.wtf&gt; qed
Proof completed!
main.wtf = proof
  intros
  rewrite (plusSuccRightSucc r o)
  mrefine lteSucc
  trivial</code></pre>
<p>We need this proof in our source file, but having to copy and paste is the kind of thing we did in the early 2010’s, and that doesn’t cut it anymore. After entering <code>qed</code> for a solved proof, you can use <code>:addproof</code> to have it automatically appended to your source file.</p>
<h4 id="conditional-proofs">Conditional proofs</h4>
<p>So far so good! But we said users can only redeem tokens if they have made enough recommendations to other users, and that’s something we can only know at runtime. <a href="http://en.wikipedia.org/wiki/Ivor_the_Engine#Idris_the_Dragon">Idris</a> might be magic, but even Idris can’t predict the future.</p>
<p>We might first think to write a function with type <code>History -&gt; Redeem -&gt; History</code>, but it’s impossible to redeem a token if a user doesn’t have enough recommendations, and those values are only known at runtime. So let’s try <code>History -&gt; Redeem -&gt; Maybe History</code> instead, and it’ll look a little something like:</p>
<pre><code>redeemToken : History -&gt; Redeem -&gt; Maybe History
redeemToken (MkHist _ _ Z     _ _ _) _     = Nothing
redeemToken (MkHist u r (S o) e p v) token =
  Just $ MkHist u (S r) o e ?redeemPrf (Left token :: v)</code></pre>
<p>Remember that weird looking offset value we carry around in the <code>History</code> type? It’s time to put it to use! If we didn’t have an offset we’d only ever know that we had a number of redeemed tokens less than or equal to the number of earned tokens, and <code>r &lt;= e</code> isn’t enough information to prove <code>r + 1 &lt;= e</code>.</p>
<p>The offset lets us rewrite everything as <code>r + o &lt;= e</code>. If <code>o</code> is 0 (the natural number <code>Z</code>) then the problem reduces to <code>r &lt;= e</code> and can’t be solved. But if <code>o</code> is greater than 0 then we can always rewrite <code>r + (o + 1)</code> as <code>(r + 1) + o</code>. This lets us increase the count for redeemed tokens and the size of our history vector, while always enforcing we’ll never have more redeemed tokens than earned tokens.</p>
<p>Writing the <code>?redeemPrf</code> is a fun exercise, or you can see a full, working example of the code in this <a href="https://gist.github.com/ericrasmussen/8173956196158e39c716">gist</a>.</p>
<h4 id="not-convinced">Not convinced?</h4>
<p>Writing correct software and only having to check things once means efficiency, and efficiency means <em>success</em>. And money. Mostly money.</p>
<p>The cost of efficiency is having to know what you want to write before you write it, and our findings have shown this is a useful property in software development despite conventional wisdom.</p>
<p>In the preceding example we showed that you can make a data structure correct by construction: if you can’t show you’re doing it right, you can’t construct an instance of it. Imagine all the hours we just saved from writing TDD driven tests! Idris just let us interactively write one big test that only has to run once before your program runs, and all the test cases are covered there on out.</p>
<p>This might be a silly example, but imagine a world where crypto libraries can’t fail due to bounds checks.</p>
<p>Imagine it.</p>
<h4 id="sign-me-up">Sign me up!</h4>
<p>Get started with this amazing new technology by installing the <a href="http://www.haskell.org/platform/">Haskell Platform</a> (if you don’t have GHC and cabal-install on your system already), and running the commands:</p>
<pre class="console"><code>cabal update
cabal install idris</code></pre>
<p>You can read more detailed instructions for different operating systems on the <a href="https://github.com/idris-lang/Idris-dev/wiki">Idris wiki</a>.</p>
<p>Now you can work through the tutorial on the <a href="http://www.idris-lang.org/documentation/">docs</a> page to learn more!</p>]]></summary>
</entry>
<entry>
    <title>Adventures in Hoogling</title>
    <link href="http://chromaticleaves.com/posts/how-to-hoogle.html" />
    <id>http://chromaticleaves.com/posts/how-to-hoogle.html</id>
    <published>2014-03-31T00:00:00Z</published>
    <updated>2014-03-31T00:00:00Z</updated>
    <summary type="html"><![CDATA[<p><a href="http://www.haskell.org/hoogle/">Hoogle</a> is the de facto tool for searching types and documentation in Haskell libraries, and it’s simple to install and use at the command-line or in the browser. At least, until you decide you’d like a straightforward way to create your own Hoogle database for all libraries installed in a cabal sandbox. Which, incidentally, was the original motivation for this post.</p>
<p>Things didn’t go quite as smoothly as expected.</p>
<p>But before we get to that…</p>
<h4 id="how-to-hoogle-the-easy-way">How to Hoogle: the easy way</h4>
<p>Hoogle is easy to <code>cabal install</code> and get started with locally. For many use cases, all you need is to install it and populate it with data using either:</p>
<pre class="console"><code># creates databases for many common libs
hoogle data</code></pre>
<p>Or:</p>
<pre class="console"><code># creates databases for a whole lot of libs
hoogle data all</code></pre>
<p>If you’re using sandboxes, you may have to specify the location of Hoogle with <code>.cabal-sandbox/bin/hoogle data</code> (even though I had that instance of Hoogle higher up on my search path, I ran into a quirk in my environment where it couldn’t find the cabal dirs it needed if I didn’t specify the relative path).</p>
<p>From there you can start searching at the command-line:</p>
<pre class="console"><code>$ hoogle &quot;(a -&gt; b) -&gt; [a] -&gt; [b]&quot;
Prelude map :: (a -&gt; b) -&gt; [a] -&gt; [b]</code></pre>
<p>Or you can run <code>hoogle server -p 1234</code> to serve the web version on localhost at port 1234 (or port of your choice).</p>
<h4 id="how-to-hoogle-the-ghci-way">How to Hoogle: the GHCi way</h4>
<p>GHCi is more than just a Haskell interpreter: you can also use it to issue shell commands. If you haven’t done this before, try it out! You can prefix shell commands with <code>:!</code>. For instance, <code>:!pwd</code> will print the current working directory in GHCi.</p>
<p>This means you can also call Hoogle from within GHCi, assuming it’s on your path:</p>
<pre class="console"><code>Prelude&gt; :! hoogle &quot;[a] -&gt; Int&quot;
Prelude length :: [a] -&gt; Int</code></pre>
<p>This works, but it’s a little clunky to have to quote the search term. There’s a <a href="http://www.haskell.org/haskellwiki/Hoogle">Hoogle entry</a> on the HaskellWiki with a tip for getting around this. You can add this to your <code>.ghci</code> file (in your cabal sandbox folder, project folder, or as described <a href="http://www.haskell.org/ghc/docs/7.4.2/html/users_guide/ghci-dot-files.html">here</a>):</p>
<pre class="console"><code># .ghci
:def hoogle \x -&gt; return $ &quot;:!hoogle \&quot;&quot;        ++ x ++ &quot;\&quot;&quot;
:def doc    \x -&gt; return $ &quot;:!hoogle --info \&quot;&quot; ++ x ++ &quot;\&quot;&quot;</code></pre>
<p>Now you can call them handily within GHCi:</p>
<pre class="console"><code>*Main&gt; :hoogle head
Prelude head :: [a] -&gt; a
Data.List head :: [a] -&gt; a
...
*Main&gt; :doc head
Prelude head :: [a] -&gt; a

Extract the first element of a list, which must be non-empty.

From package base
head :: [a] -&gt; a</code></pre>
<p>Especially when you’re first learning a library, it can also be helpful to limit search results to that library. For instance, if you want to find all of the Hakyll functions that make use of <code>Compiler</code>, use <code>+hakyll</code> to search only that module:</p>
<pre><code>Prelude&gt; :hoogle +hakyll Compiler
Hakyll.Core.Compiler data Compiler a
Hakyll.Core.Compiler module Hakyll.Core.Compiler
...</code></pre>
<h4 id="how-to-hoogle-your-own-way">How to Hoogle: your own way</h4>
<p>The next step in my journey for making the most of Hoogle was finding a way to search my current project while working on it. The high level process for creating a Hoogle database is to use <code>haddock</code> (commonly via <code>cabal haddock</code>) to generate a text file suitable for consumption via Hoogle, convert the text file to a <code>.hoo</code> Hoogle database, and combine it with an existing Hoogle database.</p>
<p>Let’s break it down. First, cabal has a haddock command that is very convenient to use when working with sandboxes. The <code>--hoogle</code> flag will generate a text file database, and <code>--all</code> says to generate one for everything in the package in the current working directory (you could also specify any of <code>--executables</code>, <code>--tests</code>, of <code>--benchmarks</code>). If you’re writing a library, you don’t need to specify <code>--all</code>, but it’s useful when you want to be able to search everything in your current project:</p>
<pre class="console"><code>cabal haddock --hoogle --all</code></pre>
<p>Now we can use Hoogle’s <code>convert</code> command to create a <code>.hoo</code> file from the text database. The text file should be somewhere in the current working directory under dist/doc/html:</p>
<pre class="console"><code>hoogle convert dist/doc/html/path/to/your/package/docs.txt</code></pre>
<p>Lastly you can combine it with the <code>default.hoo</code> database (typically somewhere in your global, user, or sandbox <code>cabal/share</code> folder):</p>
<pre class="console"><code>hoogle combine default.hoo dist/doc/html/path/to/your/package/docs.hoo</code></pre>
<h3 id="how-to-hoogle-the-hard-way">How to Hoogle: the hard way</h3>
<p>My original goal was making it easy to generate a database with all the packages in a cabal sandbox. It turned out to be challenging for a few reasons, one of which is that cabal installing packages (sandbox or no) doesn’t create the <code>.txt</code> or <code>.hoo</code> files needed by Hoogle. Some quick research shows that adding this type of functionality isn’t a new <a href="https://github.com/haskell/cabal/issues/395">issue</a>.</p>
<p>This is by no means a trivial addition to <code>cabal</code>, but it’s arguably the cleanest solution to the problem.</p>
<p>However, if you want a quick hack in the meantime, the basic idea is making use of:</p>
<ol>
<li><code>ghc-pkg</code> to get a list of sandboxed packages</li>
<li><code>cabal get</code> to fetch each package’s source code</li>
<li><code>cabal haddock</code> to generate <code>.txt</code> databases for each</li>
<li><code>hoogle convert</code> to create the <code>.hoo</code> databases</li>
<li><code>hoogle combine</code> to merge the databases into a single <code>default.hoo</code></li>
</ol>
<p>This process isn’t perfect, but it’d look something like this:</p>
<pre class="console"><code># get an easy to parse list of packages pinned at their installed versions
ghc-pkg list --package-db=&quot;.cabal-sandbox/&lt;architecture&gt;-ghc-&lt;version&gt;-packages.conf.d/&quot; --simple-output
# then for each package:
cabal get &lt;package&gt; -d &lt;destination directory&gt;
cabal haddock --hoogle --haddock-options=&#39;&lt;package&gt;/Setup.hs&#39;
cabal convert &lt;package&gt;/dist/doc/html/&lt;package&gt;.txt
cabal combine path/to/default.hoo &lt;package&gt;/dist/doc/html/&lt;package&gt;.hoo</code></pre>
<p>This approach is problematic because not all installed packages are libraries (in which case <code>cabal haddock</code> will generate errors and not exit cleanly), the location and name of the setup file may vary, and having to <code>cabal get</code> a lot of packages can be an expensive and time consuming operation.</p>
<p>Overall I’ve found it much easier to start with <code>hoogle data all</code> and then add my own package, rather than try to automate database creation for sandboxed libraries. You get greater search capabilities (sometimes with too many results, but it’s easy to limit the search by module), and it doesn’t stop you from building your own databases as needed.</p>
<h4 id="references">References</h4>
<p>Some links I found indispensable in learning the various ways one can Hoogle:</p>
<ul>
<li><a href="https://github.com/ndmitchell/hoogle/blob/master/README.md">Hoogle manual</a></li>
<li><a href="http://neilmitchell.blogspot.com/2008/08/hoogle-database-generation.html">Neil Mitchell’s post on database generation</a></li>
<li><a href="http://www.haskell.org/haskellwiki/Hoogle">Hoogle wiki entry</a></li>
<li><a href="http://www.haskell.org/hoogle/">Online Hoogle search</a></li>
</ul>]]></summary>
</entry>
<entry>
    <title>The Fool's Choice: A Tale of Two Types</title>
    <link href="http://chromaticleaves.com/posts/type-systems-fools-choice.html" />
    <id>http://chromaticleaves.com/posts/type-systems-fools-choice.html</id>
    <published>2014-02-28T00:00:00Z</published>
    <updated>2014-02-28T00:00:00Z</updated>
    <summary type="html"><![CDATA[<p>Imagine for a moment that programmers were constantly baited with snake oil: paradigm shifts this way! Agile scrum productivity boost ahead! An IDE that will astound you! A framework that solves the internets in only three lines of code!</p>
<p>Oh, that’s right. We don’t have to imagine.</p>
<p>But now imagine that, among all the noise, all the tools and frameworks created for specialized use cases but recommended for all, lies something useful. Something with the potential to change how you describe relationships in code so you can make it correct by construction, not just assumed correct by testing.</p>
<h4 id="types-not-made-of-oil-or-snakes">Types: not made of oil or snakes</h4>
<p>A powerful way to achieve this is by using a rich type system, like those in Haskell, Scala, and OCaml.</p>
<p>It’s important to understand that these languages <em>will have issues</em>. No programming language is the best language. None will be the language to end all languages. The more you spend time using one of them for more and more complicated use cases, the more likely you are to run into different types of limitations.</p>
<p>But that’s OK, because this post isn’t about those languages. It’s about leveraging type systems to write better code. For the few people who like to point out that these languages are experimental, or untested, or too academic, however, I’d like you to keep this in mind:</p>
<ul>
<li>Haskell, Scala, and OCaml are all used in mission critical production systems</li>
<li>They are proven to work just fine in “the real world”</li>
<li>Learning types will make you a better programmer even if you use untyped languages</li>
</ul>
<h4 id="choices">Choices</h4>
<p>There’s a group specializing in all kinds of leadership and skill building techniques that uses the term <a href="http://www.crucialskills.com/glossary/#q27">Fool’s Choice</a> to describe dilemmas where you see a binary choice (either/or) instead of a multitude of options.</p>
<p>When it comes to people not wanting static types, this is the line of reasoning I see:</p>
<ol style="list-style-type: decimal">
<li>Java has static types</li>
<li>In Java I have to name the type of every single thing exactly</li>
<li>This leads to a lot of boiiler plate</li>
<li>I don’t even test types anyway!</li>
<li>Thus I can either use static types or no types (python/perl/ruby)</li>
</ol>
<p>The options are sometimes seen as limited, cumbersome types or no types at all.</p>
<p>So if you do understand static types through the lens of Java, or C/C++, or similar languages, then I have a favor to ask. Imagine that everything you know about static types is wrong. Imagine that what you’ve learned about them has nothing to do with actual static types, but only the specific, broken implementations of them that most of us are exposed to.</p>
<p>Do that, and I can tell you what static types are really about.</p>
<h4 id="a-motivating-case">A motivating case</h4>
<p>It’s tempting to think of types as a way to declare the contents of a variable. If I say the variable foo is an integer, you know the variable foo is an integer. That might be helpful in some sense, but in dynamic languages you don’t need someone to tell you that “foo = 5” means foo is an integer. You’re not going to write tests asserting that foo is an integer, and indeed, you probably aren’t even going to think of it in those terms. You don’t need to, after all.</p>
<p>But that’s not very interesting. If you only see types as something that help you declare the obvious and prevent simple bugs that you can check by eye or make assertions about, of course you’ll see no need for them. And in that case, the productivity you get from writing in a language like python will absolutely trump that of Java.</p>
<p><em>Set yourself free from making meaningless declarations! Reduce the size of your code! Simplify refactoring!</em></p>
<p>So if we don’t spend our dynamic language time testing types, what <em>do</em> we test? Let’s say you write a library function in python that takes any iterator and writes the contents to file. In the true spirit of python, you don’t care what “type” of object someone passes in; anything that allows iteration is fine, and of course you’d never want to limit yourself to only iterating over integers, or strings, or whatever.</p>
<p>Now ask yourself: how do you make sure someone using your library calls your function with an iterable?</p>
<h4 id="types-to-describe-behaviors">Types to describe behaviors</h4>
<p>In the above example, it’s absolutely essential to your library’s functionality that someone only ever passes in an iterable, and you have no way of making sure they do that. If they pass in something that doesn’t allow iteration, everything explodes. You can decide to hope for the best (and when hope fails they’ll see a built-in exception that might be confusing), or explicitly check that they pass in an iterator and raise a more meaningful exception.</p>
<p>But if you want to make sure your program behaves as expected, you’ll need to test it against both iterators and non-iterators to ensure the behavior is correct.</p>
<p>What would be ideal here is a way to describe the behavior of your program at the type level. Not to declare an exacting, exhaustive list of types that your function accepts, but a whole <em>class</em> of types that can be used as iterators.</p>
<p>In Haskell, it’d look a little like this:</p>
<pre class="sourceCode haskell"><code class="sourceCode haskell"><span class="ot">writeLines ::</span> <span class="dt">Iterator</span> a <span class="ot">=&gt;</span> a <span class="ot">-&gt;</span> <span class="dt">WriteFileAction</span></code></pre>
<p>This reads as “we have a function named writeLines that takes an iterator of any arbitrary type a, and produces an action that writes to a file.”</p>
<p>This example is important: when you hear functional programming enthusiasts saying type systems reduce testing, this is the kind of thing we mean. You’ve just described a behavior that prevents anyone from trying to write to file with your library unless they pass in an actual iterator. It’s correct by construction: try to call it with a non-iterator and it won’t compile. You don’t need extra logic or tests to account for that possibility.</p>
<h4 id="a-hidden-benefit">A hidden benefit</h4>
<p>There’s a big scary word we functional folk like to pass around called parametricity. It has a very specific meaning and is covered in <a href="http://www.haskell.org/haskellwiki/Research_papers/Type_systems#Parametricity">many research papers</a>, but for our introductory purposes here we can say it’s something that helps you reason about what a function can or can’t do by understanding how its properties hold true for more than one type.</p>
<p>Let’s look at our example one more time:</p>
<pre class="sourceCode haskell"><code class="sourceCode haskell"><span class="ot">writeLines ::</span> <span class="dt">Iterator</span> a <span class="ot">=&gt;</span> a <span class="ot">-&gt;</span> <span class="dt">WriteFileAction</span></code></pre>
<p>The syntax might be unfamiliar, but the definition tells us that we can ensure the function is only called with an iterator. We don’t care what that iterator is.</p>
<p>But this tells us something else, too: if we don’t know what the iterator is, how it iterates, or what it contains, this function can’t do anything <em>except</em> iterate.</p>
<p>When your goal is reasoning about code and understanding it, it’s not possible to understate how huge this subtle implication really is. If we write a function that holds true for all iterators, we can’t do any non-iterator things to it!</p>
<p>For instance, if someone calls it with a string iterator, we can’t manipulate the strings. How could we? If we wrote something specific to strings, the type would be Iterator String -&gt; WriteFileAction.</p>
<p>This gives us an unprecedented level of safety by ensuring the function will only be able to make use of the iterator interface. When you are refactoring a large program this makes it very easy to pull out sections of code and replace them, because you know exactly what the code could or couldn’t do.</p>
<p>Compare that to code that can do anything at anytime like raise exceptions or manipulate shared state. I’ve even seen dynamic code that would iterate over collections, check if the contents were a particular “type”, like a string, and tag something on to them. When those special cases can occur anywhere in an untyped language, you always need to be on guard for them.</p>
<h4 id="taking-the-leap-not-literally">Taking the leap (not literally)</h4>
<p>When we write code, especially code any other human (including your future self) will need at some undetermined future point in time, we want some way to tell that human how the code works.</p>
<p>If you have a rich type system, you’re halfway there already. Docs get out of date, test specifications are ill-specified, but types are forever. You get the types right or your program doesn’t compile. Want to write less tests? Write more types. You only need tests to the extent that you don’t have types.</p>
<p>And the hidden benefit to adopting this mentality (thinking in terms of correct by construction) is it forces you to consider those same cases in untyped code. It makes you all too aware of how quickly a piece of untyped code can fail if someone passes in objects that don’t fulfill some expected interface or behavior.</p>
<p>If you start thinking in terms of the behaviors you want to describe and enforce, it quickly gets you in the right state of mind for asking what happens when that behavior can’t be enforced. You can use that wariness to convey to your users how it should work, you can state your expectations in the API and narrative docs, and you can convey what will happen when that expectation isn’t met (an exception that gets raised, a function that returns some none or null type, etc).</p>
<p>So my challenge to you is this: if you have not spent an extensive amount of time working with a rich, expressive type system, spend some time <a href="http://learnyouahaskell.com/">learning you a Haskell</a>. Learn it for fun, learn it for something new, learn it to expand your mind, learn it for The Real World. Whatever works best for you. But make an effort to understand just how expressive you can be in writing code and how you can cut down on tests with nicer types.</p>]]></summary>
</entry>
<entry>
    <title>Arbitrary Fun: Generating User Profiles with QuickCheck</title>
    <link href="http://chromaticleaves.com/posts/generate-user-data-quickcheck.html" />
    <id>http://chromaticleaves.com/posts/generate-user-data-quickcheck.html</id>
    <published>2014-01-31T00:00:00Z</published>
    <updated>2014-01-31T00:00:00Z</updated>
    <summary type="html"><![CDATA[<p>QuickCheck is a popular property-based testing library for Haskell, and I recommend checking out the HaskellWiki’s <a href="http://www.haskell.org/haskellwiki/Introduction_to_QuickCheck2">Introduction to QuickCheck</a> if you’ve never used it.</p>
<p>But QuickCheck does more than help us write tests: it offers an efficient, rich API for randomly generating data. We’re going to show how you can generate a CSV file with potentially millions of fake user records. The main use case is populating a database with loads of data for interactive testing, but this method is also useful for testing outside programs and bulk data jobs.</p>
<p>This post is written in literate Haskell, so let’s get our obligatory top-level imports out of the way before we get too far along:</p>
<pre class="sourceCode literate literatehaskell"><code class="sourceCode literatehaskell"><span class="ot">&gt;</span> <span class="ot">{-# LANGUAGE OverloadedStrings #-}</span>
<span class="ot">&gt;</span> 
<span class="ot">&gt;</span> <span class="kw">import           </span><span class="dt">Data.Time</span>
<span class="ot">&gt;</span> <span class="kw">import           </span><span class="dt">Data.Char</span> (chr)
<span class="ot">&gt;</span> <span class="kw">import           </span><span class="dt">Test.QuickCheck</span>
<span class="ot">&gt;</span> <span class="kw">import           </span><span class="dt">Control.Applicative</span>
<span class="ot">&gt;</span> <span class="kw">import           </span><span class="dt">Data.Vector</span> (<span class="dt">Vector</span>, (!))
<span class="ot">&gt;</span> <span class="kw">import qualified</span> <span class="dt">Data.Vector</span> <span class="kw">as</span> <span class="dt">V</span>
<span class="ot">&gt;</span> <span class="kw">import           </span><span class="dt">Data.Text</span> (<span class="dt">Text</span>)
<span class="ot">&gt;</span> <span class="kw">import qualified</span> <span class="dt">Data.Text</span> <span class="kw">as</span> <span class="dt">T</span>
<span class="ot">&gt;</span> <span class="kw">import qualified</span> <span class="dt">Data.Text.IO</span> <span class="kw">as</span> <span class="dt">TIO</span>
<span class="ot">&gt;</span> <span class="kw">import           </span><span class="dt">System.Environment</span> (getArgs)
<span class="ot">&gt;</span> <span class="kw">import           </span><span class="dt">Text.Read</span> (readMaybe)</code></pre>
<h3>
Imaginary users
</h3>
<p>We’ll start with a basic user profile definition, similar to what you’ll find on many social media sites:</p>
<pre class="sourceCode literate literatehaskell"><code class="sourceCode literatehaskell"><span class="ot">&gt;</span> <span class="kw">data</span> <span class="dt">UserProfile</span> <span class="fu">=</span> <span class="dt">UserProfile</span> {
<span class="ot">&gt;     firstName ::</span> <span class="dt">Text</span>
<span class="ot">&gt;</span>   ,<span class="ot"> lastName  ::</span> <span class="dt">Text</span>
<span class="ot">&gt;</span>   ,<span class="ot"> email     ::</span> <span class="dt">Email</span>
<span class="ot">&gt;</span>   ,<span class="ot"> password  ::</span> <span class="dt">Text</span>
<span class="ot">&gt;</span>   ,<span class="ot"> gender    ::</span> <span class="dt">Gender</span>
<span class="ot">&gt;</span>   ,<span class="ot"> birthday  ::</span> <span class="dt">Birthday</span>
<span class="ot">&gt;</span>   } <span class="kw">deriving</span> <span class="dt">Show</span>
<span class="ot">&gt;</span> 
<span class="ot">&gt;</span> <span class="co">-- helper for rendering a UserProfile as text</span>
<span class="ot">&gt;</span> <span class="co">-- (passwords will be quoted, and generated without &quot;&quot; marks or control chars)</span>
<span class="ot">&gt; profileText ::</span> <span class="dt">UserProfile</span> <span class="ot">-&gt;</span> <span class="dt">Text</span>
<span class="ot">&gt;</span> profileText profile <span class="fu">=</span> T.intercalate <span class="st">&quot;,&quot;</span> [
<span class="ot">&gt;</span>     firstName profile
<span class="ot">&gt;</span>   , lastName  profile
<span class="ot">&gt;</span>   , emailToText   <span class="fu">$</span> email    profile
<span class="ot">&gt;</span>   , T.concat [<span class="st">&quot;\&quot;&quot;</span>, password profile, <span class="st">&quot;\&quot;&quot;</span>]
<span class="ot">&gt;</span>   , T.pack <span class="fu">.</span> show <span class="fu">$</span> gender   profile
<span class="ot">&gt;</span>   , T.pack <span class="fu">.</span> show <span class="fu">$</span> birthday profile
<span class="ot">&gt;</span>   ]</code></pre>
<p>Note: the use of a binary gender definition here is to emulate the type of profile I’ve tested against, but it’s also exclusionary and a poor UI decision (<a href="http://www.sarahdopp.com/blog/2010/designing-a-better-drop-down-menu-for-gender/">read this</a> for some alternatives and reasons not use it).</p>
<p>Next we’ll create our custom Email, Gender, and Birthday types:</p>
<pre class="sourceCode literate literatehaskell"><code class="sourceCode literatehaskell"><span class="ot">&gt;</span> <span class="kw">data</span> <span class="dt">Email</span> <span class="fu">=</span> <span class="dt">Email</span> {
<span class="ot">&gt;     local  ::</span> <span class="dt">Text</span>
<span class="ot">&gt;</span>   ,<span class="ot"> domain ::</span> <span class="dt">Text</span>
<span class="ot">&gt;</span>   } <span class="kw">deriving</span> <span class="dt">Show</span>
<span class="ot">&gt;</span> 
<span class="ot">&gt; emailToText ::</span> <span class="dt">Email</span> <span class="ot">-&gt;</span> <span class="dt">Text</span>
<span class="ot">&gt;</span> emailToText e <span class="fu">=</span> T.concat [local e, <span class="st">&quot;@&quot;</span>, domain e]
<span class="ot">&gt;</span> 
<span class="ot">&gt;</span> <span class="kw">data</span> <span class="dt">Gender</span> <span class="fu">=</span> <span class="dt">Female</span> <span class="fu">|</span> <span class="dt">Male</span>
<span class="ot">&gt;</span>   <span class="kw">deriving</span> <span class="dt">Show</span>
<span class="ot">&gt;</span> 
<span class="ot">&gt;</span> <span class="kw">data</span> <span class="dt">Birthday</span> <span class="fu">=</span> <span class="dt">Birthday</span> {
<span class="ot">&gt;     year  ::</span> <span class="dt">Integer</span>
<span class="ot">&gt;</span>   ,<span class="ot"> month ::</span> <span class="dt">Int</span>
<span class="ot">&gt;</span>   ,<span class="ot"> day   ::</span> <span class="dt">Int</span>
<span class="ot">&gt;</span>   }
<span class="ot">&gt;</span> 
<span class="ot">&gt;</span> <span class="co">-- display birthdays in the format YYYY-MM-DD</span>
<span class="ot">&gt;</span> <span class="kw">instance</span> <span class="dt">Show</span> <span class="dt">Birthday</span> <span class="kw">where</span>
<span class="ot">&gt;</span>   show bday <span class="fu">=</span> show <span class="fu">$</span> fromGregorian (year bday) (month bday) (day bday)</code></pre>
<h3>
Generating data bit by bit
</h3>
<p>QuickCheck has an <a href="http://hackage.haskell.org/package/QuickCheck-2.6/docs/Test-QuickCheck.html#g:7">Arbitrary</a> typeclass that you can use for defining how to randomly generate a piece of data for a given type. Arbitrary instances only require you to supply a definition of <em>arbitrary</em> (<code>Gen a</code>).</p>
<p>Here we’ll define a Gender instance using <em>elements</em> (<code>[a] -&gt; Gen a</code>):</p>
<pre class="sourceCode literate literatehaskell"><code class="sourceCode literatehaskell"><span class="ot">&gt;</span> <span class="kw">instance</span> <span class="dt">Arbitrary</span> <span class="dt">Gender</span> <span class="kw">where</span>
<span class="ot">&gt;</span>   arbitrary <span class="fu">=</span> elements [<span class="dt">Female</span>, <span class="dt">Male</span>]</code></pre>
<p>Now we’d like to do the same for birthdays. Using the Data.Time library, we can represent dates as modified Julian days. Here I’ve arbitrarily chosen to generate birthdays between day 25,000 (1927-04-30) and day 55,000 (2009-06-18) inclusive, along with a helper function for converting the integer day to a Birthday.</p>
<pre class="sourceCode literate literatehaskell"><code class="sourceCode literatehaskell"><span class="ot">&gt;</span> <span class="kw">instance</span> <span class="dt">Arbitrary</span> <span class="dt">Birthday</span> <span class="kw">where</span>
<span class="ot">&gt;</span>   arbitrary <span class="fu">=</span> birthdayFromInteger <span class="fu">&lt;$&gt;</span> choose (<span class="dv">25000</span>, <span class="dv">55000</span>)
<span class="ot">&gt;</span> 
<span class="ot">&gt; birthdayFromInteger ::</span> <span class="dt">Integer</span> <span class="ot">-&gt;</span> <span class="dt">Birthday</span>
<span class="ot">&gt;</span> birthdayFromInteger i <span class="fu">=</span> <span class="kw">let</span> (y, m, d) <span class="fu">=</span> toGregorian (<span class="dt">ModifiedJulianDay</span> i) <span class="kw">in</span>
<span class="ot">&gt;</span>   <span class="dt">Birthday</span> { year <span class="fu">=</span> y, month <span class="fu">=</span> m, day <span class="fu">=</span> d }</code></pre>
<p>QuickCheck makes the choice for us using <em>choose</em> (<code>Random a =&gt; (a, a) -&gt; Gen a</code>), and we use <em>fmap</em> (&lt;$&gt;) to apply our helper function of <code>Integer -&gt; Birthday</code>.</p>
<h3>
Beyond arbitrary
</h3>
<p>Next we’d like to generate passwords, but there’s a potential issue: we’ve defined names and passwords to all be of type Text. How can we define a single instance of Arbitrary Text to cover all of these cases?</p>
<p>There are several ways to approach this problem, and in a real application you could make a strong argument for creating new data types (or newtypes) for each of these fields. But in our example, the simplest answer is to not define an instance of Arbitrary for the name and field records. The <em>arbitrary</em> function is type <code>Gen a</code>, and we can write our own functions of this type without Arbitrary:</p>
<pre class="sourceCode literate literatehaskell"><code class="sourceCode literatehaskell"><span class="ot">&gt;</span> <span class="co">-- creates a text password of random length from the characters A-z, 0-9, and:</span>
<span class="ot">&gt;</span> <span class="co">--   #$%&amp;&#39;()*+,-./:;&lt;=&gt;?@[\]^_`{|}~</span>
<span class="ot">&gt; genPassword ::</span> <span class="dt">Gen</span> <span class="dt">Text</span>
<span class="ot">&gt;</span> genPassword <span class="fu">=</span> T.pack <span class="fu">&lt;$&gt;</span> listOf1 validChars
<span class="ot">&gt;</span>   <span class="kw">where</span> validChars <span class="fu">=</span> chr <span class="fu">&lt;$&gt;</span> choose (<span class="dv">35</span>, <span class="dv">126</span>)</code></pre>
<p>By design we won’t generate passwords containing quotation marks or other characters that would require escaping. This is done purely to keep this example short and make our job easier when we eventually print results in a minimal CSV format. If you find yourself writing a full-fledged program for generating CSV data, I recommend using <a href="http://hackage.haskell.org/package/cassava-0.1.0.1/docs/Data-Csv.html">cassava</a>.</p>
<h3>
Naming things
</h3>
<p>Any programmer will tell you that naming is hard. So let’s cheat: the US government offers lists of first and last names from <a href="https://www.census.gov/genealogy/www/data/1990surnames/names_files.html">1990 census data</a>.</p>
<p>I’ve cleaned up that data so names are in Title Case, one name per line, in files named: female_first_names, male_first_names, and last_names. There are less than 90,000 names total in all the files so we can easily store them in memory, and we’d like to access any element by index in constant time. This is a job for <a href="http://hackage.haskell.org/package/vector-0.10.9.1">Data.Vector</a>!</p>
<p>This means we’ll need a function of <code>Vector Text -&gt; Gen Text</code> to choose a random name from a vector of names, so let’s create some helper functions:</p>
<pre class="sourceCode literate literatehaskell"><code class="sourceCode literatehaskell"><span class="ot">&gt; nameFromVector ::</span> <span class="dt">Vector</span> <span class="dt">Text</span> <span class="ot">-&gt;</span> <span class="dt">Gen</span> <span class="dt">Text</span>
<span class="ot">&gt;</span> nameFromVector v <span class="fu">=</span> (v <span class="fu">!</span>) <span class="fu">&lt;$&gt;</span> choose (<span class="dv">0</span>, upperBound)
<span class="ot">&gt;</span>   <span class="kw">where</span> upperBound <span class="fu">=</span> V.length v <span class="fu">-</span> <span class="dv">1</span>
<span class="ot">&gt;</span> 
<span class="ot">&gt; vectorFromFile ::</span> FilePath <span class="ot">-&gt;</span> <span class="dt">IO</span> (<span class="dt">Vector</span> <span class="dt">Text</span>)
<span class="ot">&gt;</span> vectorFromFile path <span class="fu">=</span> V.fromList <span class="fu">.</span> T.lines <span class="fu">&lt;$&gt;</span> TIO.readFile path
<span class="ot">&gt;</span> 
<span class="ot">&gt; nameGenFromFile ::</span> FilePath <span class="ot">-&gt;</span> <span class="dt">IO</span> (<span class="dt">Gen</span> <span class="dt">Text</span>)
<span class="ot">&gt;</span> nameGenFromFile path <span class="fu">=</span> nameFromVector <span class="fu">&lt;$&gt;</span> vectorFromFile path</code></pre>
<p>And since we’ll need to pass around multiple generators, we can capture them in a new data structure (saving us from passing around three different generators to every function that needs them):</p>
<pre class="sourceCode literate literatehaskell"><code class="sourceCode literatehaskell"><span class="ot">&gt;</span> <span class="kw">data</span> <span class="dt">NameGenerators</span> <span class="fu">=</span> <span class="dt">NameGenerators</span> {
<span class="ot">&gt;     femaleFirstNames ::</span> <span class="dt">Gen</span> <span class="dt">Text</span>
<span class="ot">&gt;</span>   ,<span class="ot"> maleFirstNames   ::</span> <span class="dt">Gen</span> <span class="dt">Text</span>
<span class="ot">&gt;</span>   ,<span class="ot"> lastNames        ::</span> <span class="dt">Gen</span> <span class="dt">Text</span>
<span class="ot">&gt;</span>   }</code></pre>
<p>And finally, our function for loading all of the NameGenerators:</p>
<pre class="sourceCode literate literatehaskell"><code class="sourceCode literatehaskell"><span class="ot">&gt; allNameGenerators ::</span> <span class="dt">IO</span> <span class="dt">NameGenerators</span>
<span class="ot">&gt;</span> allNameGenerators <span class="fu">=</span> <span class="dt">NameGenerators</span> <span class="fu">&lt;$&gt;</span> nameGenFromFile <span class="st">&quot;female_first_names&quot;</span>
<span class="ot">&gt;</span>                                    <span class="fu">&lt;*&gt;</span> nameGenFromFile <span class="st">&quot;male_first_names&quot;</span>
<span class="ot">&gt;</span>                                    <span class="fu">&lt;*&gt;</span> nameGenFromFile <span class="st">&quot;last_names&quot;</span></code></pre>
<p>Hardcoding filepaths isn’t exactly a Best Practice<sup>TM</sup>, but in this case if a file isn’t found, we want the program to fail hard, and the default “&lt;filepath&gt;: openFile: does not exist (No such file or directory)” error message is sufficient.</p>
<h3>
Emails that kind of look like emails
</h3>
<p>QuickCheck is very good at generating random data, so the challenge with generating email addresses is not what to generate, but what not to generate. If you’re clicking interactively through a test site and every email looks like “r36oEx04C4d8l9q6q38V3xMu@Vj4WWrRcZdpCsKy904Dhz65Uy0.com” it’s a little discomfiting.</p>
<p>For the domain portion of the email address, we’ll prepare a small list of popular domains and made up weighted values to decide how frequently each should occur (we’ll see how to make use of these values soon):</p>
<pre class="sourceCode literate literatehaskell"><code class="sourceCode literatehaskell"><span class="ot">&gt; emailDomains ::</span> [(<span class="dt">Int</span>, <span class="dt">Gen</span> <span class="dt">Text</span>)]
<span class="ot">&gt;</span> emailDomains <span class="fu">=</span> map (\ (i, t) <span class="ot">-&gt;</span> (i, pure t)) [
<span class="ot">&gt;</span>     (<span class="dv">50</span>, <span class="st">&quot;yahoo.com&quot;</span>)
<span class="ot">&gt;</span>   , (<span class="dv">40</span>, <span class="st">&quot;hotmail.com&quot;</span>)
<span class="ot">&gt;</span>   , (<span class="dv">30</span>, <span class="st">&quot;aol.com&quot;</span>)
<span class="ot">&gt;</span>   , (<span class="dv">20</span>, <span class="st">&quot;gmail.com&quot;</span>)
<span class="ot">&gt;</span>   , (<span class="dv">10</span>, <span class="st">&quot;sbcglobal.net&quot;</span>)
<span class="ot">&gt;</span>   , (<span class="dv">8</span>,  <span class="st">&quot;yahoo.co.uk&quot;</span>)
<span class="ot">&gt;</span>   , (<span class="dv">6</span>,  <span class="st">&quot;yahoo.ca&quot;</span>)
<span class="ot">&gt;</span>   ]</code></pre>
<p>We could automate building a list like this from a file containing many more domains and actual frequencies if we really wanted to match historical data or real world usage in a particular context.</p>
<p>Next we’d like to create a couple of functions to generate the local part of an email address in different ways. We’ll start with two plausible forms, &lt;first initial&gt;&lt;last name&gt; and &lt;last name&gt;&lt;digits&gt;:</p>
<pre class="sourceCode literate literatehaskell"><code class="sourceCode literatehaskell"><span class="ot">&gt;</span> <span class="co">-- initialWithLast &quot;Foo&quot; &quot;Bar&quot; would produce a generator returning &quot;fbar&quot;</span>
<span class="ot">&gt; initialWithLast ::</span> <span class="dt">Text</span> <span class="ot">-&gt;</span> <span class="dt">Text</span> <span class="ot">-&gt;</span> <span class="dt">Gen</span> <span class="dt">Text</span>
<span class="ot">&gt;</span> initialWithLast fName lName <span class="fu">=</span> pure <span class="fu">$</span> initial <span class="ot">`T.cons`</span> rest
<span class="ot">&gt;</span>   <span class="kw">where</span> initial <span class="fu">=</span> T.head <span class="fu">.</span> T.toLower <span class="fu">$</span> fName
<span class="ot">&gt;</span>         rest    <span class="fu">=</span> T.toLower lName
<span class="ot">&gt;</span> 
<span class="ot">&gt;</span> <span class="co">-- lastWithNumber &quot;Bar&quot; will return barXX (XX for any two digits 11-99)</span>
<span class="ot">&gt; lastWithNumber ::</span> <span class="dt">Text</span> <span class="ot">-&gt;</span> <span class="dt">Gen</span> <span class="dt">Text</span>
<span class="ot">&gt;</span> lastWithNumber lName <span class="fu">=</span> T.append namePart <span class="fu">&lt;$&gt;</span> numberPart
<span class="ot">&gt;</span>   <span class="kw">where</span> namePart   <span class="fu">=</span> T.toLower lName
<span class="ot">&gt;</span>         numberPart <span class="fu">=</span> T.pack <span class="fu">.</span> show <span class="fu">&lt;$&gt;</span> numId
<span class="ot">&gt;</span>         numId      <span class="fu">=</span> choose (<span class="dv">11</span>, <span class="dv">99</span>)<span class="ot"> ::</span> <span class="dt">Gen</span> <span class="dt">Int</span></code></pre>
<p>We can put it all together using QuickCheck’s <em>oneof</em> (<code>[Gen a] -&gt; Gen a</code>) to randomly choose from the above functions for the local part, and <em>frequency</em> (<code>[(Int, Gen a)] -&gt; Gen a</code>) to select domains from our weighted list:</p>
<pre class="sourceCode literate literatehaskell"><code class="sourceCode literatehaskell"><span class="ot">&gt; genEmail ::</span> <span class="dt">Text</span> <span class="ot">-&gt;</span> <span class="dt">Text</span> <span class="ot">-&gt;</span> <span class="dt">Gen</span> <span class="dt">Email</span>
<span class="ot">&gt;</span> genEmail f l <span class="fu">=</span> <span class="dt">Email</span> <span class="fu">&lt;$&gt;</span> oneof [initialWithLast f l, lastWithNumber l]
<span class="ot">&gt;</span>                      <span class="fu">&lt;*&gt;</span> frequency emailDomains</code></pre>
<p>These examples are only meant to be illustrative, and while the email addresses will look somewhat convincing, there won’t be much variation. You can always extend the list of strategies with as many email patterns as you can think of: first name with last initial, nick names, foods, random dictionary words, incorporating the user’s birth year in any of the other patterns, etc.</p>
<h3>
The full profile
</h3>
<p>We finally have all of the generators we need to create a complete user profile:</p>
<pre class="sourceCode literate literatehaskell"><code class="sourceCode literatehaskell"><span class="ot">&gt; genUserProfile ::</span> <span class="dt">NameGenerators</span> <span class="ot">-&gt;</span> <span class="dt">Gen</span> <span class="dt">UserProfile</span>
<span class="ot">&gt;</span> genUserProfile nameGens <span class="fu">=</span> <span class="kw">do</span>
<span class="ot">&gt;</span>   gender   <span class="ot">&lt;-</span> arbitrary
<span class="ot">&gt;</span>   bDay     <span class="ot">&lt;-</span> arbitrary
<span class="ot">&gt;</span>   fName    <span class="ot">&lt;-</span> <span class="kw">case</span> gender <span class="kw">of</span>
<span class="ot">&gt;</span>     <span class="dt">Female</span> <span class="ot">-&gt;</span> femaleFirstNames nameGens
<span class="ot">&gt;</span>     <span class="dt">Male</span>   <span class="ot">-&gt;</span> maleFirstNames   nameGens
<span class="ot">&gt;</span>   lName    <span class="ot">&lt;-</span> lastNames nameGens
<span class="ot">&gt;</span>   email    <span class="ot">&lt;-</span> genEmail fName lName
<span class="ot">&gt;</span>   password <span class="ot">&lt;-</span> genPassword <span class="ot">`suchThat`</span> ((<span class="fu">&gt;</span><span class="dv">5</span>) <span class="fu">.</span> T.length)
<span class="ot">&gt;</span>   return <span class="fu">$</span> <span class="dt">UserProfile</span> fName lName email password gender bDay</code></pre>
<p>Note that we create a new password generator on the fly using the <em>suchThat</em> modifier (<code>Gen a -&gt; (a -&gt; Bool) -&gt; Gen a</code>) with our original generator. We could have placed this constraint in the <em>genPassword</em> definition, but this example shows how you can easily create modified generators for particular use cases.</p>
<h3>
Producing data
</h3>
<p>QuickCheck is mostly designed to help you test generated data, not generate data for arbitrary uses (hah, hah). But even though it doesn’t export tools for working with the internals of Gen directly, it does export a function called <em>sample’</em> that always generates a list of 11 results in the IO monad. We can pair this with <em>concat</em> and the <em>vectorOf</em> generator to create as many elements as we want, as long as you want multiples of 11. In case you don’t, we’ll apply <em>take</em> to ensure we only extract the requested number of elements:</p>
<pre class="sourceCode literate literatehaskell"><code class="sourceCode literatehaskell"><span class="ot">&gt; generate ::</span> <span class="dt">Int</span> <span class="ot">-&gt;</span> <span class="dt">Gen</span> a <span class="ot">-&gt;</span> <span class="dt">IO</span> [a]
<span class="ot">&gt;</span> generate n gen <span class="fu">=</span> take n <span class="fu">.</span> concat <span class="fu">&lt;$&gt;</span> (sample&#39; <span class="fu">.</span> vectorOf count) gen
<span class="ot">&gt;</span>   <span class="kw">where</span> count <span class="fu">=</span> ceiling <span class="fu">$</span> fromIntegral n <span class="fu">/</span> <span class="fl">11.0</span></code></pre>
<p>If this looks like a hack, well, sure. It is. The <em>sample’</em> function exists for debugging purposes and isn’t a perfect fit here, but it’s the only exported function we have to work with that will give us <code>Gen a -&gt; IO [a]</code>.</p>
<h3>
Main
</h3>
<p>We can round out the program with some basic command-line arg handling (allowing a user to specify the number of records to generate), and a main method for printing data in our CSV-compatible but not exactly robust format.</p>
<pre class="sourceCode literate literatehaskell"><code class="sourceCode literatehaskell"><span class="ot">&gt; countDefault ::</span> <span class="dt">Int</span>
<span class="ot">&gt;</span> countDefault <span class="fu">=</span> <span class="dv">100</span>
<span class="ot">&gt;</span> 
<span class="ot">&gt;</span> <span class="co">-- tries to read the first command-line arg as an Int (the number of records</span>
<span class="ot">&gt;</span> <span class="co">-- to generate), otherwise uses the default.</span>
<span class="ot">&gt; handleArgs ::</span> [<span class="dt">String</span>] <span class="ot">-&gt;</span> <span class="dt">Int</span>
<span class="ot">&gt;</span> handleArgs []    <span class="fu">=</span> countDefault
<span class="ot">&gt;</span> handleArgs (x<span class="fu">:</span>_) <span class="fu">=</span> <span class="kw">case</span> readMaybe<span class="ot"> x ::</span> <span class="dt">Maybe</span> <span class="dt">Int</span> <span class="kw">of</span>
<span class="ot">&gt;</span>   <span class="dt">Just</span> n  <span class="ot">-&gt;</span> n
<span class="ot">&gt;</span>   <span class="dt">Nothing</span> <span class="ot">-&gt;</span> countDefault
<span class="ot">&gt;</span> 
<span class="ot">&gt;</span> main <span class="fu">=</span> <span class="kw">do</span>
<span class="ot">&gt;</span>   count      <span class="ot">&lt;-</span> handleArgs     <span class="fu">&lt;$&gt;</span> getArgs
<span class="ot">&gt;</span>   profileGen <span class="ot">&lt;-</span> genUserProfile <span class="fu">&lt;$&gt;</span> allNameGenerators
<span class="ot">&gt;</span>   profiles   <span class="ot">&lt;-</span> generate count profileGen
<span class="ot">&gt;</span>   TIO.putStrLn <span class="st">&quot;first,last,email,password,gender,birthday&quot;</span>
<span class="ot">&gt;</span>   mapM_ (TIO.putStrLn <span class="fu">.</span> profileText) profiles</code></pre>
<h3>
A dash of cabal
</h3>
<p>Here’s a snippet from the arbitraryfun cabal file if you’d like to use this as an executable:</p>
<pre class="text"><code>executable arbitraryfun
  hs-source-dirs:      src
  main-is:             Main.lhs
  default-language:    Haskell2010
  build-depends:       base        &gt;= 4.6
                     , QuickCheck  &gt;= 2.6
                     , time        &gt;= 1.4
                     , text        &gt;= 1.1
                     , vector      &gt;= 0.10</code></pre>
<p>Keep in mind you’ll also need to:</p>
<ul>
<li>copy and paste the text content of this post into src/Main.lhs</li>
<li>create your own name lists (files named female_first_names, male_first_names, and last_names)</li>
<li>ensure the name files are in the current working directory when you run it</li>
</ul>
<h3>
Seeing it in action
</h3>
<p>And after all of our work, here’s what we get on a sample run:</p>
<pre class="console"><code>$ arbitraryfun 10
first,last,email,password,gender,birthday
Kathey,Hodgeman,hodgeman94@hotmail.com,&quot;%.=kn3&quot;,Female,1947-11-15
Lorri,Weyland,weyland73@yahoo.com,&quot;v/.;}?&quot;,Female,1990-02-06
Celena,Kali,ckali@yahoo.com,&quot;pg(VjsR&quot;,Female,1981-10-14
Blaine,Mellema,mellema21@sbcglobal.net,&quot;l{Um:-b6k&quot;,Male,1990-07-02
Bud,Potempa,potempa27@gmail.com,&quot;JB:*]*&gt;&quot;,Male,1993-01-28
Aletha,Schoenecker,aschoenecker@yahoo.com,&quot;#A%6lUf&quot;,Female,1998-10-13
Connie,Romesburg,cromesburg@yahoo.com,&quot;$Y$&gt;iEl&gt;e&quot;,Male,1950-01-27
Ione,Primus,primus66@hotmail.com,&quot;B[9^K+qnj&lt;f9&#39;&quot;,Female,1993-05-10
Sylvia,Magorina,smagorina@yahoo.com,&quot;^+#p1l+&quot;,Female,2007-01-13
Fermin,Lampey,flampey@sbcglobal.net,&quot;pq@f&lt;v8m*&quot;,Male,1929-07-11</code></pre>
<p>This is by no means a robust program, but we’ve put enough constraints on the generated data that you should be able to view it in a spreadsheet or use it with many CSV import tools. In a completely non-rigorous benchmark this program was able to generate about 40,000 records in a second, and thanks to lazy Haskell magic, QuickCheck, and Data.Text, it also showed a low, constant memory usage even when generating 10 million records and piping them to a file (a process that took less than 4 minutes).</p>]]></summary>
</entry>
<entry>
    <title>Haskell Development with Cabal Sandboxes</title>
    <link href="http://chromaticleaves.com/posts/cabal-sandbox-workflow.html" />
    <id>http://chromaticleaves.com/posts/cabal-sandbox-workflow.html</id>
    <published>2014-01-10T00:00:00Z</published>
    <updated>2014-01-10T00:00:00Z</updated>
    <summary type="html"><![CDATA[<p>Cabal sandboxes were introduced in cabal 1.18, and they’re designed to let you build Haskell packages in isolated environments. Cabal sandboxes are largely based on the <a href="https://hackage.haskell.org/package/cabal-dev">cabal-dev</a> tool, and similar in spirit to <a href="http://hackage.haskell.org/package/hsenv">hsenv</a> (which has some other advantages).<sup><a href="#footnote1">1</a></sup></p>
<h4 id="simplifying-your-workflow">Simplifying your workflow</h4>
<p>The motivation for isolating environments is straightforward: if you’re working on more than one project at a time, the projects may have conflicting dependencies, and managing all of them at the system level is a nightmare.</p>
<p>Throw in large libraries and web frameworks at different versions and you have a recipe for dependency hell. Trying to resolve and accommodate every new build error at the system level is enough to make anyone superstitious, performing archaic rituals and beseeching the mighty build gods before daring to run their next cabal command.</p>
<p>Even if you manage to make it work, it leaves your system environment in a state that might not be easy to reproduce, making it harder to troubleshoot build issues others might experience with your software. After having been through this enough times on my own (and across enough languages), I finally realized that sandboxes shouldn’t be the exception during development: they should be the default.<sup><a href="#footnote2">2</a></sup></p>
<h4 id="versions-used-here">Versions used here</h4>
<p>Before we work through a quick example, here are the versions I’m using:</p>
<pre><code>$ ghc --version
The Glorious Glasgow Haskell Compilation System, version 7.6.3
$ cabal --version
cabal-install version 1.18.0.1
using version 1.18.0 of the Cabal library</code></pre>
<h4 id="example-building-this-blog">Example: building this blog</h4>
<p>My blog is created with <a href="http://jaspervdj.be/hakyll/">Hakyll</a>, a Haskell library with many dependencies. If you wanted to learn Hakyll and use my code as a starting point, it’s entirely possible (and likely) that something in the chain of dependencies will conflict with Haskell libraries you have installed at the system level.</p>
<p>Here’s how you can build <code>chromaticleaves</code> in a sandbox to avoid these issues:</p>
<pre><code>$ git clone git@github.com:ericrasmussen/chromaticleaves.git
$ cd chromaticleaves
$ cabal sandbox init
Writing a default package environment file to
/path/to/chromaticleaves/cabal.sandbox.config
Creating a new sandbox at /path/to/chromaticleaves/.cabal-sandbox</code></pre>
<p>Now that we’re in a sandbox, the next step is installing all the dependencies from <a href="https://github.com/ericrasmussen/chromaticleaves/blob/master/chromaticleaves.cabal">chromaticleaves.cabal</a> (it’s a deceptively short list, but Hakyll will pull in many other dependencies):</p>
<pre><code>$ cabal install --only-dependencies</code></pre>
<p>Hopefully everything will install fine, but you may still see some missing system dependencies or other issues depending on your OS. The output from the install command should provide details.</p>
<p>Once you’ve got that sorted out, you can install the <code>site</code> binary with:</p>
<pre><code>$ cabal install</code></pre>
<p>This will create the executable .cabal-sandbox/bin/site that you can use to launch the site locally with “site preview”, rebuild after changes with “site rebuild”, and anything else from Hakyll’s <a href="http://jaspervdj.be/hakyll/tutorials/02-basics.html">The Basics</a> tutorial.</p>
<p>Lastly, you can even jump into a fully loaded GHCi session using:</p>
<pre><code>$ cabal repl</code></pre>
<p>Which will start GHCi with all of the top level functions from the <code>chromaticleaves</code> main source file.</p>
<h4 id="path-hackery">Path hackery</h4>
<p>When you cabal install anything in your sandbox (including any executables from the software you’re developing), they’re placed in <em>your/sandbox/.cabal-sandbox/bin</em>. It’s convenient to add this relative path to your system’s <a href="http://en.wikipedia.org/wiki/PATH_%28variable%29">$PATH variable</a>:</p>
<pre><code>.cabal-sandbox/bin</code></pre>
<p>Preferably adding it before your user cabal bin and other bin folders. Specifying it as a relative path means that when your current working directory contains a sandbox, any binaries installed there take precedence.</p>
<p>However, note that this only works for executables installed with “cabal install” in your sandbox. There’s also a “cabal build” command that creates dist files in meaningfully named subfolders. The command will work just fine, but note that the simple relative path we used above won’t pick up any binaries installed that way.</p>
<p>If you followed along on the above blog building example, then going to the chromaticleaves directory should automatically place the sandboxed <code>site</code> on your path. You can verify with:</p>
<pre><code>$ which site
.cabal-sandbox/bin/site</code></pre>
<h4 id="ignorables">Ignorables</h4>
<p>Initializing a cabal sandbox will add a hidden folder and a config file to your current working directory. If you manage your project with version control, you should add these to your ignore/boring files:</p>
<pre><code>.cabal-sandbox/
cabal.sandbox.config</code></pre>
<h4 id="further-reading">Further reading</h4>
<p>There are many common commands and other usage patterns not covered here. The best thorough introduction to using cabal sandboxes is <a href="http://coldwa.st/e/blog/2013-08-20-Cabal-sandbox.html">An Introduction to Cabal sandboxes</a>.</p>
<p>It’s a must-read if you plan on using them, and you should also keep the official <a href="http://www.haskell.org/cabal/users-guide/installing-packages.html#developing-with-sandboxes">Cabal User Guide</a> handy as a reference.</p>
<hr />
<p><sub><a id="footnote1">1.</a> hsenv only works on *nix systems but has the advantage of fully sandboxing ghc, ghci, and cabal, instead of relying on their system versions and only sandboxing build dependencies.</sub></p>
<p><sub><a id="footnote2">2.</a> Of course, there are other solutions to this problem: jails, containers, VMs, buying a new laptop for each project, etc. </sub></p>]]></summary>
</entry>
<entry>
    <title>Compiled Heist: The Walkthrough</title>
    <link href="http://chromaticleaves.com/posts/compiled-heist-the-walkthrough.html" />
    <id>http://chromaticleaves.com/posts/compiled-heist-the-walkthrough.html</id>
    <published>2013-12-04T00:00:00Z</published>
    <updated>2013-12-04T00:00:00Z</updated>
    <summary type="html"><![CDATA[<p>This tutorial post is going to jump right in to learning about and using the Heist.Compiled module inside a Snap application. If you’ve never used Heist before, you may want to start with the much gentler introduction from my previous post: <a href="/posts/the-great-template-heist.html">The Great Template Heist</a>.</p>
<h4 id="there-can-only-be-one-not-really">There can only be one (not really)</h4>
<p>Heist now comes in two flavors: interpreted and compiled. The former has been around longer, is more flexible, and has a very accessible API. It is plenty fast for many use cases, but inefficient because it requires traversing templates node by node each time they’re rendered.</p>
<p>Compiled Heist takes a different approach: it compiles as much of the templates down to ByteStrings as possible, letting you fill in runtime values only where you need them. The result is a staggering performance gain, with some compiled templates rendering at more than 3000x the speed of their interpreted equivalents.<sup><a href="#footnote1">1</a></sup></p>
<p>The price you pay for these huge gains in performance is having to specify and load all of your compiled splices, once, at the top level of your application.</p>
<p>Take a moment to let that sink in: all of your top level splices need to be pre-defined and available at the time your application loads. Unlike interpreted Heist, you can’t bind local splices to a template at render time. When you render a compiled template in a Snap Handler, the only splices it can use are those you defined in your HeistConfig.</p>
<h4 id="runtime-splices-and-node-reuse">Runtime splices and node reuse</h4>
<p>If you’re only familiar with interpreted splices, you might be wondering how this inversion of control affects us. Specifically, two questions come to mind:</p>
<ol style="list-style-type: decimal">
<li>If we need to pre-define our splices, how can we render dynamic values?</li>
<li>If we can only bind a node to a single compiled splice, how can we reuse nodes?</li>
</ol>
<p>The first problem can be solved with the notion of a RuntimeSplice, which you can think of as a computation that will be evaluated at runtime each time its needed, letting you perform the IO and logic you need for accessing databases, reading from files, etc.</p>
<p>We can reuse nodes by declaring any compiled splices we need within the top level splice. You can think of it as nesting splices, or inner splices, or binders full of splices, or… nevermind. Let’s just work through an example.</p>
<h4 id="listing-things">Listing things</h4>
<p>Here’s a sample template where the <code>&lt;allTutorials&gt;</code> node contains nodes representing one table row for a single tutorial. We’d like to be able to repeat those nodes once for each tutorial in a list of tutorials:</p>
<pre class="sourceCode html"><code class="sourceCode html"><span class="kw">&lt;table&gt;</span>
  <span class="kw">&lt;thead&gt;</span>
    <span class="kw">&lt;tr&gt;</span>
      <span class="kw">&lt;th&gt;</span>Title<span class="kw">&lt;/th&gt;</span>
      <span class="kw">&lt;th&gt;</span>Author<span class="kw">&lt;/th&gt;</span>
    <span class="kw">&lt;/tr&gt;</span>
  <span class="kw">&lt;/thead&gt;</span>
  <span class="kw">&lt;tbody&gt;</span>

  <span class="kw">&lt;allTutorials&gt;</span>

    <span class="kw">&lt;tr&gt;</span>
      <span class="kw">&lt;td&gt;</span>
        <span class="kw">&lt;a</span><span class="ot"> href=</span><span class="st">&quot;${tutorialURL}&quot;</span><span class="kw">&gt;&lt;tutorialTitle/&gt;&lt;/a&gt;</span>
      <span class="kw">&lt;/td&gt;</span>
      <span class="kw">&lt;td&gt;</span>
        <span class="kw">&lt;tutorialAuthor/&gt;</span>
      <span class="kw">&lt;/td&gt;</span>
    <span class="kw">&lt;/tr&gt;</span>

  <span class="kw">&lt;/allTutorials&gt;</span>

  <span class="kw">&lt;/tbody&gt;</span>
<span class="kw">&lt;/table&gt;</span></code></pre>
<p>We’ll get started by defining a simple tutorial type:</p>
<pre class="sourceCode haskell"><code class="sourceCode haskell"><span class="kw">data</span> <span class="dt">Tutorial</span> <span class="fu">=</span> <span class="dt">Tutorial</span> {
<span class="ot">    title  ::</span> <span class="dt">Text</span>
  ,<span class="ot"> url    ::</span> <span class="dt">Text</span>
  ,<span class="ot"> author ::</span> <span class="dt">Text</span>
  }</code></pre>
<p>Now, remember we mentioned being able to defer computations until runtime? To keep things simple we’re going to return a constant list of Tutorials as the result of a RuntimeSplice computation, but in a real world app you could query a database or obtain the list from another source:</p>
<pre class="sourceCode haskell"><code class="sourceCode haskell"><span class="ot">tutorialsRuntime ::</span> <span class="dt">Monad</span> n <span class="ot">=&gt;</span> <span class="dt">RuntimeSplice</span> n [<span class="dt">Tutorial</span>]
tutorialsRuntime <span class="fu">=</span> return [ <span class="dt">Tutorial</span> <span class="st">&quot;title1&quot;</span> <span class="st">&quot;url1&quot;</span> <span class="st">&quot;author1&quot;</span>
                          , <span class="dt">Tutorial</span> <span class="st">&quot;title2&quot;</span> <span class="st">&quot;url2&quot;</span> <span class="st">&quot;author2&quot;</span>
                          ]</code></pre>
<p>Here’s where things get interesting: there is virtually no API for working directly with RuntimeSplices, so we can’t easily inspect the underlying runtime value and bind the result to a node name. Instead, we’re going to create Splices containing a function that can do this for us. Note that in the examples below, Heist.Compiled is imported as <code>C</code>.</p>
<pre class="sourceCode haskell"><code class="sourceCode haskell"><span class="ot">splicesFromTutorial ::</span> <span class="dt">Monad</span> n <span class="ot">=&gt;</span> <span class="dt">Splices</span> (<span class="dt">RuntimeSplice</span> n <span class="dt">Tutorial</span> <span class="ot">-&gt;</span> <span class="dt">C.Splice</span> n)
splicesFromTutorial <span class="fu">=</span> mapS (C.pureSplice <span class="fu">.</span> C.textSplice) <span class="fu">$</span> <span class="kw">do</span>
  <span class="st">&quot;tutorialTitle&quot;</span>  <span class="st">## title</span>
  <span class="st">&quot;tutorialURL&quot;</span>    <span class="st">## url</span>
  <span class="st">&quot;tutorialAuthor&quot;</span> <span class="st">## author</span></code></pre>
<p>Remember that title, url, and author are functions defined in our Tutorial type. So our do block contains a value of type <code>Splices (Tutorial -&gt; Text)</code>. We then map over those splices to create pure splices from each.</p>
<p>If this all sounds a little heavy, don’t panic! It takes some time working with functions in the Heist.Compiled module to build fluency. No amount of explanation is going to make the reason for this immediately clear; it’s simply one way we can leverage the higher level compiled splice functions we have available to us.</p>
<p>But you <em>should</em> make an effort to follow the types as we go, even if only in the abstract. Here are the type signatures for the Heist functions we used above:</p>
<pre class="sourceCode haskell"><code class="sourceCode haskell"><span class="ot">textSplice ::</span> (a <span class="ot">-&gt;</span> <span class="dt">Text</span>) <span class="ot">-&gt;</span> a <span class="ot">-&gt;</span> <span class="dt">Builder</span>

<span class="ot">pureSplice ::</span> <span class="dt">Monad</span> n <span class="ot">=&gt;</span> (a <span class="ot">-&gt;</span> <span class="dt">Builder</span>) <span class="ot">-&gt;</span> <span class="dt">RuntimeSplice</span> n a <span class="ot">-&gt;</span> <span class="dt">Splice</span> n

<span class="ot">mapS ::</span> (a <span class="ot">-&gt;</span> b) <span class="ot">-&gt;</span> <span class="dt">Splices</span> a <span class="ot">-&gt;</span> <span class="dt">Splices</span> b</code></pre>
<p>In our case, the splices first contain a function of <code>Tutorial -&gt; Text</code>, which is passed to textSplice, giving us a function of <code>Text -&gt; Builder</code>, which is what pureSplice expects as its first argument.</p>
<p>The end result is a series of splices where node names map to functions of <code>RuntimeSplice n Tutorial -&gt; C.Splice n</code>. Compiled Heist gives us a few options for working with splices containing functions of this type. Here’s how we can map over a list of runtime tutorials and create a single compiled splice containing all of the rendered tutorial splices:</p>
<pre class="sourceCode haskell"><code class="sourceCode haskell"><span class="ot">renderTutorials ::</span> <span class="dt">Monad</span> n <span class="ot">=&gt;</span> <span class="dt">RuntimeSplice</span> n [<span class="dt">Tutorial</span>] <span class="ot">-&gt;</span> <span class="dt">C.Splice</span> n
renderTutorials <span class="fu">=</span> C.manyWithSplices C.runChildren splicesFromTutorial</code></pre>
<p>For posterity, here are the type signatures for the supporting Heist.Compiled functions used above:</p>
<pre class="sourceCode haskell"><code class="sourceCode haskell"><span class="ot">runChildren ::</span> <span class="dt">Monad</span> n <span class="ot">=&gt;</span> <span class="dt">Splice</span> n

<span class="ot">manyWithSplices ::</span> <span class="dt">Monad</span> n
                <span class="ot">=&gt;</span> <span class="dt">Splice</span> n
                <span class="ot">-&gt;</span> <span class="dt">Splices</span> (<span class="dt">RuntimeSplice</span> n a <span class="ot">-&gt;</span> <span class="dt">Splice</span> n)
                <span class="ot">-&gt;</span> <span class="dt">RuntimeSplice</span> n [a]
                <span class="ot">-&gt;</span> <span class="dt">Splice</span> n</code></pre>
<p>It’s a lot to take in, but follow through step by step to see that everything lines up.</p>
<p>Now we have a way to process a runtime computation returning a list of tutorials, create individual tutorial splices for each tutorial, and return it as a single compiled splice. This is a very important point that gets to the core of compiled Heist: we can reuse splices (and thus nodes in a template) however we want, as long as we compile them down to a single splice this way.</p>
<p>We can then create top level splices that will map the outer <code>&lt;allTutorials&gt;</code> node to this compiled splice:</p>
<pre class="sourceCode haskell"><code class="sourceCode haskell"><span class="ot">allTutorialSplices ::</span> <span class="dt">Monad</span> n <span class="ot">=&gt;</span> <span class="dt">Splices</span> (<span class="dt">C.Splice</span> n)
allTutorialSplices <span class="fu">=</span>
  <span class="st">&quot;allTutorials&quot;</span> <span class="st">## (renderTutorials tutorialsRuntime)</span></code></pre>
<p>Once we have the fully compiled splices, we can add them to our HeistConfig so it will be available to our template when rendered:</p>
<pre class="sourceCode haskell"><code class="sourceCode haskell"><span class="ot">app ::</span> <span class="dt">SnapletInit</span> <span class="dt">App</span> <span class="dt">App</span>
app <span class="fu">=</span> makeSnaplet <span class="st">&quot;app&quot;</span> <span class="st">&quot;A snap demo application.&quot;</span> <span class="dt">Nothing</span> <span class="fu">$</span> <span class="kw">do</span>
    h <span class="ot">&lt;-</span> nestSnaplet <span class="st">&quot;&quot;</span> heist <span class="fu">$</span> heistInit <span class="st">&quot;templates&quot;</span>
    <span class="co">-- add the compiled splices to our HeistConfig</span>
    addConfig h <span class="fu">$</span> mempty { hcCompiledSplices <span class="fu">=</span> allTutorialSplices }
    <span class="co">-- the rest of your SnapletInit</span></code></pre>
<p>At this point all that remains is rendering the template in a Snap handler:</p>
<pre class="sourceCode haskell"><code class="sourceCode haskell"><span class="ot">tutorialHandler ::</span> <span class="dt">Handler</span> <span class="dt">App</span> <span class="dt">App</span> ()
tutorialHandler <span class="fu">=</span> cRender <span class="st">&quot;tutorials&quot;</span></code></pre>
<p>Notice again that unlike interpreted splices, we don’t (and can’t!) provide local splices specific to this template. When our handler renders the template, those splices will be automatically found in our HeistConfig.</p>
<p>The above walkthrough will hopefully give you enough insight to get started, but check out the <a href="https://github.com/ericrasmussen/snap-heist-examples/">snap-heist-examples</a> repo for a complete working version with all of the required imports, other examples, and a cabal file listing the library versions used here.</p>
<h4 id="choosing-between-interpreted-and-compiled">Choosing between interpreted and compiled</h4>
<p>It’d be nice if I could tell you to start with interpreted splices on your next project and only move to compiled splices when you need extra speed. I’m all for keeping things simple and avoiding premature optimization, and interpreted splices are plenty fast for many use cases.<sup><a href="#footnote2">2</a></sup></p>
<p>What gives me pause is that compiled splices give you a dramatic performance improvement without much extra effort, provided you plan for them in the beginning. This extra effort isn’t a bad thing either: it forces you to really think through how you obtain data and expose it to templates at the application level, whereas interpreted splices make it a little easier to play fast and loose with splices that can change locally depending on the template and particular view.</p>
<p>Compiled splices only introduce one major caveat: they won’t stop you from declaring splices with the same node name, and it will happily let you overwrite duplicate values.<sup><a href="#footnote3">3</a></sup> Let’s say you make two different compiled splices for a “userName” node used in separate templates, and put both in your Heist config. One of them will be silently overwritten, and the value it returns could be used in both templates.</p>
<p>I can think of a lot of ways this could be very dangerous (say, accidentally displaying every user’s account on an individual user profile page because you used the same node name for both). I do not think this is a likely accident, but you should definitely take precautions to ensure your Heist config doesn’t contain any surprises. Hopefully at some point in the future we’ll get a way to specify compiled splices for particular templates so we can explicitly control this behavior.</p>
<h4 id="more-examples-and-tutorials">More examples and tutorials</h4>
<p>I updated my <a href="https://github.com/ericrasmussen/snap-heist-examples">snap-heist-examples repo</a> with comparable compiled versions of the original interpreted examples. It’s not a bad place to start if you want to see Heist used in the context of a Snap application, and it should be relatively straightforward to clone the repo and build the app locally if you need a playground for learning Snap and Heist.</p>
<p>Here are some additional resources for learning more:<sup><a href="#footnote4">4</a></sup></p>
<ul>
<li><a href="http://snapframework.com/docs/tutorials/heist">Heist Template Tutorial</a></li>
<li><a href="http://snapframework.com/docs/tutorials/compiled-splices">Compiled Splices Tutorial</a></li>
<li><a href="http://snapframework.com/docs/tutorials/attribute-splices">Attribute Splices Tutorial</a></li>
<li><a href="https://www.fpcomplete.com/school/to-infinity-and-beyond/older-but-still-interesting/compiled-heist-insight-with-no-snap-in-sight">Compiled Heist insight, with no Snap in sight</a></li>
<li><a href="/posts/the-great-template-heist.html">The Great Template Heist</a></li>
</ul>
<hr />
<p><sub><a id="footnote1">1.</a> Details available in the <a href="http://snapframework.com/blog/2012/12/9/heist-0.10-released">original announcement</a>.</sub></p>
<p><sub><a id="footnote2">2.</a> We often talk about speed in relative terms as if it’s meaningful, but it’s not. Unless you benchmark and know what your expected load is, you really can’t rule out interpreted splices on the grounds that they “aren’t fast enough” for you, even though it’s tempting.</sub></p>
<p><sub><a id="footnote3">3.</a>The <a href="http://hackage.haskell.org/package/heist-0.13.0.2/docs/Heist-SpliceAPI.html">SpliceAPI module</a> exports a “#!” combinator that is similar to “##” but throws an error if there is a duplicate. </sub></p>
<p><sub><a id="footnote4">4.</a> If you write a Heist tutorial and would like to add it to the list, <a href="https://github.com/ericrasmussen/chromaticleaves/issues">open an issue</a> or send a pull request.</sub></p>]]></summary>
</entry>
<entry>
    <title>The Great Template Heist</title>
    <link href="http://chromaticleaves.com/posts/the-great-template-heist.html" />
    <id>http://chromaticleaves.com/posts/the-great-template-heist.html</id>
    <published>2013-11-27T00:00:00Z</published>
    <updated>2013-11-27T00:00:00Z</updated>
    <summary type="html"><![CDATA[<p>Heist is a powerful templating engine written in Haskell, and commonly used in Snap web applications. But if you’ve only ever worked with programmable template engines or template attribute languages, the journey to Heist proficiency is one that would make Lewis Carroll proud<sup><a href="#footnote1">1</a></sup>.</p>
<p>But first: what’s in a template?</p>
<h4 id="a-templates-journey-there-and-back-again">A template’s journey: there and back again</h4>
<p>My experience with server-side templates has been heavily influenced by popular python libraries like Mako, Jinja 2, and Chameleon.</p>
<p>The former two fall firmly into the programmable category, meaning you can use a specialized syntax in the templates to express programming logic along with your markup:</p>
<pre><code>&lt;!-- mako example: displaying a table of active users --&gt;
&lt;table&gt;
% for user in users:
  % if user.active:
    &lt;tr&gt;
      &lt;td&gt;${user.name}&lt;/td&gt;
      &lt;td&gt;${user.email}&lt;/td&gt;
    &lt;/tr&gt;
  % endif
% endfor
&lt;/table&gt;</code></pre>
<p>Which, if you’re both programmer and designer, works pretty well most of the time. However, some find this approach… distasteful. An alternative is a TAL (Template Attribute Language) like Chameleon, where you embed logic in tag attributes so you can still enforce proper markup:</p>
<pre><code>&lt;!-- chameleon example: displaying a table of active users --&gt;
&lt;table&gt;
  &lt;tal:repeat=&quot;user users&quot;&gt;
    &lt;tr tal:condition=&quot;user.active&quot;&gt;
      &lt;td&gt;${user.name}&lt;/td&gt;
      &lt;td&gt;${user.email}&lt;/td&gt;
    &lt;/tr&gt;
  &lt;/tal:repeat&gt;
&lt;/table&gt;</code></pre>
<p>This gives us cleaner markup, but the logic is still embedded in the template.</p>
<h4 id="zero-control-flow">Zero control flow</h4>
<p>Heist takes an even more extreme view: no control flow or logic in the templates. This may not be <em>entirely</em> accurate (it does have a couple of basic constructs built into the templating language, such as bind and apply), but compared to our other examples it’s a whole new world of template purity.</p>
<p>Our previous user example might look like this:</p>
<pre><code>&lt;!-- heist example: displaying a table of active users --&gt;
&lt;table&gt;
  &lt;activeUsers&gt;
    &lt;tr&gt;
      &lt;td&gt;&lt;userName/&gt;&lt;/td&gt;
      &lt;td&gt;&lt;userEmail/&gt;&lt;/td&gt;
    &lt;/tr&gt;
  &lt;/activeUsers&gt;
&lt;/table&gt;</code></pre>
<p>We can now write plain old Haskell code to:</p>
<ul>
<li>filter the user list for active users</li>
<li>map over the list to create user name and email splices</li>
<li>run the user splices against the contents of <code>&lt;activeUsers&gt;</code></li>
<li>bind the result to the <code>&lt;activeUsers&gt;</code> node</li>
</ul>
<p>One helpful way of viewing interpreted Heist is that it’s not so much a templating engine as a library for manipulating templates.<sup><a href="#footnote2">2</a></sup> An API for taking a template apart node by node and putting it back together again, optionally splicing in dynamically generated elements or text. In fact, a Heist template is literally a list of nodes:</p>
<pre class="sourceCode haskell"><code class="sourceCode haskell"><span class="co">-- a Node is an element in a Document from the Text.XmlHtml library</span>
<span class="kw">type</span> <span class="dt">Template</span> <span class="fu">=</span> [<span class="dt">Node</span>]</code></pre>
<p>Here’s the supporting code to bring it all together:</p>
<pre class="sourceCode haskell"><code class="sourceCode haskell"><span class="co">-- binds a list of splices to &lt;activeUsers&gt; (assumes we pass in active users)</span>
<span class="ot">activeUsersSplices ::</span> [<span class="dt">User</span>] <span class="ot">-&gt;</span> <span class="dt">Splices</span> (<span class="dt">SnapletISplice</span> <span class="dt">App</span>)
activeUsersSplices users <span class="fu">=</span> <span class="st">&quot;activeUsers&quot;</span> <span class="st">## (bindUsers users)</span>

<span class="co">-- maps over a list of users to create splices for each</span>
<span class="ot">bindUsers ::</span> [<span class="dt">User</span>] <span class="ot">-&gt;</span> <span class="dt">SnapletISplice</span> <span class="dt">App</span>
bindUsers <span class="fu">=</span> I.mapSplices <span class="fu">$</span> I.runChildrenWith <span class="fu">.</span> userSplices

<span class="co">-- creates the &lt;userName/&gt; and &lt;userEmail/&gt; splices for an individual user</span>
<span class="ot">userSplices ::</span> <span class="dt">Monad</span> n <span class="ot">=&gt;</span> <span class="dt">User</span> <span class="ot">-&gt;</span> <span class="dt">Splices</span> (<span class="dt">I.Splice</span> n)
userSplices (<span class="dt">User</span> name email) <span class="fu">=</span> <span class="kw">do</span>
  <span class="st">&quot;userName&quot;</span>  <span class="st">## I.textSplice name</span>
  <span class="st">&quot;userEmail&quot;</span> <span class="st">## I.textSplice email</span></code></pre>
<h4 id="navigating-the-heist-landscape">Navigating the Heist landscape</h4>
<p>Once you embrace this view of Heist as functions for manipulating templates, the next task is learning the libraries. Here’s the high level breakdown:</p>
<table>
<thead>
<tr class="header">
<th align="left">Library</th>
<th align="left">Use</th>
</tr>
</thead>
<tbody>
<tr class="odd">
<td align="left"><a href="http://hackage.haskell.org/package/heist/docs/Heist-Interpreted.html">Heist.Interpreted</a></td>
<td align="left">API for splices interpreted at runtime</td>
</tr>
<tr class="even">
<td align="left"><a href="http://hackage.haskell.org/package/heist/docs/Heist-Compiled.html">Heist.Compiled</a></td>
<td align="left">a slightly more complicated API for (more efficient) compiled splices</td>
</tr>
<tr class="odd">
<td align="left"><a href="http://hackage.haskell.org/package/heist/docs/Heist-SpliceAPI.html">Heist.SpliceAPI</a></td>
<td align="left">handy syntactic sugar for working with splices</td>
</tr>
<tr class="even">
<td align="left"><a href="http://hackage.haskell.org/package/snap/docs/Snap-Snaplet-Heist.html">Snap.Snaplet.Heist</a></td>
<td align="left">convenience functions for accessing Heist state in a Snap application</td>
</tr>
</tbody>
</table>
<h4 id="intermission-new-paint-for-the-bikeshed">Intermission: new paint for the bikeshed</h4>
<p>Choosing a template engine is kind of like choosing a text editor: everyone’s sure their approach is best, and sooner or later you’ll be dragged into silly arguments.</p>
<p>With programmable template engines, people are often quick to mention how we need a clean separation of concerns to keep business logic from ruining our pristine templates, and won’t you think of all the poor designers out there who just want to work with valid markup.</p>
<p>They sometimes neglect to mention that for some teams, expressing logic in templates is a benefit (it can clarify intent, and may be preferred when programmers are solely responsible for integrating markup), or that designer preferences vary. I have worked with designers that only hand off static assets and require the developers to handle 100% of the integration, and I’ve worked with designers that take the time to learn enough of your chosen framework and templating system to work with it.<sup><a href="#footnote3">3</a></sup></p>
<p>The bottom line is we’re discussing matters of taste and preference, so there is no right answer. It depends on the context and how well it’s going to work for everyone involved on the project.</p>
<h4 id="the-heist-payoff">The Heist payoff</h4>
<p>If your preference is designer friendly templating systems free of dangerous magic and unclean business logic, Heist is the go-to Haskell template library for you. But it’s not my own typical use case, and it’s not the grounds on which I’d recommend choosing it.</p>
<p>The payoff for me turned out to be much more subtle: you can write more Haskell. You don’t have to find a way to express what you want in a specialized template language. You can take full advantage of the language, its type system, GHCi, your tricked out text editor, etc.</p>
<p>This approach can require more code if you’re used to the convenience of programmable templates, but it also forces you to be more conscious about how you’re manipulating data and exposing it to templates. And at the end of the day, you’re writing Haskell: if you find yourself writing boilerplate, there’s probably an abstraction you can use to DRY it up.</p>
<h4 id="show-me-the-code">Show me the code!</h4>
<p>I have a bad habit of making my learning process public. In this case, I worked through some control flow basics in Heist (using interpreted splices), and wanted to share. You can view the <a href="https://github.com/ericrasmussen/snap-heist-examples">snap-heist-examples repo</a> to see <a href="https://github.com/ericrasmussen/snap-heist-examples/tree/master/src/handlers">standalone Snap handlers</a> that demonstrate different ways to repeat or conditionally include text and templates.</p>
<p>Contributions or issues/ideas are very welcome.</p>
<hr />
<p><sub><a id="footnote1">1.</a> In lieu of saying “down the rabbit hole” again, a phrase I repeat far too often. I expect I’ll continue to use more and more obscure variations on that theme. Steel yourselves.</sub></p>
<p><sub><a id="footnote2">2.</a> It’s actually more powerful and subtle than that: you can use the library to implement your own domain-specific markup languages.</sub></p>
<p><sub><a id="footnote3">3.</a> If you know of any actual studies on designer preferences, please send details to eric @ chromatic leaves dot com.</sub></p>]]></summary>
</entry>
<entry>
    <title>Death and The Sound of Perseverance</title>
    <link href="http://chromaticleaves.com/posts/death-sop.html" />
    <id>http://chromaticleaves.com/posts/death-sop.html</id>
    <published>2013-10-31T00:00:00Z</published>
    <updated>2013-10-31T00:00:00Z</updated>
    <summary type="html"><![CDATA[<div class="figure">
<img src="/images/death-sop.jpg" title="Death - SOP" />
</div>
<p>Death’s final studio album is one of the all time metal classics. On The Sound of Perseverance, Death took their brand of technical progressive thrash death metal to the next level. This is death metal evolved.</p>
<p>Most tracks open with sparse instrumentation. Deep bass lines, drum solos, lead guitar melodies, welcoming you to a new soundscape before the rest of the band appears. Before the thick guitar and bass riffs take over, the drums pound relentlessly, the scratchy vocals and lyrics invade your consciousness. Soon all of the instruments are building and pushing and driving to create an oppressive atmosphere, making it harder to breathe, harder to think, a deadly wall of sound compelling and propelling you deeper into their vision.</p>
<p>Just when you can’t take any more, it stops. A heroic melody swoops in to the rescue, letting you soar through the world they’ve created. Soon you’re surrounded by glitchy high-speed guitar solos, unexpected drum fills played with impossible accuracy, bass and rhythm guitars carrying you further and further inward until there’s nothing left but you and the music. But you have only a moment to reflect before another chaotic shift in tempo leaves you stranded in the fray, the frenzy of chugging riffs and blast beat drums.</p>
<p>Usually when we talk about progressive metal we mean metal with classically influenced melodies and harmonies, sweep picking and scales, and the many other ways skilled musicians have learned to show off their skills. You won’t get that here. You’ll get the sound of a band that evolved naturally, forever in debt to the heavy metal and thrash that preceded it, but carving ahead well into uncharted territory.</p>
<p>Death’s magic is making you a part of their journey. It’s tragic that they never got the attention they deserved<sup><a href="#footnote1">1</a></sup>, and far more so that lead guitarist/songwriter Chuck Schuldiner passed away at 34. If you missed out on The Sound of Perseverance for any reason before, now’s the time to get it. This metal is just as relevant today as it was in 1998.</p>
<hr />
<p><sub><a id="footnote1">1.</a> According to the <a href="https://en.wikipedia.org/wiki/The_Sound_of_Perseverance">WikiPedia entry</a>, The Sound of Perseverance originally saw about 34,000 copies sold in the US, vs. hundreds of thousands of record sales for popular Cannibal Corpse, Deicide, and Morbid Angel albums.</sub></p>]]></summary>
</entry>
<entry>
    <title>Striving for Correctness: A Case Study</title>
    <link href="http://chromaticleaves.com/posts/haskell-memory-quiz.html" />
    <id>http://chromaticleaves.com/posts/haskell-memory-quiz.html</id>
    <published>2013-09-25T00:00:00Z</published>
    <updated>2013-09-25T00:00:00Z</updated>
    <summary type="html"><![CDATA[<p>The most generic definition of confidence in your code is “code that does what you think it does”. No easy task. In a codebase of even modest size, there is far too much room for flawed assumptions, edge cases, and other unexpectations. Programmers seem to agree that gaining confidence in your code is desirable, and there have emerged at least two broad categories of solutions:</p>
<ol>
<li>Types</li>
<li>Tests</li>
</ol>
<p>Many inflammatory posts and twitter arguments have framed these camps as Types <em>versus</em> Tests, but the two aren’t mutually exclusive. If you’ve read my post on <a href="/posts/making-code-reasonable.html">Making Code Reasonable</a>, you may correctly guess that I prefer types, but I write tests (albeit for different purposes) either way.</p>
<p>Proponents of dynamic languages<sup><a href="#footnote1">1</a></sup> are frequently taught to solve problems in ways that can only be checked with tests, and this particular style of problem solving is one of the fundamental disconnects between the types and NoTypes crowds. Ask one of these people (including me!) how often they’ve had to write extra unit tests to make up for the lack of a good type system, and you’re likely to be met with a confused look and a “why, never!”</p>
<p>It’s true that you won’t find many tests in Python or JavaScript where the programmers are explicitly inspecting the types of objects and secretly wishing they had static typing, but this is missing the point. The benefit of static typing isn’t about enforcing the kinds of simple relationships that you wouldn’t test anyway, but expressing richer interactions that you can check with the compiler instead of a test suite.</p>
<h4 id="case-study-hsmemoryquiz">Case Study: hsmemoryquiz</h4>
<p>Recently I had a somewhat frivolous project idea: a command-line program to help me learn the Dominic System (a technique for increasing memory skills). An explanation of the Dominic System and the program, hsmemoryquiz, are available on <a href="https://github.com/ericrasmussen/hsmemoryquiz">GitHub</a>. We’ll look at some of the benefits of elevating data and abstractions to the type level.</p>
<h5 id="rethinking-numbers-and-letters">Rethinking numbers and letters</h5>
<p>The Dominic system is based on a mapping of the digits 0-9 to the letters O, A, B, C, D, E, S, G, H, and N. This foundation gives you the building blocks for working with all possible pairs of digits (00-99) and pairs of letters (OO-NN).</p>
<p>In many languages it would be practical (and expected) for you to model this data with the primitives for integers and characters. But if you enjoy obsessing over failure points in your program, this is unacceptable, because it means that every function or method using these values would need to account for the possibility of numbers outside the range 0-9.</p>
<p>Short of hideous, sprawling code with maddening error checking at every turn, it’s much more practical to define entry points for validating input before passing it to the underlying functions. You can then narrow the scope of your tests to those entry points and hope for the best.</p>
<p>But if we step back for a moment, we should be asking whether or not we need the full power of integers, characters, strings, and all of the libraries and built-ins capable of manipulating them.</p>
<p>Spoiler alert: we don’t!</p>
<p>We can create new data types that contain only the values we need:</p>
<pre class="sourceCode haskell"><code class="sourceCode haskell"><span class="kw">data</span> <span class="dt">Digit</span> <span class="fu">=</span> <span class="dt">Zero</span> <span class="fu">|</span> <span class="dt">One</span> <span class="fu">|</span> <span class="dt">Two</span> <span class="fu">|</span> <span class="dt">Three</span> <span class="fu">|</span> <span class="dt">Four</span> <span class="fu">|</span> <span class="dt">Five</span> <span class="fu">|</span> <span class="dt">Six</span> <span class="fu">|</span> <span class="dt">Seven</span> <span class="fu">|</span> <span class="dt">Eight</span> <span class="fu">|</span> <span class="dt">Nine</span>
  <span class="kw">deriving</span> (<span class="dt">Eq</span>, <span class="dt">Enum</span>)

<span class="kw">data</span> <span class="dt">DigitPair</span> <span class="fu">=</span> <span class="dt">DigitPair</span> <span class="dt">Digit</span> <span class="dt">Digit</span>
  <span class="kw">deriving</span> <span class="dt">Eq</span>

<span class="kw">data</span> <span class="dt">Letter</span> <span class="fu">=</span> <span class="dt">A</span> <span class="fu">|</span> <span class="dt">B</span> <span class="fu">|</span> <span class="dt">C</span> <span class="fu">|</span> <span class="dt">D</span> <span class="fu">|</span> <span class="dt">E</span> <span class="fu">|</span> <span class="dt">S</span> <span class="fu">|</span> <span class="dt">G</span> <span class="fu">|</span> <span class="dt">H</span> <span class="fu">|</span> <span class="dt">N</span> <span class="fu">|</span> <span class="dt">O</span>
  <span class="kw">deriving</span> (<span class="dt">Show</span>, <span class="dt">Eq</span>, <span class="dt">Enum</span>)

<span class="kw">data</span> <span class="dt">LetterPair</span> <span class="fu">=</span> <span class="dt">LetterPair</span> <span class="dt">Letter</span> <span class="dt">Letter</span>
  <span class="kw">deriving</span> <span class="dt">Eq</span></code></pre>
<p>In the Dominic system there is an exact mapping of Digits to Letters, and in the Letter module of hsmemoryquiz we’ll need a way to create Letters from Digits. We can write a function with the following signature:</p>
<pre class="sourceCode haskell"><code class="sourceCode haskell"><span class="ot">fromDigit ::</span> <span class="dt">Digit</span> <span class="ot">-&gt;</span> <span class="dt">Letter</span></code></pre>
<p>This simple declaration gives us powerful reasoning tools:</p>
<ul>
<li>The function is total; given a value of type Digit, we can produce a value of type Letter</li>
<li>We can enforce at compile time that fromDigit cannot be called with anything but a Digit</li>
<li>No logic or tests required to check input, because by definition we only accept Digits</li>
</ul>
<p>Now we can operate with complete confidence<sup><a href="#footnote2">2</a></sup> that the function does what we expect, and does so without affecting other parts of our system. We’ve succeeded in pushing the need for validation further out, allowing us to write a more robust core that doesn’t need to consider the possibility of bad input (and if anyone tries, the program won’t compile).</p>
<h4 id="control-flow-and-staircasing">Control flow and staircasing</h4>
<p>Inevitably we will need to face the outside world, and types afford us many tools for combating bad input. In imperative languages, it’s common to ignore certain kinds of troublesome input and instead throw exceptions when things go awry. This is a pattern that is convenient to write, but complicates the flow of our programs. There is an added mental overhead in having to know which exceptions may be thrown and where they may or may not be caught.</p>
<p>Often we can obviate the need for exceptions by returning values that indicate some failure condition instead. The problem here is that if you have many values that work this way, you can end up with long, complicated code blocks. Let’s look at an example in python where any of the arguments may be a legitimate value or <em>None</em>:</p>
<pre class="sourceCode python"><code class="sourceCode python"><span class="kw">def</span> build_registry(foo, bar, baz):
    <span class="kw">if</span> foo is not <span class="ot">None</span>:
        <span class="kw">if</span> bar is not <span class="ot">None</span>:
            <span class="kw">if</span> baz is not <span class="ot">None</span>:
                <span class="kw">return</span> Registry(foo, bar, baz)
    <span class="kw">return</span> <span class="ot">None</span></code></pre>
<p>Now you can see why exceptions are so appealing here! It’s much simpler to try to make an instance of Registry and ask for forgiveness (in the form of a try/except block) than it is to constantly validate input. In many languages and frameworks the notion of an empty or bad value may vary as well, requiring you to sometimes check for null, undefined, empty strings, lists with a length of 0, etc.</p>
<p>What we’re really missing in these languages is a way to express values that may be more than one type. In Haskell we can achieve this with algebraic data types. One of the canonical examples is:</p>
<pre class="sourceCode haskell"><code class="sourceCode haskell"><span class="kw">data</span> <span class="dt">Either</span> a b <span class="fu">=</span> <span class="dt">Left</span> a <span class="fu">|</span> <span class="dt">Right</span> b</code></pre>
<p>We can use this to unambiguously signify error conditions with the Left constructor and valid values with the Right. This would even allow us to define a concrete type Either String String and reliably differentiate the two cases without resorting to string matching, checking for null values, or checking for an empty string.</p>
<p>More importantly, we can use this as a basis for richer types that carry the notion of success or failure cases with them, rather than requiring the use of exceptions. Here’s an example from the Game module in hsmemoryquiz that runs a continuous quiz game:</p>
<pre class="sourceCode haskell"><code class="sourceCode haskell"><span class="ot">playGame ::</span> <span class="dt">Quiz</span> ()
playGame <span class="fu">=</span> <span class="kw">do</span>
  assoc <span class="ot">&lt;-</span> nextAssociation
  res   <span class="ot">&lt;-</span> playRound assoc
  <span class="kw">case</span> res <span class="kw">of</span>
    <span class="dt">Continue</span> <span class="ot">-&gt;</span> playGame
    <span class="dt">Stop</span>     <span class="ot">-&gt;</span> return ()</code></pre>
<p>The Quiz monad stack includes ErrorT, which means that any time we run a computation in the Quiz monad (in this case, the first two lines in the <em>do</em> block), the value returned may be either an error or a valid value. There’s no need to alter the flow of the program or nest a long series of conditionals, because the types extracted from Quiz computations already carry that notion of failure with them. If the nextAssociation function is unsuccessful (i.e. it returns ErrorT’s Left case), then the playRound line will not be evaluated, and the entire block will evaluate to that Left case.</p>
<p>The function that runs the game can then pattern match on the final value to differentiate the two cases:</p>
<pre class="sourceCode haskell"><code class="sourceCode haskell"><span class="ot">runGame ::</span> <span class="dt">Registry</span> <span class="ot">-&gt;</span> <span class="dt">IO</span> ()
runGame registry <span class="fu">=</span> <span class="kw">do</span>
  putStrLn <span class="st">&quot;Welcome! Quit at any time with \&quot;:q\&quot; or by pressing ctrl-c&quot;</span>
  res <span class="ot">&lt;-</span> runQuiz registry newQuizState playGame
  <span class="kw">case</span> res <span class="kw">of</span>
    (<span class="dt">Left</span>  e, q) <span class="ot">-&gt;</span> putStrLn <span class="fu">$</span> formatError e q
    (<span class="dt">Right</span> _, q) <span class="ot">-&gt;</span> putStrLn <span class="fu">$</span> formatSuccess q</code></pre>
<h3 id="a-twist-ending">A twist ending</h3>
<p>Although I am very certain all of you will want to dedicate hundreds of hours to learning obscure memory techniques and practicing them with my program, the real motivation behind <a href="https://github.com/ericrasmussen/hsmemoryquiz">hsmemoryquiz</a> was creating a fairly straightforward example of a Haskell command-line utility with several nice touches:</p>
<ul>
<li>Lots of code comments</li>
<li>Command-line flag parsing</li>
<li>Error handling through types</li>
<li>QuickCheck test examples using hspec</li>
<li>An interactive prompt via Haskeline (including interrupt handling)</li>
</ul>
<p>There are of course plenty of great resources out there for learning Haskell, and this isn’t intended to be a canonical example of How to Write Haskell; there are much better and more interesting Haskell programs<sup><a href="#footnote3">3</a></sup>.</p>
<p>But many full-featured utilities and programs are not written with beginners in mind. If you find yourself writing a lot of smaller utilities or single-file Haskell examples but haven’t quite taken the next step, I hope this will help you on your way.</p>
<hr />
<p><sub><a id="footnote1">1.</a> “Dynamic” being a somewhat contentious term, used here to roughly mean “types that are checked at runtime”</sub></p>
<p><sub><a id="footnote2">2.</a> Modulo the usual caveats (unsafePerformIO, error, non-termination)</sub></p>
<p><sub><a id="footnote3">3.</a> A short list of programs that have inspired me: xmonad, hlint, hoogle, hakyll</sub></p>]]></summary>
</entry>

</feed>
