<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>My life is virtual... DOT COM &#187; fake-world-haskell</title>
	<atom:link href="http://my.life-is-virtual.com/tag/fake-world-haskell/feed/" rel="self" type="application/rss+xml" />
	<link>http://my.life-is-virtual.com</link>
	<description></description>
	<lastBuildDate>Sun, 06 Mar 2011 06:32:02 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.1</generator>
		<item>
		<title>Fake World Haskell, Part 1</title>
		<link>http://my.life-is-virtual.com/2009/10/07/fake-world-haskell-part-1/</link>
		<comments>http://my.life-is-virtual.com/2009/10/07/fake-world-haskell-part-1/#comments</comments>
		<pubDate>Wed, 07 Oct 2009 02:31:20 +0000</pubDate>
		<dc:creator>jcooper</dc:creator>
				<category><![CDATA[Vaguely Instructional]]></category>
		<category><![CDATA[fake-world-haskell]]></category>
		<category><![CDATA[haskell]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[tutorial]]></category>

		<guid isPermaLink="false">http://my.life-is-virtual.com/?p=94</guid>
		<description><![CDATA[Introduction Real World Haskell (RWH) is an amazing book. Along with Learn You a Haskell, it&#8217;s one of the main resources available for Haskell newbies/intermediates who are looking for a comprehensive guide. It especially focuses on using &#8220;everyday life&#8221; coding &#8230;<p class="read-more"><a href="http://my.life-is-virtual.com/2009/10/07/fake-world-haskell-part-1/">Read more &#187;</a></p>]]></description>
			<content:encoded><![CDATA[<p><span class="bold">Introduction</span></p>
<p><a href="http://book.realworldhaskell.org/" class="italic">Real World Haskell</a> (RWH) is an amazing book. Along with <a href="http://learnyouahaskell.com/">Learn You a Haskell</a>, it&#8217;s one of the main resources available for Haskell newbies/intermediates who are looking for a comprehensive guide. It especially focuses on using &#8220;everyday life&#8221; coding examples to show how things are done. Many concepts are taught by example in this way.</p>
<p>RWH is a big book. And it&#8217;s not just fluff: it&#8217;s big and <span class="italic">concentrated</span>&#8211;you can tell that it could easily be twice as big. I was unable to digest it on one reading, and have read many of the chapters many times. I&#8217;m not the sharpest knife in the drawer, but I&#8217;m an experienced programmer in other languages, and I&#8217;m sure there are others in my boat: programmers who are intrigued by Haskell and functional programming, but are looking for more resources to make the journey easier.</p>
<p>I&#8217;m writing this, therefore, to be a sort of &#8220;companion&#8221; to RWH. From it, I&#8217;m going to steal much of the organization and flow. The authors of RWH didn&#8217;t have the luxury of being able to go back and explain things they&#8217;d already explained, and as such I found that following the examples could be difficult. <span class="bold">The goal of this text is to provide a more gentle guide through the examples presented in RWH.</span></p>
<p><span class="bold">Who is this for?</span></p>
<p>Hopefully, any Haskell newbie will benefit from reading this, even if they haven&#8217;t had any issues following along with RWH. But it&#8217;s especially geared toward those who have found RWH&#8217;s pace to be a little too rigorous, and wouldn&#8217;t mind some reinforcement about concepts already touched upon. I&#8217;m going to assume that syntax largely isn&#8217;t a problem; the first couple chapters of RWH cover most of what I think you&#8217;d need to know to follow along (and do so quite well). I won&#8217;t, however, assume total familiarity with the concepts the syntax represents (in other words, a datatype definition shouldn&#8217;t <span class="italic">look</span> weird, but it&#8217;s okay if you don&#8217;t know what a &#8220;data constructor&#8221; is). </p>
<p>I&#8217;m also going to break a longstanding tradition as far as variable names. As RWH points out, since function definitions in Haskell are short and succinct, short variable names often don&#8217;t hamper readability much <span class="italic">once you are used to them</span>. For me however, this was (and is) quite an adjustment. I believe the new reader will have plenty of opportunity to acclimate to this style without needing to do so while also trying to figure out what&#8217;s going on conceptually. I&#8217;m going to take care to avoid one-letter variables and abbreviations where possible.</p>
<p><span class="bold">Part 1: Companion to Chapter 5</span></p>
<p>I&#8217;m going to start with the first &#8220;real world&#8221; example in RWH, taking some time to re-explain stuff that was brought up earlier in the book as I see fit. This article will cover the definition of a datatype and implementation of accessor functions.</p>
<p><span class="bold">Onward to JSON</span></p>
<p>JSON (JavaScript Object Notation) is a mini-language designed to represent data, usually to store or transmit said data. It&#8217;s an alternative to column-based formats like CSV, and has a simple syntax. We&#8217;d like to be able to use Haskell to store data in this format, and then read it back again.</p>
<p>JSON has some notion of datatypes, based (unsurprisingly) on JavaScript&#8217;s types: strings, numbers, booleans, arrays, objects, and null.</p>
<p>It would make sense to have representations of those types in Haskell. Of course, most of them are trivial to implement, as they already exist in Haskell. We&#8217;ll make a new algebraic data type to represent any JSON type; let&#8217;s call it JsonType:</p>

<div class="wp_syntax"><div class="code"><pre class="haskell" style="font-family:monospace;"><span style="color: #06c; font-weight: bold;">data</span> JsonType <span style="color: #339933; font-weight: bold;">=</span></pre></div></div>

<p>Remember, &#8220;<span class="mono">JsonType</span>&#8221; is the <span class="italic">type constructor</span>, which will be how we refer to the type in the type signatures of functions. On the other side of the = we&#8217;ll define our <span class="italic">data constructors</span>, which is how we create <span class="mono">JsonType</span> data.</p>

<div class="wp_syntax"><div class="code"><pre class="haskell" style="font-family:monospace;"><span style="color: #06c; font-weight: bold;">data</span> JsonType <span style="color: #339933; font-weight: bold;">=</span> JsonString <span style="color: #cccc00; font-weight: bold;">String</span>
    <span style="color: #339933; font-weight: bold;">|</span> JsonNumber <span style="color: #cccc00; font-weight: bold;">Double</span>
    <span style="color: #339933; font-weight: bold;">|</span> JsonBool <span style="color: #cccc00; font-weight: bold;">Bool</span>
    <span style="color: #339933; font-weight: bold;">|</span> JsonNull</pre></div></div>

<p>We can use these data constructors like functions in order to create <span class="mono">JsonType</span> values. We can see that the first 3 constructors are just wrappers for the existing Haskell types <span class="mono">String</span>, <span class="mono">Double</span>, and <span class="mono">Bool</span>. This means we can write something like <span class="mono">JsonBool True</span> to represent the true value that would appear in a JSON file.</p>
<p><span class="bold">Why not just use the types we already have?</span></p>
<p>Types exist so that we can more exactly specify our intent, both for programmers (including ourselves), and for programming <span class="italic">tools</span> that can help prove the correctness of a given program. In C, for example, it is common to use a <span class="mono">#define</span> or an <span class="mono">enum</span> to give a name to an otherwise ambiguous value.</p>

<div class="wp_syntax"><div class="code"><pre class="c" style="font-family:monospace;"><span style="color: #339933;">#define TRUE 1</span></pre></div></div>

<p>Now we can more clearly express our intent in situations like <span class="mono">flag = TRUE</span>. This is a step in the right direction, but there is nothing stopping you from doing things like taking the square root of flag, because the name <span class="mono">TRUE</span> is really just veneer for an integer, and the compiler sees it as such.</p>
<p>We made a <span class="mono">JsonType</span> so we can distinctly operate on values associated with our task. The JSON language has strings, but does not care about the things Haskell strings/chars care about (length, case, etc.). What is significant to JSON is how they will be parsed and represented in comparison to numbers. From our standpoint, JSON&#8217;s strings and numbers are both <span class="mono">JsonType</span>s that we will write functions to work on, sharing the fact that they represent a JSON value, and notwithstanding the fact that they bear resemblance to existing Haskell types.</p>
<p>On the other hand, it would be silly to not take advantage of similar functionality that would work just as well on a <span class="mono">JsonString</span> as a Haskell <span class="mono">String</span>, if we need to. For that reason, we&#8217;ll see it is painless to &#8220;extract&#8221; the Haskell value from its <span class="mono">JsonString</span> wrapper and play with it as needed.</p>
<p><span class="bold">Compound JSON Types</span></p>
<p>We haven&#8217;t yet talked about a couple of important JSON types yet: objects and arrays. These let us describe structured data (&#8220;dictionary style,&#8221; with key-value pairs, and laundry list style, respectively). We can represent compound types in our Haskell library quite simply:</p>

<div class="wp_syntax"><div class="code"><pre class="haskell" style="font-family:monospace;"><span style="color: #5d478b; font-style: italic;">-- ...</span>
    <span style="color: #339933; font-weight: bold;">|</span> JsonArray <span style="color: green;">&#91;</span>JsonType<span style="color: green;">&#93;</span></pre></div></div>

<p>Whoa, let&#8217;s stop there already. On the surface, we&#8217;re doing the same thing as we did for <span class="mono">JsonNumber</span> and <span class="mono">JsonBool</span>: we make a data constructor, and make it take an existing Haskell type as a parameter (in this case, a list). But there&#8217;s an additional wrinkle: we need to state what kind of values this &#8220;JSONy list&#8221; should be able to hold. Well, in JSON, you can put any JSON type inside an array: a string, a boolean, even another array if you want. We need a way to express &#8220;this list can hold all JSON types.&#8221; And it just so happens we have a type that represents all JSON types, including JSON arrays themselves: <span class="mono">JsonType</span>! This is an example of a <span class="italic">recursive type definition</span>, or a type that refers to <span class="italic">itself</span> in its own definition. Don&#8217;t worry about the fact that we aren&#8217;t finished defining it yet!</p>
<p>And finally:</p>

<div class="wp_syntax"><div class="code"><pre class="haskell" style="font-family:monospace;"><span style="color: #5d478b; font-style: italic;">-- ...</span>
    <span style="color: #339933; font-weight: bold;">|</span> JsonObject <span style="color: green;">&#91;</span><span style="color: green;">&#40;</span><span style="color: #cccc00; font-weight: bold;">String</span><span style="color: #339933; font-weight: bold;">,</span> JsonType<span style="color: green;">&#41;</span><span style="color: green;">&#93;</span></pre></div></div>

<p>This is also a recursive definition, as it&#8217;s a <span class="mono">JsonType</span> that contains a <span class="mono">JsonType</span>. If you recall, comma-delimited values inside parentheses represent a tuple (a fixed-sized collection of values). Thus we&#8217;re saying a <span class="mono">JsonObject</span> is a list of pairs with a <span class="mono">String</span> key and a <span class="mono">JsonType</span> value.</p>
<p>Let&#8217;s add <span class="italic">default instances</span> to our new type&#8211;Haskell can automatically give our new type the ability to be compared, sorted, and printed. We just have to say the words!</p>

<div class="wp_syntax"><div class="code"><pre class="haskell" style="font-family:monospace;"><span style="color: #06c; font-weight: bold;">data</span> JsonType <span style="color: #339933; font-weight: bold;">=</span> JsonString <span style="color: #cccc00; font-weight: bold;">String</span>
    <span style="color: #339933; font-weight: bold;">|</span> JsonNumber <span style="color: #cccc00; font-weight: bold;">Double</span>
    <span style="color: #339933; font-weight: bold;">|</span> JsonBool <span style="color: #cccc00; font-weight: bold;">Bool</span>
    <span style="color: #339933; font-weight: bold;">|</span> JsonNull
    <span style="color: #339933; font-weight: bold;">|</span> JsonArray <span style="color: green;">&#91;</span>JsonType<span style="color: green;">&#93;</span>
    <span style="color: #339933; font-weight: bold;">|</span> JsonObject <span style="color: green;">&#91;</span><span style="color: green;">&#40;</span><span style="color: #cccc00; font-weight: bold;">String</span><span style="color: #339933; font-weight: bold;">,</span> JsonType<span style="color: green;">&#41;</span><span style="color: green;">&#93;</span>
    <span style="color: #06c; font-weight: bold;">deriving</span> <span style="color: green;">&#40;</span><span style="color: #cccc00; font-weight: bold;">Eq</span><span style="color: #339933; font-weight: bold;">,</span> <span style="color: #cccc00; font-weight: bold;">Ord</span><span style="color: #339933; font-weight: bold;">,</span> <span style="color: #cccc00; font-weight: bold;">Show</span><span style="color: green;">&#41;</span></pre></div></div>

<p>The above complete type definition is suitable for some playin&#8217; around in GHCi. Save it to a file (for example, SimpleJSON.hs) and open GHCi in the directory where you saved it. Use the <span class="mono">:load</span> command to tell it about your new definition. </p>
<p class="ghci">ghci> :load SimpleJSON<br />
[1 of 1] Compiling Main             ( SimpleJSON.hs, interpreted )<br />
Ok, modules loaded: Main.<br />
ghci> :type JsonString &#8220;hello&#8221;<br />
JsonString &#8220;hello&#8221; :: JsonType<br />
ghci> 3.1 + JsonNumber 2.2<br />
&#8230;error&#8230;
</p>
<p>The important thing to note is that using a value constructor like <span class="mono">JsonString</span> creates a value of type <span class="mono">JsonType</span>. As the programmer who wrote the type, you know that it is a thin veneer over existing Haskell types, but other programmers who use the type don&#8217;t (and shouldn&#8217;t). For example, just because you know that a <span class="mono">JsonNumber</span> is basically a <span class="mono">Double</span>, trying to treat it like one (as in the last example above) is illegal.</p>
<p><span class="bold">But um, so?</span></p>
<p>In its current form, our new type isn&#8217;t very useful; we can really only use <span class="mono">JsonType</span> values for making <span class="mono">JsonArrays</span> or <span class="mono">JsonObjects</span> (or with the automatic stuff Haskell did thanks to our deriving statement). Creating a library in Haskell (and in many languages) is a matter of creating the necessary types, and the <span class="bold">operations </span>that work on those types. That means we need to define some functions! </p>
<p>What functions do we need? Now&#8217;s a good time for a look at the Big Picture:</p>
<p><span class="bold">What is our goal?</span></p>
<p>I think it&#8217;s important to not lose focus of <span class="italic">why</span> we created <span class="mono">JsonType</span> in the midst of learning <span class="italic">how</span> to do it. So keeping in mind that our end goal is translating data to JSON and back again, it makes sense that we need some functions to help with this conversion.</p>
<p>Our <span class="mono">JsonType</span> serves as a good &#8220;programmy&#8221; representation of JSON; we can now write functions that read JSON-formatted files or streams (for example, customer order data from a website) and convert that text into Haskell by outputting <span class="mono">JsonType</span> values. Likewise, we can imagine writing functions that then extract the useful data out of <span class="mono">JsonType</span>s, for actual use (for example, in order to total up the line items of a customer&#8217;s order, we need to get the &#8220;number part&#8221; out of <span class="mono">JsonNumber</span> so we can add them). Finally, we&#8217;ll probably want a way to spit out JSON to the outside world, and we can write functions that can output JSON when given data in <span class="mono">JsonType</span> form.</p>
<p><span class="bold">Let&#8217;s put that in words. Programmy words.</span></p>
<p>A great way to write programs in a language with an expressive type system is to express our goal via &#8220;function blueprints,&#8221; if you will&#8211;just writing the type signatures without worrying about implementation yet. Let&#8217;s take a shot at it, writing types for what we outlined as desired functionality:</p>

<div class="wp_syntax"><div class="code"><pre class="haskell" style="font-family:monospace;"><span style="color: #5d478b; font-style: italic;">-- Going from real JSON to our Haskell JsonType</span>
fromJson <span style="color: #339933; font-weight: bold;">::</span> <span style="color: #cccc00; font-weight: bold;">String</span> <span style="color: #339933; font-weight: bold;">-&gt;</span> JsonType
<span style="color: #5d478b; font-style: italic;">-- Extracting actual data for manipulation</span>
extractData <span style="color: #339933; font-weight: bold;">::</span> JsonType <span style="color: #339933; font-weight: bold;">-&gt;</span> <span style="color: #339933; font-weight: bold;">??</span>
<span style="color: #5d478b; font-style: italic;">-- Saving data as JSON</span>
toJson <span style="color: #339933; font-weight: bold;">::</span> JsonType <span style="color: #339933; font-weight: bold;">-&gt;</span> <span style="color: #cccc00; font-weight: bold;">String</span></pre></div></div>

<p>Not too bad so far. We can imagine how getting <span class="mono">fromJson</span> and <span class="mono">toJson</span> will work; given a string containing JSON-formatted text, we will figure out a way to parse the text and end up with a <span class="mono">JsonType</span>. Similarly, if we have a <span class="mono">JsonType</span>, we can figure out how to print it with JSON syntax. The tricky thing to think about the type of seems to be extracting values from our new type; after all, the result could be a number of different types (a <span class="mono">Double</span>, a <span class="mono">String</span>, a list of stuff, etc.). So we&#8217;ll need to break that down more:</p>

<div class="wp_syntax"><div class="code"><pre class="haskell" style="font-family:monospace;">extractString <span style="color: #339933; font-weight: bold;">::</span> JsonType <span style="color: #339933; font-weight: bold;">-&gt;</span> <span style="color: #cccc00; font-weight: bold;">String</span>
extractDouble <span style="color: #339933; font-weight: bold;">::</span> JsonType <span style="color: #339933; font-weight: bold;">-&gt;</span> <span style="color: #cccc00; font-weight: bold;">Double</span>
extractBool   <span style="color: #339933; font-weight: bold;">::</span> JsonType <span style="color: #339933; font-weight: bold;">-&gt;</span> <span style="color: #cccc00; font-weight: bold;">Bool</span>
extractObject <span style="color: #339933; font-weight: bold;">::</span> JsonType <span style="color: #339933; font-weight: bold;">-&gt;</span> <span style="color: green;">&#91;</span><span style="color: green;">&#40;</span><span style="color: #cccc00; font-weight: bold;">String</span><span style="color: #339933; font-weight: bold;">,</span> JsonType<span style="color: green;">&#41;</span><span style="color: green;">&#93;</span>  <span style="color: #5d478b; font-style: italic;">-- Remember, &quot;object&quot; in JSON terms is a collection of key-value pairs</span>
extractArray  <span style="color: #339933; font-weight: bold;">::</span> JsonType <span style="color: #339933; font-weight: bold;">-&gt;</span> <span style="color: green;">&#91;</span>JsonType<span style="color: green;">&#93;</span>  <span style="color: #5d478b; font-style: italic;">-- Remember, we are representing a JSON array as a list</span></pre></div></div>

<p>Now we&#8217;re getting somewhere! Oh wait, we forgot one of our <span class="mono">JsonTypes</span> &#8212; <span class="mono">JsonNull</span>. Looking at our type definition, we didn&#8217;t wrap an existing Haskell type to make a <span class="mono">JsonNull</span>; &#8220;null&#8221; can really only be one thing (the absence of a value), and therefore it&#8217;s not necessary to &#8220;extract&#8221; data out of it (we&#8217;d always get the same thing!). Of course, we do need a way of telling if we are dealing with a null value:</p>

<div class="wp_syntax"><div class="code"><pre class="haskell" style="font-family:monospace;">isNull <span style="color: #339933; font-weight: bold;">::</span> JsonType <span style="color: #339933; font-weight: bold;">-&gt;</span> <span style="color: #cccc00; font-weight: bold;">Bool</span></pre></div></div>

<p><span class="bold">Why boilerplate?</span></p>
<p>Users of dynamically-typed languages are probably not excited about having to write a function for every different type that can be extracted from a <span class="mono">JsonType</span>. Haskell recognizes that dealing with types sometimes requires more typing (no pun intended), and provides a shortcut or two to help out. The primary one is via <span class="italic">record syntax</span>, which I won&#8217;t talk about here. Suffice to say it&#8217;s quite easy to have Haskell automatically create &#8220;accessor functions&#8221; like our extract functions above for a type we define. So don&#8217;t worry too much!</p>
<p><span class="bold">Implementation</span></p>
<p>Now that we&#8217;ve sketched out some functions, we can start implementing them. During this process, we might think of other functions that would be nice to have. I personally like to pretend such methods existed, then go back and implement them once I&#8217;m done with whatever I was doing.</p>
<div class="highlight"><span class="bold">Stubbing out functions</span><br />
It often happens that we want to compile our source file in order to test a particular function we&#8217;ve written. It&#8217;s probably the case that we want to do this before implementing <span class="italic">every</span> function we&#8217;ve dreamed up. We shouldn&#8217;t let unimplemented functions prevent us from a quick compile to test what we&#8217;ve already done! </p>
<p>It&#8217;s therefore useful to be able to &#8220;stub out&#8221; a function that we haven&#8217;t written yet. This is done very simply:</p>

<div class="wp_syntax"><div class="code"><pre class="haskell" style="font-family:monospace;">someFunction <span style="color: #339933; font-weight: bold;">=</span> <span style="font-weight: bold;">undefined</span></pre></div></div>

<p>You might say the special value <span class="mono">undefined</span> counts as any type, so code using it will compile even if you&#8217;ve already written the type signature for the stubbed function.
</div>
<p>Let&#8217;s start off by implementing our extractor functions, as they are straightforward. The key here is going to be <span class="italic">pattern matching</span>.</p>

<div class="wp_syntax"><div class="code"><pre class="haskell" style="font-family:monospace;">extractString <span style="color: #339933; font-weight: bold;">::</span> JsonType <span style="color: #339933; font-weight: bold;">-&gt;</span> <span style="color: #cccc00; font-weight: bold;">String</span>
extractString <span style="color: green;">&#40;</span>JsonString innerString<span style="color: green;">&#41;</span> <span style="color: #339933; font-weight: bold;">=</span> innerString</pre></div></div>

<p>Remember, when we define functions in Haskell, we can not only specify parameters, but <span class="italic">how those parameters were created</span>. Our type signature says we accept a <span class="mono">JsonType</span> parameter, and in our definition we specify a <span class="italic">pattern</span> that says specifically we want a <span class="mono">JsonType</span> that was created via the <span class="mono">JsonString</span> data constructor. That&#8217;s already cool, but furthermore it allows us to give the underlying data the type was created with a name. That is, in this case, we can now name the Haskell <span class="mono">String</span> inside the <span class="mono">JsonString</span> and use it! And use it we do&#8211;by returning it as the value of our <span class="mono">extractString</span> function.</p>
<p><span class="bold">Error handling</span></p>
<p>We just made our first accessor function by matching a <span class="mono">JsonType</span> value that was created with the <span class="mono">JsonString</span> constructor. This works fine for situations like:</p>
<p class="ghci">ghci> let valueParsed = JsonString &#8220;hello&#8221;<br />
ghci> extractString valueParsed<br />
&#8220;hello&#8221;
</p>
<p>But try this:</p>
<p class="ghci">ghci> let valueParsed = JsonNumber 23<br />
ghci> extractString valueParsed
</p>
<p>Whoops&#8211;our <span class="mono">extractString</span> function can take any sort of <span class="mono">JsonType</span>, so the above code compiles, but then it blows up when it realizes its parameter wasn&#8217;t created via the <span class="mono">JsonString</span> constructor. </p>
<p>Since our ultimate goal is to parse arbitrary JSON data, this won&#8217;t do. If <span class="mono">extractString</span> fails to parse its argument, it doesn&#8217;t mean our whole program should crash, it just means we need to try a different extractor function. So clearly we need a way of indicating failure in a less drastic way, without throwing an exception. Many languages leave how to achieve this up to you: Perhaps a special value is returned, like -1, or <span class="mono">false</span>, or <span class="mono">null</span>. Then future code has to know that special value and check for it explicitly.</p>
<p>Haskell has a nice solution to &#8220;returning <span class="mono">null</span>&#8221; that leverages the type system so there&#8217;s no guesswork in future code: we can write a function that <span class="italic">maybe</span> returns a useful value, and there&#8217;s an actual type for that! This means that code that uses the return value knows in advance that it&#8217;s only maybe going to get a useful value; it can&#8217;t blindly march forward without checking first. Hence, you&#8217;ll never run into the &#8220;null reference exception&#8221; problem that we&#8217;ve all dealt with in other languages.</p>
<p>So, how do we do this? Well, we need to find out how the <span class="mono">JsonType</span> that is passed in was created, and if it matches the <span class="mono">JsonString</span> constructor, then we return a useful value. If not, we return a failure value. Future code can then check if the failure value was returned, and if so, try a different extractor or whatever.</p>
<p><span class="bold">Ugh, does that mean boilerplate again?</span></p>
<p>We all hate writing &#8220;tests for <span class="mono">null</span>.&#8221; They are ubiquitous and as such lead to our code containing a lot of boilerplate if-statements. Fortunately, Haskell provides a neat way of hiding this particular breed of inelegance, and we will learn about it in the future. To avoid introducing too much at once, however, we&#8217;ll explicitly check for the time being.</p>
<p><span class="bold">Our extractor implementations, version 2</span></p>
<p>The type that represents &#8220;maybe a value&#8221; is called, interestingly enough, <span class="mono">Maybe</span>. <span class="mono">Maybe</span> is the name of the type constructor, just like <span class="mono">JsonType</span> is the name of our type&#8217;s type constructor. So we write our type signatures something like this:</p>

<div class="wp_syntax"><div class="code"><pre class="haskell" style="font-family:monospace;">extractString <span style="color: #339933; font-weight: bold;">::</span> JsonType <span style="color: #339933; font-weight: bold;">-&gt;</span> <span style="color: #cccc00; font-weight: bold;">Maybe</span> <span style="color: #cccc00; font-weight: bold;">String</span></pre></div></div>

<p>That reads pretty well, doesn&#8217;t it? Notice how we can still specify the type of the value that might be returned (<span class="mono">String</span> in this case). </p>
<p>Now we need to know how to create a <span class="mono">Maybe</span> value. Just like <span class="mono">JsonType</span> has a number of value constructors (<span class="mono">JsonString</span>, <span class="mono">JsonNumber</span>, etc.), <span class="mono">Maybe</span> has a couple as well. The constructor for making a value that represents &#8220;no useful value&#8221; is called <span class="mono">Nothing</span>. It&#8217;s kinda like our <span class="mono">JsonNull</span> constructor: it doesn&#8217;t wrap any other value, because there&#8217;s no value to wrap. The constructor for representing a useful value is called <span class="mono">Just</span>. <span class="mono">Just</span> takes a parameter&#8211;the value to wrap. Here is <span class="mono">Maybe</span> in action:</p>

<div class="wp_syntax"><div class="code"><pre class="haskell" style="font-family:monospace;">extractString <span style="color: #339933; font-weight: bold;">::</span> JsonType <span style="color: #339933; font-weight: bold;">-&gt;</span> <span style="color: #cccc00; font-weight: bold;">Maybe</span> <span style="color: #cccc00; font-weight: bold;">String</span>
extractString <span style="color: green;">&#40;</span>JsonString innerString<span style="color: green;">&#41;</span> <span style="color: #339933; font-weight: bold;">=</span> Just innerString
extractString somethingElse            <span style="color: #339933; font-weight: bold;">=</span> Nothing</pre></div></div>

<p>So now it looks like we have two versions of our <span class="mono">extractString</span> function, and indeed we do: one for taking <span class="mono">JsonString</span>s, and one for anything else. So if the function receives a <span class="mono">JsonString</span>, we create the &#8220;useful&#8221; <span class="mono">Maybe</span> type, wrapping the <span class="mono">String</span> we got. Otherwise, we just return <span class="mono">Nothing</span>.</p>
<p>As an (important) aside, note that we can use whatever name we want for &#8220;<span class="mono">somethingElse</span>.&#8221; This is because we aren&#8217;t trying to match an argument&#8217;s specific constructor; we&#8217;re basically just saying &#8220;match anything and give it the name <span class="mono">somethingElse</span>.&#8221; It is pointless (and can be misleading) to give a name to a value we aren&#8217;t going to use. In our extractor function, we don&#8217;t care about the value of <span class="mono">somethingElse</span>; we are simply interested in catching all values that weren&#8217;t created via <span class="mono">JsonString</span>. Therefore, Haskell programmers use the name <span class="mono">_</span> (the underscore) in cases like this. It still matches everything, but makes it clear you aren&#8217;t interested in what was matched. We&#8217;ll use the underscore from now on for this purpose.</p>
<p>The rest of our extractors are similar:</p>

<div class="wp_syntax"><div class="code"><pre class="haskell" style="font-family:monospace;">extractDouble <span style="color: green;">&#40;</span>JsonNumber number<span style="color: green;">&#41;</span> <span style="color: #339933; font-weight: bold;">=</span> Just number
extractDouble <span style="color: #339933; font-weight: bold;">_</span>                   <span style="color: #339933; font-weight: bold;">=</span> Nothing
&nbsp;
extractBool <span style="color: green;">&#40;</span>JsonBool bool<span style="color: green;">&#41;</span>       <span style="color: #339933; font-weight: bold;">=</span> Just bool
extractBool <span style="color: #339933; font-weight: bold;">_</span>                     <span style="color: #339933; font-weight: bold;">=</span> Nothing
&nbsp;
extractObject <span style="color: green;">&#40;</span>JsonObject object<span style="color: green;">&#41;</span> <span style="color: #339933; font-weight: bold;">=</span> Just object
extractObject <span style="color: #339933; font-weight: bold;">_</span>                   <span style="color: #339933; font-weight: bold;">=</span> Nothing
&nbsp;
extractArray <span style="color: green;">&#40;</span>JsonArray array<span style="color: green;">&#41;</span>    <span style="color: #339933; font-weight: bold;">=</span> Just array
extractArray <span style="color: #339933; font-weight: bold;">_</span>                    <span style="color: #339933; font-weight: bold;">=</span> Nothing</pre></div></div>

<p>We can also write our <span class="mono">isNull</span> function quite easily:</p>

<div class="wp_syntax"><div class="code"><pre class="haskell" style="font-family:monospace;">isNull jsonData <span style="color: #339933; font-weight: bold;">=</span> jsonData <span style="color: #339933; font-weight: bold;">==</span> JsonNull</pre></div></div>

<p>That was easy since Haskell figured out how to compare one <span class="mono">JsonType</span> with another automatically, because in our type declaration we told it to derive <span class="mono">Eq</span>. We&#8217;ll talk about what <span class="mono">Eq</span> is later.</p>
<p><span class="bold">Wrapping up part 1</span><br />
To review, we&#8217;ve talked about making our own types, and what a <span class="italic">type constructor</span> and <span class="italic">data constructor</span> are. We&#8217;ve talked about the value of having distinct representations of distinct entities. You should feel comfortable defining accessor functions to get at data contained in a type, and using the <span class="mono">Maybe</span> type to represent a possible lack of value. We&#8217;ll continue next time with more from RWH, chapter 5.</p>
]]></content:encoded>
			<wfw:commentRss>http://my.life-is-virtual.com/2009/10/07/fake-world-haskell-part-1/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>

