<?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; incremental-haskell</title>
	<atom:link href="http://my.life-is-virtual.com/tag/incremental-haskell/feed/" rel="self" type="application/rss+xml" />
	<link>http://my.life-is-virtual.com</link>
	<description></description>
	<lastBuildDate>Mon, 02 Nov 2009 23:30:37 +0000</lastBuildDate>
	<generator>http://wordpress.org/?v=2.8.4</generator>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
			<item>
		<title>Incremental Haskell III: Tokyo Drift</title>
		<link>http://my.life-is-virtual.com/2009/11/02/incremental-haskell-iii-tokyo-drift/</link>
		<comments>http://my.life-is-virtual.com/2009/11/02/incremental-haskell-iii-tokyo-drift/#comments</comments>
		<pubDate>Mon, 02 Nov 2009 23:30:37 +0000</pubDate>
		<dc:creator>jcooper</dc:creator>
				<category><![CDATA[Vaguely Instructional]]></category>
		<category><![CDATA[haskell]]></category>
		<category><![CDATA[incremental-haskell]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[tutorial]]></category>

		<guid isPermaLink="false">http://my.life-is-virtual.com/?p=110</guid>
		<description><![CDATA[Prelude
This is part 3 in a series of articles designed to help those new to Haskell work through the highly-recommended book, Real World Haskell. In them, I try to keep things at a digestible pace and not to presuppose too much. Here are links to the previous articles. I hope you find these helpful, and [...]]]></description>
			<content:encoded><![CDATA[<p><span class="bold">Prelude</span></p>
<p><span class="italic">This is part 3 in a series of articles designed to help those new to Haskell work through the highly-recommended book, <a href="http://book.realworldhaskell.org/">Real World Haskell</a>. In them, I try to keep things at a digestible pace and not to presuppose too much. Here are links to the <a href="http://my.life-is-virtual.com/2009/10/07/fake-world-haskell-part-1/">previous</a> <a href="http://my.life-is-virtual.com/2009/10/13/incremental-haskell-part-2/">articles</a>. I hope you find these helpful, and welcome comments on the Haskell subreddit.</span></p>
<p><span class="bold">Mo&#8217; problems, mo types</span></p>
<p>As we mentioned in the previous article, it would be nice to be able to customize our JSON output. Right now, we have a default implementation of printing output that isn&#8217;t very flexible, not supporting things like &#8220;word wrapping&#8221; (soft line breaks).</p>
<p>Certainly, being able to format output text in a flexible manner is not a problem specific to JSON (though that will be our current application of it). Because it&#8217;s a new &#8220;problem to solve,&#8221; we&#8217;ll start from the top with a new type. We want to represent a chunk of text that can be formatted.</p>

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

<p>The simplest type of formatting is no formatting at all (just like momma always said).</p>

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

<p>We want the ability to break text over more than one line if it&#8217;s too wide. We&#8217;ll add a data constructor to our type that represents these line breaks. Then when we go to render the text, when we match this constructor, we can go to the next line.</p>

<div class="wp_syntax"><div class="code"><pre class="haskell" style="font-family:monospace;"><span style="color: #06c; font-weight: bold;">data</span> FormattedText <span style="color: #339933; font-weight: bold;">=</span>  Text <span style="color: #cccc00; font-weight: bold;">String</span>
                    <span style="color: #339933; font-weight: bold;">|</span> Linebreak</pre></div></div>

<p>We also want to support a soft line break, which will be a space character if we aren&#8217;t out of space on a line, or a newline otherwise. So we&#8217;ll make a <span class="mono">WithOptionalBreaks</span> data constructor to represent this.</p>

<div class="wp_syntax"><div class="code"><pre class="haskell" style="font-family:monospace;"><span style="color: #06c; font-weight: bold;">data</span> FormattedText <span style="color: #339933; font-weight: bold;">=</span>  Text <span style="color: #cccc00; font-weight: bold;">String</span>
                    <span style="color: #339933; font-weight: bold;">|</span> Linebreak
                    <span style="color: #339933; font-weight: bold;">|</span> WithOptionalBreaks FormattedText FormattedText</pre></div></div>

<p>As you can imagine, a real document (JSON or otherwise) is going to consist of chunks of text combined together. Some chunks will have different formatting than others, but together they make up a whole document of formatted text, which we can call a formatted document. And since a formatted document is just formatted text, if we combine it with more formatted text, we still have a formatted document. I hope that makes sense, even if it does involve some &#8220;recursive thinking.&#8221; The concept translates very well into Haskell:</p>

<div class="wp_syntax"><div class="code"><pre class="haskell" style="font-family:monospace;"><span style="color: #06c; font-weight: bold;">data</span> FormattedText <span style="color: #339933; font-weight: bold;">=</span>  Text <span style="color: #cccc00; font-weight: bold;">String</span>
                    <span style="color: #339933; font-weight: bold;">|</span> Linebreak
                    <span style="color: #339933; font-weight: bold;">|</span> WithOptionalBreaks FormattedText FormattedText
                    <span style="color: #339933; font-weight: bold;">|</span> FormattedDocument FormattedText FormattedText</pre></div></div>

<p>That is, we represent a whole document as two chunks of <span class="mono">FormattedText</span>, which can include plain <span class="mono">Text</span>, <span class="mono">Linebreak</span>s, even other <span class="mono">FormattedDocument</span>s that are themselves made up of the same thing. If you know anything about data structures, you&#8217;ll recognize a tree structure here.</p>
<p><span class="bold">Defining custom operators in Haskell</span></p>
<p>Almost every language has <span class="italic">operators</span>, which give abstract symbols meaning to make certain expressions read more smoothly. Of course, this concept originally comes from mathematics, where being able to tersely express things is important.</p>
<p>Languages with operators tend to at least include ASCII equivalents of the basic arithmetic symbols like <span class="mono">+</span> and <span class="mono">-</span>. Some language designers decided to &#8220;overload&#8221; operators, giving them different meanings depending on context. In Java, for example, you concatenate strings thus:</p>

<div class="wp_syntax"><div class="code"><pre class="java" style="font-family:monospace;"><span style="color: #003399;">String</span> newString <span style="color: #339933;">=</span> <span style="color: #0000ff;">&quot;hello &quot;</span> <span style="color: #339933;">+</span> <span style="color: #0000ff;">&quot;world&quot;</span><span style="color: #339933;">;</span></pre></div></div>

<p>Most people tend to be in favor of operators; having to write <span class="mono">Plus(1, 3)</span> every time you wanted to add 1 and 3 isn&#8217;t quite as convenient, and one could argue less readily apparent. Not everyone is in agreement on operator <span class="italic">overloading</span>, however, as it can introduce ambiguity when one symbol has more than one meaning.</p>
<p>Haskell programmers are big fans of operators. I&#8217;m sure this has a lot to do with the math culture that is quite prevalent in the community and user base. Haskell and its community are quite bold in using abstract concepts in everyday code, and often it makes more sense to define an operator than give an otherwise inadequate name to a function.  </p>
<p>The language lets you define your own operators, including precedence. Functions that you name using only non-alphanumeric symbols are automatically considered operators and can be used just like you&#8217;d use <span class="mono">+</span> or <span class="mono">-</span>. Just like functions, operator names need to be unique and there is no overloading allowed (in the traditional sense). That is, you don&#8217;t see <span class="mono">1 + 1</span> on one line and <span class="mono">&#8220;hello &#8221; + &#8220;world&#8221;</span> on the next. The <span class="mono">(+)</span> function is coded to accept only numeric inputs, and so there wouldn&#8217;t be a way to add <span class="mono">String</span>s with <span class="mono">(+)</span> without <span class="mono">String</span> being numeric.</p>
<p><span class="bold">So what&#8217;s that have to do with what we&#8217;re doing?</span></p>
<p>The type we just wrote is perfectly suited to having a custom operator or two to help us out. Right now, if we want to build a document up out of text chunks, we have to do something like this:</p>

<div class="wp_syntax"><div class="code"><pre class="haskell" style="font-family:monospace;">FormattedDocument <span style="color: green;">&#40;</span>Text <span style="color: #3366CC;">&quot;hi&quot;</span><span style="color: green;">&#41;</span> <span style="color: green;">&#40;</span>FormattedDocument <span style="color: green;">&#40;</span>Text <span style="color: #3366CC;">&quot;howdy&quot;</span><span style="color: green;">&#41;</span> <span style="color: green;">&#40;</span>Text <span style="color: #3366CC;">&quot;hello&quot;</span><span style="color: green;">&#41;</span><span style="color: green;">&#41;</span></pre></div></div>

<p>We can quickly and easily define an operator that makes the concept of combining text more palatable:</p>

<div class="wp_syntax"><div class="code"><pre class="haskell" style="font-family:monospace;"><span style="color: green;">&#40;</span><span style="color: #339933; font-weight: bold;">&lt;++&gt;</span><span style="color: green;">&#41;</span> <span style="color: #339933; font-weight: bold;">::</span> FormattedText <span style="color: #339933; font-weight: bold;">-&gt;</span> FormattedText <span style="color: #339933; font-weight: bold;">-&gt;</span> FormattedText
textChunk <span style="color: #339933; font-weight: bold;">&lt;++&gt;</span> anotherChunk <span style="color: #339933; font-weight: bold;">=</span> FormattedDocument textChunk anotherChunk</pre></div></div>

<p>Since <span class="mono">FormattedText</span> concatenation is conceptually kinda like <span class="mono">String</span> concatenation, I chose an operator that looks like <span class="mono">(++)</span>.</p>
<p>Now we can avoid &#8220;parentheses nesting hell&#8221;:</p>

<div class="wp_syntax"><div class="code"><pre class="haskell" style="font-family:monospace;">Text <span style="color: #3366CC;">&quot;Knights &quot;</span> <span style="color: #339933; font-weight: bold;">&lt;++&gt;</span> Text <span style="color: #3366CC;">&quot;who say&quot;</span> <span style="color: #339933; font-weight: bold;">&lt;++&gt;</span> Linebreak <span style="color: #339933; font-weight: bold;">&lt;++&gt;</span> Text <span style="color: #3366CC;">&quot;ni&quot;</span></pre></div></div>

<p>As you can see above, we can add text to other text, and add line breaks where we want. We can use this same approach for our optional line breaks. Let&#8217;s make another operator that represents a possible breaking spot in a line:</p>

<div class="wp_syntax"><div class="code"><pre class="haskell" style="font-family:monospace;"><span style="color: green;">&#40;</span><span style="color: #339933; font-weight: bold;">&lt;/&gt;</span><span style="color: green;">&#41;</span> <span style="color: #339933; font-weight: bold;">::</span> FormattedText <span style="color: #339933; font-weight: bold;">-&gt;</span> FormattedText <span style="color: #339933; font-weight: bold;">-&gt;</span> FormattedText
textChunk <span style="color: #339933; font-weight: bold;">&lt;/&gt;</span> anotherChunk <span style="color: #339933; font-weight: bold;">=</span> textChunk <span style="color: #339933; font-weight: bold;">&lt;++&gt;</span> softLineBreak <span style="color: #339933; font-weight: bold;">&lt;++&gt;</span> anotherChunk</pre></div></div>

<p>So when we <span class="mono"></></span> two pieces of text, we join them together with a soft line break&#8211;the kind that ends up being a newline if <span class="mono">anotherChunk</span> didn&#8217;t fit on the current line. Otherwise, it&#8217;ll just become a space.</p>
<p>Our <span class="mono">WithOptionalBreaks</span> constructor handles these two possibilities (break or just space) for us:</p>

<div class="wp_syntax"><div class="code"><pre class="haskell" style="font-family:monospace;">softLineBreak <span style="color: #339933; font-weight: bold;">=</span> WithOptionalBreaks <span style="color: green;">&#40;</span>Text <span style="color: #3366CC;">&quot; &quot;</span><span style="color: green;">&#41;</span> <span style="color: green;">&#40;</span>Linebreak<span style="color: green;">&#41;</span></pre></div></div>

<p><span class="bold">Back to rendering JSON</span></p>
<p>Now that we have our type and the ability to combine values of our type, let&#8217;s take a look at how we&#8217;ll use it to &#8220;pretty print&#8221; a JSON string value. This isn&#8217;t quite as trivial as it sounds because we need to pay attention to characters in the string that need to be escaped with backslashes.</p>

<div class="wp_syntax"><div class="code"><pre class="haskell" style="font-family:monospace;">renderJsonString <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> FormattedText
renderJsonString string <span style="color: #339933; font-weight: bold;">=</span> Text <span style="color: #3366CC;">&quot;<span style="background-color: #3cb371; font-weight: bold;">\&quot;</span>&quot;</span> <span style="color: #339933; font-weight: bold;">&lt;++&gt;</span> Text <span style="color: green;">&#40;</span>escapeChars string<span style="color: green;">&#41;</span> <span style="color: #339933; font-weight: bold;">&lt;++&gt;</span> Text <span style="color: #3366CC;">&quot;<span style="background-color: #3cb371; font-weight: bold;">\&quot;</span>&quot;</span>
    <span style="color: #06c; font-weight: bold;">where</span> escapeChars chars <span style="color: #339933; font-weight: bold;">=</span> <span style="font-weight: bold;">concatMap</span> escapeChar chars
          escapeChar char   <span style="color: #339933; font-weight: bold;">=</span> <span style="color: #5d478b; font-style: italic;">-- ??</span></pre></div></div>

<p>We&#8217;re breaking the problem into chunks, keeping individual functions small. Our main function, <span class="mono">renderJsonString</span>, just surrounds the string in quotation marks, and then calls a helper function <span class="mono">escapeChars</span> on the string. <span class="mono">escapeChars</span>, in turn, is going to <span class="mono">concatMap</span> an escape function over each individual character in the string. </p>
<p>In case you still aren&#8217;t used to the <span class="mono">map</span> family of functions yet, they&#8217;re the ones that pass each element of a provided list to a specified function. A new list is returned containing the results of each function application. In this case, each result is going to be a <span class="mono">String</span> (which, don&#8217;t forget, is just a <span class="mono">[Char]</span>). We only want one <span class="mono">String</span> out of our <span class="mono">escapeChars</span> function, so we use the <span class="mono">concatMap</span> version of <span class="mono">map</span>. It just smooshes all the results together, which is great for scenarios like this.</p>
<div class="highlight"><span class="bold">On patterns that need to be matched</span></p>
<p>In the previous installment, we talked about covering all our bases when pattern matching. If you are matching against a <span class="mono">Maybe</span>, it&#8217;s a good idea to think about what happens if the value is <span class="mono">Nothing</span> as well as if it is <span class="mono">Just something</span>. If our input is a list, what if it&#8217;s empty?</p>
<p>These are great things to think about to avoid errors. However, Haskell programmers feel very passionate about avoiding redundant code, so it&#8217;s okay to avoid special-casing a pattern if we won&#8217;t gain anything by it. The <span class="mono">escapeChars</span> function above is a good example, as it takes a list. We could have done the following:</p>

<div class="wp_syntax"><div class="code"><pre class="haskell" style="font-family:monospace;">escapeChars <span style="color: green;">&#91;</span><span style="color: green;">&#93;</span> <span style="color: #339933; font-weight: bold;">=</span> <span style="color: #3366CC;">&quot;&quot;</span>
escapeChars chars <span style="color: #339933; font-weight: bold;">=</span> <span style="font-weight: bold;">concatMap</span> escapeChar chars</pre></div></div>

<p>But actually we don&#8217;t need to, because <span class="mono">concatMap</span> already handles the empty list case for us in the same way! (If the list passed to <span class="mono">concatMap</span> is empty, it returns an empty list. In Haskell this looks like:)</p>

<div class="wp_syntax"><div class="code"><pre class="haskell" style="font-family:monospace;"><span style="font-weight: bold;">concatMap</span> <span style="color: #339933; font-weight: bold;">_</span> <span style="color: green;">&#91;</span><span style="color: green;">&#93;</span> <span style="color: #339933; font-weight: bold;">=</span> <span style="color: green;">&#91;</span><span style="color: green;">&#93;</span></pre></div></div>

<p>(Remember, the underscore pattern is used when we don&#8217;t care about the value of an argument. In this case, it doesn&#8217;t matter what function is passed to <span class="mono">concatMap</span>, if the list is empty, it just returns <span class="mono">[]</span>.)
</div>
<p><span class="bold">Escaping special characters</span></p>
<p>Our <span class="mono">escapeChar</span> function will take a character from a string, find out if it needs to be escaped, and if so, return an escaped version. Otherwise it&#8217;ll just return the character.</p>

<div class="wp_syntax"><div class="code"><pre class="haskell" style="font-family:monospace;"><span style="color: #5d478b; font-style: italic;">-- ...</span>
          escapeChar char   <span style="color: #339933; font-weight: bold;">=</span> <span style="color: #06c; font-weight: bold;">case</span> <span style="font-weight: bold;">lookup</span> char asciiEscapeTable <span style="color: #06c; font-weight: bold;">of</span>
                                Just escaped <span style="color: #339933; font-weight: bold;">-&gt;</span> escaped
                                Nothing      <span style="color: #339933; font-weight: bold;">-&gt;</span> <span style="color: #5d478b; font-style: italic;">-- ??</span></pre></div></div>

<p>Here, we are pattern matching the result of our check. The check is done with the <span class="mono">lookup</span> function, a standard library function which searches a list of key-value pairs for a given key (in our case, the character we&#8217;re checking). Since <span class="mono">lookup</span> returns <span class="mono">Maybe</span> a result, we match against <span class="mono">Just</span> (meaning the character was found in the list of characters-needing-escape) and <span class="mono">Nothing</span>. For the first case, we grab the escaped string and return it.</p>
<p>Our list of escaped characters, <span class="mono">asciiEscapeTable</span>, contains the most common escape sequences. We will build it by feeding a table-creation function two lists: a list of characters that need escaping, and a list of their escaped versions.</p>

<div class="wp_syntax"><div class="code"><pre class="haskell" style="font-family:monospace;">asciiEscapeTable <span style="color: #339933; font-weight: bold;">::</span> <span style="color: green;">&#91;</span><span style="color: green;">&#40;</span><span style="color: #cccc00; font-weight: bold;">Char</span><span style="color: #339933; font-weight: bold;">,</span> <span style="color: #cccc00; font-weight: bold;">String</span><span style="color: green;">&#41;</span><span style="color: green;">&#93;</span>  <span style="color: #5d478b; font-style: italic;">-- a list of key-value pairs, commonly called an 'association list'</span>
asciiEscapeTable <span style="color: #339933; font-weight: bold;">=</span> mysteryTableMakerFunction <span style="color: green;">&#91;</span>'\b'<span style="color: #339933; font-weight: bold;">,</span>'\n'<span style="color: #339933; font-weight: bold;">,</span>'\f'<span style="color: #339933; font-weight: bold;">,</span>'\r'<span style="color: #339933; font-weight: bold;">,</span>'\t'<span style="color: #339933; font-weight: bold;">,</span>'\\'<span style="color: #339933; font-weight: bold;">,</span>'<span style="color: #3366CC;">&quot;','/'] [&quot;</span>\\b<span style="color: #3366CC;">&quot;,&quot;</span>\\n<span style="color: #3366CC;">&quot;,&quot;</span>\\f<span style="color: #3366CC;">&quot;,&quot;</span>\\r<span style="color: #3366CC;">&quot;,&quot;</span>\\t<span style="color: #3366CC;">&quot;,&quot;</span>\\\\<span style="color: #3366CC;">&quot;,&quot;</span>\\\<span style="color: #3366CC;">&quot;&quot;</span><span style="color: #339933; font-weight: bold;">,</span><span style="color: #3366CC;">&quot;<span style="background-color: #3cb371; font-weight: bold;">\\</span>/&quot;</span><span style="color: green;">&#93;</span></pre></div></div>

<p>So far, so good&#8211;assuming we can find a function that takes two lists and makes one list of pairs out of them (sequentially pairing one element from the first list with one from the second). If we think about what the type of such a function would be, we come up with:</p>

<div class="wp_syntax"><div class="code"><pre class="haskell" style="font-family:monospace;"><span style="color: green;">&#91;</span>a<span style="color: green;">&#93;</span> <span style="color: #339933; font-weight: bold;">-&gt;</span> <span style="color: green;">&#91;</span>b<span style="color: green;">&#93;</span> <span style="color: #339933; font-weight: bold;">-&gt;</span> <span style="color: green;">&#91;</span><span style="color: green;">&#40;</span>a<span style="color: #339933; font-weight: bold;">,</span> b<span style="color: green;">&#41;</span><span style="color: green;">&#93;</span></pre></div></div>

<p>Remember <a href="http://www.haskell.org/hoogle/">Hoogle</a>? If we go there and search for a function with that type, it tells us straight away that the function we want is called <span class="mono">zip</span>, and it&#8217;s in the Prelude so we don&#8217;t even need to import it. (In fact, <span class="mono">zip</span> is a common functional programming building block.)</p>

<div class="wp_syntax"><div class="code"><pre class="haskell" style="font-family:monospace;">asciiEscapeTable <span style="color: #339933; font-weight: bold;">=</span> <span style="font-weight: bold;">zip</span> <span style="color: green;">&#91;</span>'\b'<span style="color: #339933; font-weight: bold;">,</span>'\n'<span style="color: #339933; font-weight: bold;">,</span>'\f'<span style="color: #339933; font-weight: bold;">,</span>'\r'<span style="color: #339933; font-weight: bold;">,</span>'\t'<span style="color: #339933; font-weight: bold;">,</span>'\\'<span style="color: #339933; font-weight: bold;">,</span>'<span style="color: #3366CC;">&quot;','/'] [&quot;</span>\\b<span style="color: #3366CC;">&quot;,&quot;</span>\\n<span style="color: #3366CC;">&quot;,&quot;</span>\\f<span style="color: #3366CC;">&quot;,&quot;</span>\\r<span style="color: #3366CC;">&quot;,&quot;</span>\\t<span style="color: #3366CC;">&quot;,&quot;</span>\\\\<span style="color: #3366CC;">&quot;,&quot;</span>\\\<span style="color: #3366CC;">&quot;&quot;</span><span style="color: #339933; font-weight: bold;">,</span><span style="color: #3366CC;">&quot;<span style="background-color: #3cb371; font-weight: bold;">\\</span>/&quot;</span><span style="color: green;">&#93;</span></pre></div></div>

<div class="highlight"><span class="bold">But hey, lists of <span class="mono">Char</span>s are <span class="mono">String</span>s, you tell us that all the time. And all our escapes are done with backslashes!</span></p>
<p>Very true. Using those facts, we can write a version that&#8217;s easier to type, if we want:</p>

<div class="wp_syntax"><div class="code"><pre class="haskell" style="font-family:monospace;">asciiEscapeTable <span style="color: #339933; font-weight: bold;">=</span> <span style="font-weight: bold;">zipWith</span> addBackslash <span style="color: #3366CC;">&quot;<span style="background-color: #3cb371; font-weight: bold;">\b</span><span style="background-color: #3cb371; font-weight: bold;">\n</span><span style="background-color: #3cb371; font-weight: bold;">\f</span><span style="background-color: #3cb371; font-weight: bold;">\r</span><span style="background-color: #3cb371; font-weight: bold;">\t</span><span style="background-color: #3cb371; font-weight: bold;">\\</span><span style="background-color: #3cb371; font-weight: bold;">\&quot;</span>/&quot;</span> <span style="color: #3366CC;">&quot;bnfrt<span style="background-color: #3cb371; font-weight: bold;">\\</span><span style="background-color: #3cb371; font-weight: bold;">\&quot;</span>/&quot;</span>
    <span style="color: #06c; font-weight: bold;">where</span> addBackslash input output <span style="color: #339933; font-weight: bold;">=</span> <span style="color: green;">&#40;</span>input<span style="color: #339933; font-weight: bold;">,</span> <span style="color: green;">&#91;</span>'\\'<span style="color: #339933; font-weight: bold;">,</span> output<span style="color: green;">&#93;</span><span style="color: green;">&#41;</span></pre></div></div>

<p>The <span class="mono">zipWith</span> function lets us apply a helper function before it combines the pair into a list element. We use it to simply prepend a backslash to every element of our output list.
</div>
<p><span class="bold">And if the lookup returns <span class="mono">Nothing</span>?</span></p>
<p>Unfortunately, we aren&#8217;t done yet. We can&#8217;t just return the character because it might be a Unicode character that requires escaping, and our nice little escape table earlier was ASCII only. So we need another check to see if this is the case:</p>

<div class="wp_syntax"><div class="code"><pre class="haskell" style="font-family:monospace;"><span style="color: #5d478b; font-style: italic;">-- ...</span>
                                Nothing <span style="color: #339933; font-weight: bold;">|</span> needsUnicodeEscape char <span style="color: #339933; font-weight: bold;">-&gt;</span> unicodeEscape char
                                        <span style="color: #339933; font-weight: bold;">|</span> <span style="font-weight: bold;">otherwise</span>               <span style="color: #339933; font-weight: bold;">-&gt;</span> <span style="color: green;">&#91;</span>char<span style="color: green;">&#93;</span>
&nbsp;
needsUnicodeEscape <span style="color: #339933; font-weight: bold;">::</span> <span style="color: #cccc00; font-weight: bold;">Char</span> <span style="color: #339933; font-weight: bold;">-&gt;</span> <span style="color: #cccc00; font-weight: bold;">Bool</span>
needsUnicodeEscape char <span style="color: #339933; font-weight: bold;">=</span> char <span style="color: #339933; font-weight: bold;">&lt;</span> ' ' <span style="color: #339933; font-weight: bold;">||</span> char <span style="color: #339933; font-weight: bold;">==</span> '\x7f' <span style="color: #5d478b; font-style: italic;">{-- ASCII 'del' --}</span> <span style="color: #339933; font-weight: bold;">||</span> char <span style="color: #339933; font-weight: bold;">&gt;</span> '\xff'</pre></div></div>

<p>So we changed the second pattern in our case statement to be more specific, using <span class="italic">guards</span>. Guards allow you to specify further conditions on a pattern match. Our first guard does a check to see if we need to escape the character in a more complex way (using RWH&#8217;s choice of escaping all non-printable ASCII characters). The other guard, the <span class="mono">otherwise</span>, just returns the character because it means it doesn&#8217;t need escaping. (We made a singleton list out of <span class="mono">char</span> because the other branches of the statement are returning a <span class="mono">String</span>, not just a single <span class="mono">Char</span>, and we need to be consistent.)</p>
<p>Now we need to write our <span class="mono">unicodeEscape</span> function. To do this, we need to turn the character into a string representing its numeric Unicode value. This means a backslash, a <span class="mono">u</span>, and a four-digit hex string. (The JSON standard requires this format.)</p>

<div class="wp_syntax"><div class="code"><pre class="haskell" style="font-family:monospace;">unicodeEscape <span style="color: #339933; font-weight: bold;">::</span> <span style="color: #cccc00; font-weight: bold;">Char</span> <span style="color: #339933; font-weight: bold;">-&gt;</span> <span style="color: #cccc00; font-weight: bold;">String</span>
unicodeEscape char <span style="color: #339933; font-weight: bold;">=</span> <span style="color: #3366CC;">&quot;<span style="background-color: #3cb371; font-weight: bold;">\\</span>u&quot;</span> <span style="color: #339933; font-weight: bold;">++</span> padWithZeroes <span style="color: green;">&#40;</span>toHex char<span style="color: green;">&#41;</span>
    <span style="color: #06c; font-weight: bold;">where</span> padWithZeroes string <span style="color: #339933; font-weight: bold;">=</span> <span style="color: #5d478b; font-style: italic;">-- ??</span>
          toHex char <span style="color: #339933; font-weight: bold;">=</span> <span style="color: #5d478b; font-style: italic;">-- ??</span></pre></div></div>

<p>We need to ensure our hex value is four digits, so we&#8217;ll pad it with zeroes if necessary. This means finding out the length of our hex, and throwing a <span class="mono">0</span> in front for each place less than four. </p>
<p>To help us, we&#8217;ll use a handy little function called <span class="mono">replicate</span> that (as you&#8217;d expect) replicates its argument. You specify how many times it should do this.</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: #06c; font-weight: bold;">where</span> padWithZeroes string <span style="color: #339933; font-weight: bold;">=</span> replicate <span style="color: green;">&#40;</span><span style="color: red;">4</span> <span style="color: #339933; font-weight: bold;">-</span> <span style="font-weight: bold;">length</span> string<span style="color: green;">&#41;</span> '<span style="color: red;">0</span>' <span style="color: #339933; font-weight: bold;">++</span> string</pre></div></div>

<p>In order to convert a character to its hex value, we first need to get a numeric value of the <span class="mono">Char</span>. Hoogle can help us if we search for the type signature of such a function (that is, <span class="mono">Char -> Int</span>). The result that suits our needs is <span class="mono">ord</span>, in <span class="mono">Data.Char</span> (it gives the <span class="italic">ord</span>inal value of a character). We then need to turn our numeric value into a hex string. The <span class="mono">Numeric</span> module provides such a function: <span class="mono">showHex</span>. If we import the <span class="mono">Numeric</span> and <span class="mono">Data.Char</span> modules at the top of our file, we can finish up our <span class="mono">toHex</span> function snappily:</p>

<div class="wp_syntax"><div class="code"><pre class="haskell" style="font-family:monospace;"><span style="color: #5d478b; font-style: italic;">-- ...</span>
          toHex char <span style="color: #339933; font-weight: bold;">=</span> showHex <span style="color: green;">&#40;</span>ord char<span style="color: green;">&#41;</span> <span style="color: #3366CC;">&quot;&quot;</span></pre></div></div>

<p>(<span class="mono">showHex</span> actually takes another argument after the input number&#8211;a <span class="mono">String</span>. This has uses, but we won&#8217;t bother with it here, so we just feed it an empty string.)</p>
<div class="highlight"><span class="bold">A note on correctness</span></p>
<p>Though our function is pretty good, Unicode values actually go up higher than the JSON &#8220;\uxxxx&#8221; syntax allows. The standard describes how to express characters that have values higher than four digits. RWH has already implemented this; look for the <span class="mono">astral</span> function in chapter 5. Feel free to incorporate it if you want!
</div>
<p><span class="bold">Now to pretty printing!</span></p>
<p>Now that we have our string rendering, we&#8217;re ready to get on to flexible output formatting. We&#8217;ll start with a type signature:</p>

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

<p>The <span class="mono">Int</span> parameter will represent the maximum width of a line. Remember our soft line breaks? If one of those occurs in our text, we can use this width information to determine whether or not to begin a new line. </p>
<p>Our implementation will use the different constructors we defined for <span class="mono">FormattedText</span> to our advantage: we&#8217;ll use them as instructions about how to print.</p>

<div class="wp_syntax"><div class="code"><pre class="haskell" style="font-family:monospace;">printWithWidth width formattedText <span style="color: #339933; font-weight: bold;">=</span> processText <span style="color: red;">0</span> <span style="color: green;">&#91;</span>formattedText<span style="color: green;">&#93;</span>
    <span style="color: #06c; font-weight: bold;">where</span>   processText column <span style="color: green;">&#40;</span>textChunk : remainingText<span style="color: green;">&#41;</span> <span style="color: #339933; font-weight: bold;">=</span>
                        <span style="color: #06c; font-weight: bold;">case</span> textChunk <span style="color: #06c; font-weight: bold;">of</span>
                            Text string                     <span style="color: #339933; font-weight: bold;">-&gt;</span> string <span style="color: #339933; font-weight: bold;">++</span> processText <span style="color: green;">&#40;</span>column <span style="color: #339933; font-weight: bold;">+</span> <span style="font-weight: bold;">length</span> string<span style="color: green;">&#41;</span> remainingText
                            Linebreak                       <span style="color: #339933; font-weight: bold;">-&gt;</span> '\n' : processText <span style="color: red;">0</span> remainingText
                            FormattedDocument part1 part2   <span style="color: #339933; font-weight: bold;">-&gt;</span> processText column <span style="color: green;">&#40;</span>part1 : part2 : remainingText<span style="color: green;">&#41;</span>
                            WithOptionalBreaks noBr withBr  <span style="color: #339933; font-weight: bold;">-&gt;</span> nicestFit column <span style="color: green;">&#40;</span>processText column <span style="color: green;">&#40;</span>noBr : remainingText<span style="color: green;">&#41;</span><span style="color: green;">&#41;</span>
                                                                                <span style="color: green;">&#40;</span>processText column <span style="color: green;">&#40;</span>withBr : remainingText<span style="color: green;">&#41;</span><span style="color: green;">&#41;</span>
            processText <span style="color: #339933; font-weight: bold;">_</span> <span style="color: #339933; font-weight: bold;">_</span> <span style="color: #339933; font-weight: bold;">=</span> <span style="color: #3366CC;">&quot;&quot;</span></pre></div></div>

<p>A line-by-line explanation might help. </p>
<p>Right away, we pass column number <span class="mono">0</span> and a list containing what our function was passed to a helper function. Then we define said helper function, and have it match against every possible sort of <span class="mono">FormattedText</span>. The <span class="mono">column</span> variable will track our current position in a line. So when <span class="mono">processText</span> gets a string of <span class="mono">Text</span>, it increments the <span class="mono">column</span> variable by the length of the string and emits the string. When it gets a <span class="mono">Linebreak</span>, it emits a newline character, and resets the <span class="mono">column</span> count because we&#8217;re now on a fresh line. In both cases, we recursively continue processing the <span class="mono">[formattedText]</span> list.</p>
<p><span class="bold">But that list only has one element, right?</span></p>
<p>Well yes, at the start. But if we pass in a <span class="mono">FormattedDocument</span> (which as you remember, contains other <span class="mono">FormattedText</span>s), we grow our <span class="mono">remainingText</span> list by prepending both halves of the document &#8220;tree.&#8221; This action in and of itself doesn&#8217;t move our column position on the line; the recursive call to <span class="mono">processText</span> will take care of that later.  </p>
<p><span class="bold">The most interesting piece</span></p>
<p>Remember we made the <span class="mono">WithOptionalBreaks</span> constructor to hold the two versions of a soft line break: the space version, and the newline version. The reason we did this will now become clear. What we&#8217;re going to do with our <span class="mono">nicestFit</span> function is compare the lengths of those two versions of text based on what column position we&#8217;re on in the line. If the &#8220;no breaks&#8221; version would be too long, we&#8217;ll emit the version with line breaks.</p>

<div class="wp_syntax"><div class="code"><pre class="haskell" style="font-family:monospace;"><span style="color: #5d478b; font-style: italic;">-- ...</span>
            nicestFit column version1 version2 <span style="color: #339933; font-weight: bold;">=</span> <span style="color: #06c; font-weight: bold;">if</span> version1 `fitsIn` spaceRemaining
                                                 <span style="color: #06c; font-weight: bold;">then</span> version1
                                                 <span style="color: #06c; font-weight: bold;">else</span> version2
                        <span style="color: #06c; font-weight: bold;">where</span> spaceRemaining <span style="color: #339933; font-weight: bold;">=</span> width <span style="color: #339933; font-weight: bold;">-</span> <span style="color: green;">&#40;</span><span style="font-weight: bold;">min</span> width column<span style="color: green;">&#41;</span>
&nbsp;
fitsIn <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> <span style="color: #cccc00; font-weight: bold;">Int</span> <span style="color: #339933; font-weight: bold;">-&gt;</span> <span style="color: #cccc00; font-weight: bold;">Bool</span>
<span style="color: #339933; font-weight: bold;">_</span>              `fitsIn` remainingWidth <span style="color: #339933; font-weight: bold;">|</span> remainingWidth <span style="color: #339933; font-weight: bold;">&lt;</span> <span style="color: red;">0</span> <span style="color: #339933; font-weight: bold;">=</span> False
<span style="color: #3366CC;">&quot;&quot;</span>             `fitsIn` remainingWidth                      <span style="color: #339933; font-weight: bold;">=</span> True
<span style="color: green;">&#40;</span>'\n':<span style="color: #339933; font-weight: bold;">_</span><span style="color: green;">&#41;</span>       `fitsIn` remainingWidth                      <span style="color: #339933; font-weight: bold;">=</span> True
<span style="color: green;">&#40;</span>char : chars<span style="color: green;">&#41;</span> `fitsIn` remainingWidth                      <span style="color: #339933; font-weight: bold;">=</span> chars `fitsIn` <span style="color: green;">&#40;</span>remainingWidth <span style="color: #339933; font-weight: bold;">-</span> <span style="color: red;">1</span><span style="color: green;">&#41;</span></pre></div></div>

<p>Hopefully those two functions are pretty straightforward. Hitting our <span class="mono">WithOptionalBreaks</span> constructor causes our <span class="mono">nicestFit</span> function to test both the versions it contains by seeing if there&#8217;s enough space for the &#8220;no breaks&#8221; version. It does this by testing one character at a time vs. the remaining width on the line. If we get to the end of the string (<span class="mono">&#8220;&#8221;</span>) or a newline, it fits. Otherwise we return <span class="mono">False</span>, which means we&#8217;ll emit the version with line breaks.</p>
<div class="highlight"><span class="bold">A side note on self-instruction</span></p>
<p>Though once you are used to it, you&#8217;ll be able to instantly figure out what recursive functions like the ones above do, you might becoming from an imperative language background, where recursion is uncommon at best. There&#8217;s nothing to be scared of, but I do recommend sitting down and working through all the steps in evaluating a recursive procedure every now and then. It might be helpful to sit down with GHCi and maybe even a pencil and work through a step-by-step evaluation of a call to <span class="mono">printWithWidth</span>.
</div>
]]></content:encoded>
			<wfw:commentRss>http://my.life-is-virtual.com/2009/11/02/incremental-haskell-iii-tokyo-drift/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Incremental Haskell, Part 2</title>
		<link>http://my.life-is-virtual.com/2009/10/13/incremental-haskell-part-2/</link>
		<comments>http://my.life-is-virtual.com/2009/10/13/incremental-haskell-part-2/#comments</comments>
		<pubDate>Tue, 13 Oct 2009 02:08:50 +0000</pubDate>
		<dc:creator>jcooper</dc:creator>
				<category><![CDATA[Vaguely Instructional]]></category>
		<category><![CDATA[haskell]]></category>
		<category><![CDATA[incremental-haskell]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[tutorial]]></category>

		<guid isPermaLink="false">http://my.life-is-virtual.com/?p=104</guid>
		<description><![CDATA[Prelude
This is part 2 in a polyonymous series that seeks to be a companion guide for those learning Haskell through reading Real World Haskell. In case you missed it, here&#8217;s the full intro and part 1.
When we last finished, we ended up with a swell type for representing JSON data and some functions for converting [...]]]></description>
			<content:encoded><![CDATA[<p><span class="bold">Prelude</span></p>
<p><span class="italic">This is part 2 in a polyonymous series that seeks to be a companion guide for those learning Haskell through reading <a href="http://book.realworldhaskell.org/">Real World Haskell</a>. In case you missed it, <a href="http://my.life-is-virtual.com/2009/10/07/fake-world-haskell-part-1/">here&#8217;s the full intro and part 1</a>.</span></p>
<p>When we last finished, we ended up with a swell type for representing JSON data and some functions for converting from existing types like String to our new type and back again. We also thought about a couple more functions we&#8217;d need to complete our library, including one for converting our Haskell representation of a JSON type to real JSON. We tentatively gave this function the name <span class="mono">toJson</span>, with the logical type <span class="mono">JsonType -> String</span>. After all, the goal is to get from our custom type to something we can print to the screen or to a file, and we&#8217;d like our data in <span class="mono">String</span> form to do that.</p>
<div class="highlight"><span class="bold">On separation of concerns</span></p>
<p>There are a couple of advantages to keeping functions small and focused. Sure, we could write a function that takes a <span class="mono">JsonType</span> and prints it right away, instead of returning a <span class="mono">String</span>. But what if we later decide we want to compress the string before printing? That way it&#8217;d be smaller and thus take up less bandwidth if we need to send it over a network (a common practice with JSON-serialized data). What if we also want to provide an option for legibly-formatted, human-readable output? </p>
<p>If we try to account for these (and more) possibilities, our function soon becomes bloated. We&#8217;ll likely end up tearing pieces of it out to reuse anyway, so it&#8217;s better to keep in mind ahead of time that functions should do one thing. This is sound advice in any language, but there are a couple more especially enticing reasons to do it in Haskell:</p>
<ul>
<li>The type signature of a function can tell you a lot about it. We&#8217;ll see in this article how that gives you an advantage that even something like Visual Studio&#8217;s Intellisense is hard-pressed to match. If your function becomes bloated, trying to do too much, then you sacrifice this nicety.</li>
<li>Haskell makes a bigger deal about <span class="italic">side effects</span> than most programming languages. Side effects are the parts of a program that affect global state&#8211;that is, when a function interacts with something it didn&#8217;t create. This sort of code can be tough to reason about, as the function interacting with global state cannot tell what else might interact with it. Successful Haskellers have found that properly controlling and segregating code that has side effects (like I/O) is a boon to maintainability. The general principle is, code that doesn&#8217;t have to have side effects shouldn&#8217;t. This would include our example of getting our parsed JSON data into a string suitable for printing: eventually we <span class="italic">do</span> need to print it out, which is I/O, but the actual construction of the appropriate string doesn&#8217;t involve I/O, and can be performed separately. We&#8217;ll continue to focus on this concept.</li>
</ul>
</div>
<p><span class="bold">How to say <span class="mono">toString()</span> in Haskell</span></p>
<p>Many mainstream object-oriented languages have a hierarchy of types such that all types are subtypes of a base &#8220;<span class="mono">Object</span>&#8221; class. Very frequently, this <span class="mono">Object</span> class (and thus all classes) has a method that is used to print a string representation of itself. In such a language, our <span class="mono">JsonType</span> might override this method so that when printed, <span class="mono">JsonType</span> values would come out looking like real chunks of JSON. </p>
<p>Haskell has similar functionality, but for a different purpose. Whereas the typical <span class="mono">toString()</span> method mentioned above is generally not of much use until overridden, and the format of its output unspecified, Haskell has a function called <span class="mono">show</span> that provides a more consistent approach. Specifically, calling <span class="mono">show</span> on a value will return a string that, if read back into Haskell, would yield the value passed. That is, its output is designed to be not just human-readable, but compiler-readable. For example, passing a <span class="mono">String</span> value to <span class="mono">show</span> will return it surrounded in double quotes and containing properly escaped special characters. </p>
<p>We get a default implementation for <span class="mono">show</span> when we put &#8220;<span class="mono">deriving Show</span>&#8221; in the declaration of a new type. If you recall, we indeed did this for <span class="mono">JsonType</span>. That&#8217;s why GHCi is able to print out our <span class="mono">JsonType</span> values&#8211;GHCi always calls <span class="mono">show</span> on the result of an expression!</p>
<p>If for some reason we aren&#8217;t satisfied with the <span class="mono">show</span> that Haskell gives a type automatically, we can define it ourselves. It&#8217;s recommended, though, that if we do so, it should behave as we described above&#8211;the output should be valid Haskell. Since we want our <span class="mono">toJson</span> function to produce valid <span class="italic">JSON</span>, not valid Haskell, we aren&#8217;t going to redefine <span class="mono">JsonType</span>&#8217;s <span class="mono">show</span>.</p>
<p><span class="bold">What the heck, man? Then why did you just tell me about <span class="mono">show</span>?</span></p>
<p>Fear not&#8211;<span class="mono">show</span> will still help us out! A couple of our <span class="mono">JsonType</span>s are really <span class="mono">String</span>s and <span class="mono">Double</span>s, and so once we extract them out of the <span class="mono">JsonString</span> and <span class="mono">JsonNumber</span> constructors respectively, we can call <span class="mono">show</span> on the values, and Haskell will format them to strings representing valid Haskell syntax. For strings and numbers, JSON&#8217;s syntax and Haskell&#8217;s are the same, so we get these cases taken care of for free:</p>

<div class="wp_syntax"><div class="code"><pre class="haskell" style="font-family:monospace;">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>
&nbsp;
toJson <span style="color: green;">&#40;</span>JsonString string<span style="color: green;">&#41;</span> <span style="color: #339933; font-weight: bold;">=</span> <span style="font-weight: bold;">show</span> string
toJson <span style="color: green;">&#40;</span>JsonNumber number<span style="color: green;">&#41;</span> <span style="color: #339933; font-weight: bold;">=</span> <span style="font-weight: bold;">show</span> number</pre></div></div>

<p>However, if we tried to do the same thing with <span class="mono">JsonBool</span>, we&#8217;d be in trouble: if you try <span class="mono">show True</span> in GHCi, you&#8217;ll see it returns <span class="mono">&#8220;True&#8221;</span>, and JSON wants lowercase booleans. Thus:</p>

<div class="wp_syntax"><div class="code"><pre class="haskell" style="font-family:monospace;">toJson <span style="color: green;">&#40;</span>JsonBool True<span style="color: green;">&#41;</span>  <span style="color: #339933; font-weight: bold;">=</span> <span style="color: #3366CC;">&quot;true&quot;</span>
toJson <span style="color: green;">&#40;</span>JsonBool False<span style="color: green;">&#41;</span> <span style="color: #339933; font-weight: bold;">=</span> <span style="color: #3366CC;">&quot;false&quot;</span></pre></div></div>

<p>Likewise, trying <span class="mono">show JsonNull</span> in GHCi gives <span class="mono">&#8220;JsonNull&#8221;</span>, and that&#8217;s not what we want.</p>

<div class="wp_syntax"><div class="code"><pre class="haskell" style="font-family:monospace;">toJson JsonNull <span style="color: #339933; font-weight: bold;">=</span> <span style="color: #3366CC;">&quot;null&quot;</span></pre></div></div>

<p>Printing a JSON &#8220;object&#8221; is also a bit more complicated. In JSON, an object looks like this:</p>

<div class="wp_syntax"><div class="code"><pre class="javascript" style="font-family:monospace;"><span style="color: #009900;">&#123;</span> <span style="color: #3366CC;">&quot;some key&quot;</span><span style="color: #339933;">:</span> value<span style="color: #339933;">,</span> <span style="color: #3366CC;">&quot;another key&quot;</span><span style="color: #339933;">:</span> anotherValue <span style="color: #009900;">&#125;</span></pre></div></div>

<p>In other words, curly braces surround the object, pairs are delimited by commas, and a pair consists of a string followed by a colon followed by a value (which can be of any JSON type). Another wrinkle is that there can be any number of pairs, including zero. This means we&#8217;re going to use a common functional programming pattern:</p>
<ul>
<li>Our primary function does the stuff that will happen for sure, and passes the processing that can vary to a helper function.</li>
<li>The helper function needs to handle the cases of what to do when there&#8217;s useful input, and what to do when there isn&#8217;t. Commonly, input of this sort is a list, so we at least need to handle the empty list vs. a list with elements.</li>
</ul>
<p>In our case:</p>

<div class="wp_syntax"><div class="code"><pre class="haskell" style="font-family:monospace;"><span style="color: #5d478b; font-style: italic;">-- Remember, we defined JsonObject like this: JsonObject [(String, JsonType)]</span>
toJson <span style="color: green;">&#40;</span>JsonObject object<span style="color: green;">&#41;</span> <span style="color: #339933; font-weight: bold;">=</span> <span style="color: #3366CC;">&quot;{&quot;</span> <span style="color: #339933; font-weight: bold;">++</span> toKeyValuePairs object <span style="color: #339933; font-weight: bold;">++</span> <span style="color: #3366CC;">&quot;}&quot;</span>
    <span style="color: #06c; font-weight: bold;">where</span> toKeyValuePairs <span style="color: green;">&#91;</span><span style="color: green;">&#93;</span>    <span style="color: #339933; font-weight: bold;">=</span> <span style="color: #3366CC;">&quot;&quot;</span>
          toKeyValuePairs pairs <span style="color: #339933; font-weight: bold;">=</span> <span style="color: #5d478b; font-style: italic;">-- ??</span></pre></div></div>

<p>We&#8217;re off to a good start. Our top-level function is doing the part that will always be done: surrounding the object with curly braces. Our helper function to handle the rest is called <span class="mono">toKeyValuePairs</span>, and we define it using the common Haskellism of putting it in a <span class="mono">where</span> clause. When a function is supplementary like this, it doesn&#8217;t need to be available to the whole module, and it automatically has access to values introduced in the function it&#8217;s attached to. Perhaps most importantly, it allows our functions to read quite nicely, allowing a reader to digest a function a chunk at a time. It might look strange at first, but it&#8217;s a handy feature you&#8217;ll soon wish was in more languages.</p>
<p>Our helper function is primed and ready to handle any or no input. In fact, no input was easy: just return the empty string and we&#8217;re done. The other case takes a bit more work. Thinking of our algorithm, we need to turn our list of pairs into strings with the format <span class="mono">&#8220;key&#8221;: value</span>. Then we need to join those strings with commas.</p>

<div class="wp_syntax"><div class="code"><pre class="haskell" style="font-family:monospace;"><span style="color: #5d478b; font-style: italic;">-- ...</span>
        toKeyValuePairs pairs     <span style="color: #339933; font-weight: bold;">=</span> joinWithCommas <span style="color: green;">&#40;</span><span style="font-weight: bold;">map</span> pairToString pairs<span style="color: green;">&#41;</span>
        pairToString <span style="color: green;">&#40;</span>key<span style="color: #339933; font-weight: bold;">,</span> value<span style="color: green;">&#41;</span> <span style="color: #339933; font-weight: bold;">=</span> <span style="font-weight: bold;">show</span> key <span style="color: #339933; font-weight: bold;">++</span> <span style="color: #3366CC;">&quot;: &quot;</span> <span style="color: #339933; font-weight: bold;">++</span> toJson value
&nbsp;
joinWithCommas <span style="color: #339933; font-weight: bold;">::</span> <span style="color: green;">&#91;</span><span style="color: #cccc00; font-weight: bold;">String</span><span style="color: green;">&#93;</span> <span style="color: #339933; font-weight: bold;">-&gt;</span> <span style="color: #cccc00; font-weight: bold;">String</span>
joinWithCommas stringList <span style="color: #339933; font-weight: bold;">=</span> <span style="color: #5d478b; font-style: italic;">-- ??</span></pre></div></div>

<p>There&#8217;s a bit going on here, but it&#8217;s hopefully not too hard to follow. The part in parentheses comes first&#8211;the &#8220;turn list of pairs into list of properly formatted strings&#8221; part. For this, we use <span class="mono">map</span>, which you&#8217;ve probably come across before&#8211;it&#8217;s a functional programming building block. It applies a function to everything in a list, spitting out a new list containing the results of each application. We want each of our pairs turned into a string, so we&#8217;ll pass a function&#8211;let&#8217;s call it <span class="mono">pairToString</span>&#8211;and our list of pairs to <span class="mono">map</span>.</p>
<p>We then write <span class="mono">pairToString</span>. Remember, <span class="mono">map</span> will be passing it one element of the list of pairs at a time. We use pattern matching to break up the passed-in pair into its key and value parts. The key part needs to be printed as a properly escaped string in double quotes, so we&#8217;ll use the same trick we did earlier and use the <span class="mono">show</span> function. We then append the colon. Now we need to print out the value. The problem is, value can be any valid JSON type, and different types get printed out in different ways. If only we had a function that handled the printing of every JSON type! Oh wait, we&#8217;re writing it, and it&#8217;s called <span class="mono">toJson</span> :)</p>
<p>Now we need to join our resulting list of formatted strings with commas. It&#8217;s reasonable to assume that joining a list, delimiting elements with a certain thing, is already in the standard library (as it is in many languages, for strings at least). Problem is, we may not know exactly what that function is called. We could just write it ourselves, but it&#8217;s of course better not to have to replicate effort if we don&#8217;t have to.</p>
<p>Earlier I mentioned how Haskell&#8217;s cool type system can help us know what a function does <span class="italic">merely by knowing its type</span>. In fact, an entire method of searching the Haskell API is built upon this concept. One website that uses this method to allow us to find functions is <a href="http://www.haskell.org/hoogle/">Hoogle</a>.</p>
<p>So let&#8217;s go to Hoogle, and search for the type of the function we&#8217;re looking for. We want a function that takes a list of <span class="mono">String</span>s to be joined, a <span class="mono">String</span> to join them with, and returns a single joined <span class="mono">String</span> as the result. In Haskell, we write that type as:</p>

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

<p>So type that into the search box in Hoogle.</p>
<p>The first result of the search is the function we want! It&#8217;s called <span class="mono">intercalate</span>, and the description says it &#8220;inserts the list xs in between the lists in xss and concatenates the result.&#8221; If you think about it, that&#8217;s exactly what we&#8217;re doing. <span class="bold">Note that Hoogle found this function for us even though we didn&#8217;t even type in the type exactly.</span> We had the arguments swapped, and we specified <span class="mono">String</span> even though <span class="mono">intercalate</span> can really use any type of list, not just <span class="mono">[Char]</span> (which is all a <span class="mono">String</span> is). Cool, eh? Use Hoogle a lot.</p>
<p>Before we go using the function we found in our code, we should take note of where this function is defined. Unless it&#8217;s in the Prelude (the name of the Haskell library that&#8217;s imported by default), we have to explicitly import the specified library so that the function name can be found. This practice is common in many languages, as the standard library tends to be divided up into namespaces/modules/whatever. <span class="small">(An apology to PHP programmers, who are used to having every standard library function ever written smooshed into the default namespace.)</span></p>
<p>Hoogle notes in soothing green text that <span class="mono">intercalate</span> resides in the module <span class="mono">Data.List</span>, so add the following to the top of your source file:</p>

<div class="wp_syntax"><div class="code"><pre class="haskell" style="font-family:monospace;"><span style="color: #06c; font-weight: bold;">import</span> Data<span style="color: #339933; font-weight: bold;">.</span>List <span style="color: green;">&#40;</span>intercalate<span style="color: green;">&#41;</span></pre></div></div>

<p>Now we can finish up our <span class="mono">joinWithCommas</span> function:</p>

<div class="wp_syntax"><div class="code"><pre class="haskell" style="font-family:monospace;">joinWithCommas stringList <span style="color: #339933; font-weight: bold;">=</span> intercalate <span style="color: #3366CC;">&quot;, &quot;</span> stringList</pre></div></div>

<p>Now that printing JSON objects is taken care of, we&#8217;re just left with JSON arrays. The process will be almost exactly the same as for objects, except we don&#8217;t have to print keys, only values. Oh, and we use square brackets instead of curly braces.</p>

<div class="wp_syntax"><div class="code"><pre class="haskell" style="font-family:monospace;">toJson <span style="color: green;">&#40;</span>JsonArray array<span style="color: green;">&#41;</span> <span style="color: #339933; font-weight: bold;">=</span> <span style="color: #3366CC;">&quot;[&quot;</span> <span style="color: #339933; font-weight: bold;">++</span> toValues array <span style="color: #339933; font-weight: bold;">++</span> <span style="color: #3366CC;">&quot;]&quot;</span>
    <span style="color: #06c; font-weight: bold;">where</span> toValues <span style="color: green;">&#91;</span><span style="color: green;">&#93;</span>     <span style="color: #339933; font-weight: bold;">=</span> <span style="color: #3366CC;">&quot;&quot;</span>
          toValues values <span style="color: #339933; font-weight: bold;">=</span> joinWithCommas <span style="color: green;">&#40;</span><span style="font-weight: bold;">map</span> toJson values<span style="color: green;">&#41;</span></pre></div></div>

<p>Again we use <span class="mono">map</span>, this time to apply our <span class="mono">toJson</span> function over all the values in the underlying list we&#8217;re using to represent our JSON array. Then we join the resulting properly formatted strings with the <span class="mono">joinWithCommas</span> function we just fleshed out.</p>
<p>Here, then, is the full <span class="mono">toJson</span> function:</p>

<div class="wp_syntax"><div class="code"><pre class="haskell" style="font-family:monospace;">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>
&nbsp;
toJson <span style="color: green;">&#40;</span>JsonString string<span style="color: green;">&#41;</span> <span style="color: #339933; font-weight: bold;">=</span> <span style="font-weight: bold;">show</span> string
toJson <span style="color: green;">&#40;</span>JsonNumber number<span style="color: green;">&#41;</span> <span style="color: #339933; font-weight: bold;">=</span> <span style="font-weight: bold;">show</span> number
toJson <span style="color: green;">&#40;</span>JsonBool True<span style="color: green;">&#41;</span>     <span style="color: #339933; font-weight: bold;">=</span> <span style="color: #3366CC;">&quot;true&quot;</span>
toJson <span style="color: green;">&#40;</span>JsonBool False<span style="color: green;">&#41;</span>    <span style="color: #339933; font-weight: bold;">=</span> <span style="color: #3366CC;">&quot;false&quot;</span>
toJson JsonNull            <span style="color: #339933; font-weight: bold;">=</span> <span style="color: #3366CC;">&quot;null&quot;</span>
toJson <span style="color: green;">&#40;</span>JsonObject object<span style="color: green;">&#41;</span> <span style="color: #339933; font-weight: bold;">=</span> <span style="color: #3366CC;">&quot;{&quot;</span> <span style="color: #339933; font-weight: bold;">++</span> toKeyValuePairs object <span style="color: #339933; font-weight: bold;">++</span> <span style="color: #3366CC;">&quot;}&quot;</span>
    <span style="color: #06c; font-weight: bold;">where</span> toKeyValuePairs <span style="color: green;">&#91;</span><span style="color: green;">&#93;</span>        <span style="color: #339933; font-weight: bold;">=</span> <span style="color: #3366CC;">&quot;&quot;</span>
          toKeyValuePairs pairs     <span style="color: #339933; font-weight: bold;">=</span> joinWithCommas <span style="color: green;">&#40;</span><span style="font-weight: bold;">map</span> pairToString pairs<span style="color: green;">&#41;</span>
          pairToString <span style="color: green;">&#40;</span>key<span style="color: #339933; font-weight: bold;">,</span> value<span style="color: green;">&#41;</span> <span style="color: #339933; font-weight: bold;">=</span> <span style="font-weight: bold;">show</span> key <span style="color: #339933; font-weight: bold;">++</span> <span style="color: #3366CC;">&quot;: &quot;</span> <span style="color: #339933; font-weight: bold;">++</span> toJson value
toJson <span style="color: green;">&#40;</span>JsonArray array<span style="color: green;">&#41;</span>   <span style="color: #339933; font-weight: bold;">=</span> <span style="color: #3366CC;">&quot;[&quot;</span> <span style="color: #339933; font-weight: bold;">++</span> toValues array <span style="color: #339933; font-weight: bold;">++</span> <span style="color: #3366CC;">&quot;]&quot;</span>
    <span style="color: #06c; font-weight: bold;">where</span> toValues <span style="color: green;">&#91;</span><span style="color: green;">&#93;</span>     <span style="color: #339933; font-weight: bold;">=</span> <span style="color: #3366CC;">&quot;&quot;</span>
          toValues values <span style="color: #339933; font-weight: bold;">=</span> joinWithCommas <span style="color: green;">&#40;</span><span style="font-weight: bold;">map</span> toJson values<span style="color: green;">&#41;</span></pre></div></div>

<p>Not bad! Now that we&#8217;ve taken care of formatting the JSON data, we just need to actually print it. For the time being, we&#8217;ll write a quick function that will print to the screen:</p>

<div class="wp_syntax"><div class="code"><pre class="haskell" style="font-family:monospace;">printJson jsonValue <span style="color: #339933; font-weight: bold;">=</span> <span style="font-weight: bold;">putStrLn</span> <span style="color: green;">&#40;</span>toJson jsonValue<span style="color: green;">&#41;</span></pre></div></div>

<p>In the next article, we&#8217;ll play with different ways of rendering our JSON data.</p>
]]></content:encoded>
			<wfw:commentRss>http://my.life-is-virtual.com/2009/10/13/incremental-haskell-part-2/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>
