<?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>Amateur Topologist &#187; haskell</title>
	<atom:link href="http://www.amateurtopologist.com/blog/tag/haskell/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.amateurtopologist.com/blog</link>
	<description>Everything but topology.</description>
	<lastBuildDate>Sun, 15 Jan 2012 21:33:04 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.4-alpha-19719</generator>
		<item>
		<title>Writing Heist Splices for Snap</title>
		<link>http://www.amateurtopologist.com/blog/2012/01/15/writing-heist-splices-for-snap/</link>
		<comments>http://www.amateurtopologist.com/blog/2012/01/15/writing-heist-splices-for-snap/#comments</comments>
		<pubDate>Sun, 15 Jan 2012 21:33:04 +0000</pubDate>
		<dc:creator>Patrick Hurst</dc:creator>
				<category><![CDATA[Computers]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[haskell]]></category>
		<category><![CDATA[snap]]></category>
		<category><![CDATA[web programming]]></category>

		<guid isPermaLink="false">http://www.amateurtopologist.com/blog/?p=1337</guid>
		<description><![CDATA[I&#8217;ve been doing a lot of web stuff lately; so far, it&#8217;s only been very simple HTML + CSS + JS (well, CoffeeScript, but who&#8217;s counting), but eventually I might move on to other, neater things. And in the process one of the things that I found is Twitter Bootstrap; it&#8217;s a bunch of CSS [...]]]></description>
			<content:encoded><![CDATA[<p>I&#8217;ve been doing a lot of web stuff lately; so far, it&#8217;s only been very simple HTML + CSS + JS (well, <a href="http://coffeescript.org/">CoffeeScript</a>, but who&#8217;s counting), but eventually I might move on to other, neater things. And in the process one of the things that I found is <a href="http://twitter.github.com/bootstrap/">Twitter Bootstrap</a>; it&#8217;s a bunch of CSS that makes it &#8216;easy&#8217; to make professional-looking sites. I put &#8216;easy&#8217; in quotes because the learning curve is definitely steeper than that of CSS itself, because you have to nest your DOM just so in order for the given CSS to apply right. But you get nice margins, good color themes, etc.</p>
<p>One of the things that you get when you use Bootstrap is a very nice-looking nav bar, which is actually just a very well-themed unordered list of links. </p>
<p>In particular, if you set the class of one of the list items to &#8220;active&#8221;, it &#8216;highlights&#8217; it:<br />
<div id="attachment_1342" class="wp-caption alignright" style="width: 578px"><a href="http://www.amateurtopologist.com/blog/wp-content/uploads/2012/01/Screen-Shot-2012-01-14-at-5.41.18-AM.png?9d7bd4"><img src="http://www.amateurtopologist.com/blog/wp-content/uploads/2012/01/Screen-Shot-2012-01-14-at-5.41.18-AM.png?9d7bd4" alt="" title="Twitter Bootstrap nav bar" width="568" height="54" class="size-full wp-image-1342" /></a><p class="wp-caption-text">Note the highlight on &#039;Scalemate generator&#039;</p></div></p>
<p>Now, I&#8217;m serving this site through <a href="http://snapframework.com/">Snap</a>, the Haskell webdev framework; I&#8217;m doing this because one of my subsites needs to be able to upload files, and I figured I might as well use Haskell. And Snap comes with a templating language called <a href="http://hackage.haskell.org/package/heist-0.7.0.1">Heist</a>. So, given that I&#8217;m already using templating to insert the boilerplate jQuery/Bootstrap includes and the GitHub link/authorship at the bottom, wouldn&#8217;t it make sense to template the nav links?</p>
<p>It turns out that it&#8217;s fairly simple to do, as illustrated in <a href="https://github.com/veinor/amateurtopologist-code/blob/master/src/NavLinks.hs">NavLinks.hs</a>. We start with imports; nothing too interesting here. We need Heist to access the templating engine and Text.XmlHtml to actually construct the nodes.</p>
<div class="codecolorer-container haskell default" style="overflow:auto;white-space:nowrap;border:1px solid #9F9F9F;width:435px;"><table cellspacing="0" cellpadding="0"><tbody><tr><td style="padding:5px;text-align:center;color:#888888;background-color:#EEEEEE;border-right: 1px solid #9F9F9F;font: normal 12px/1.4em Monaco, Lucida Console, monospace;"><div>1<br />2<br />3<br />4<br />5<br />6<br />7<br />8<br />9<br />10<br />11<br />12<br /></div></td><td><div class="haskell codecolorer" style="padding:5px;font:normal 12px/1.4em Monaco, Lucida Console, monospace;white-space:nowrap"><span style="color: #5d478b; font-style: italic;">{-# LANGUAGE OverloadedStrings #-}</span><br />
<br />
<span style="color: #06c; font-weight: bold;">module</span> NavLinks <span style="color: #06c; font-weight: bold;">where</span><br />
<br />
<span style="color: #06c; font-weight: bold;">import</span> <span style="color: #06c; font-weight: bold;">qualified</span> Data<span style="color: #339933; font-weight: bold;">.</span>ByteString <span style="color: #06c; font-weight: bold;">as</span> B<br />
<span style="color: #06c; font-weight: bold;">import</span> <span style="color: #06c; font-weight: bold;">qualified</span> Data<span style="color: #339933; font-weight: bold;">.</span>Text <span style="color: #06c; font-weight: bold;">as</span> T<br />
<span style="color: #06c; font-weight: bold;">import</span> &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; Data<span style="color: #339933; font-weight: bold;">.</span>Text<span style="color: #339933; font-weight: bold;">.</span>Encoding<br />
<br />
<span style="color: #06c; font-weight: bold;">import</span> &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; Snap<br />
<br />
<span style="color: #06c; font-weight: bold;">import</span> &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; Text<span style="color: #339933; font-weight: bold;">.</span>Templating<span style="color: #339933; font-weight: bold;">.</span>Heist<br />
<span style="color: #06c; font-weight: bold;">import</span> <span style="color: #06c; font-weight: bold;">qualified</span> Text<span style="color: #339933; font-weight: bold;">.</span>XmlHtml <span style="color: #06c; font-weight: bold;">as</span> X</div></td></tr></tbody></table></div>
<p>Next we declare the type:</p>
<div class="codecolorer-container haskell default" style="overflow:auto;white-space:nowrap;border:1px solid #9F9F9F;width:435px;"><table cellspacing="0" cellpadding="0"><tbody><tr><td style="padding:5px;text-align:center;color:#888888;background-color:#EEEEEE;border-right: 1px solid #9F9F9F;font: normal 12px/1.4em Monaco, Lucida Console, monospace;"><div>17<br /></div></td><td><div class="haskell codecolorer" style="padding:5px;font:normal 12px/1.4em Monaco, Lucida Console, monospace;white-space:nowrap">navSplice <span style="color: #339933; font-weight: bold;">::</span> MonadSnap m <span style="color: #339933; font-weight: bold;">=&gt;</span> <span style="color: green;">&#91;</span><span style="color: green;">&#40;</span>B<span style="color: #339933; font-weight: bold;">.</span>ByteString<span style="color: #339933; font-weight: bold;">,</span> T<span style="color: #339933; font-weight: bold;">.</span>Text<span style="color: green;">&#41;</span><span style="color: green;">&#93;</span> <span style="color: #339933; font-weight: bold;">-&gt;</span> Splice m</div></td></tr></tbody></table></div>
<p>The way a splice works is this: you construct a Splice in some monad <code class="codecolorer text default"><span class="text">Splice m</span></code>, and you can lift monad actions in the <code class="codecolorer text default"><span class="text">m</span></code> monad into <code class="codecolorer text default"><span class="text">Splice m</span></code>. In this case, we can be in any monad that provides us with <code class="codecolorer text default"><span class="text">getRequest</span></code>, since we want to get the URI of the request. Since <code class="codecolorer haskell default"><span class="haskell">getRequest <span style="color: #339933; font-weight: bold;">::</span> MonadSnap m <span style="color: #339933; font-weight: bold;">=&gt;</span> Request</span></code>, we can be in any monad that is an instance of <code class="codecolorer text default"><span class="text">MonadSnap</span></code>. The argument to navSplice is the list of (path, title) tuples; for example, it might look like <code class="codecolorer haskell default"><span class="haskell"><span style="color: green;">&#91;</span><span style="color: green;">&#40;</span><span style="background-color: #3cb371;">&quot;/about&quot;</span><span style="color: #339933; font-weight: bold;">,</span> <span style="background-color: #3cb371;">&quot;About&quot;</span><span style="color: green;">&#41;</span><span style="color: #339933; font-weight: bold;">,</span> <span style="color: green;">&#40;</span><span style="background-color: #3cb371;">&quot;/blog&quot;</span><span style="color: #339933; font-weight: bold;">,</span> <span style="background-color: #3cb371;">&quot;Blog&quot;</span><span style="color: green;">&#41;</span><span style="color: green;">&#93;</span></span></code>. The path is a ByteString because the request gives us the URI as a ByteString, and the title is Text because Text.XmlHtml uses Text. Now, onto the actual declaration:</p>
<div class="codecolorer-container haskell default" style="overflow:auto;white-space:nowrap;border:1px solid #9F9F9F;width:435px;"><table cellspacing="0" cellpadding="0"><tbody><tr><td style="padding:5px;text-align:center;color:#888888;background-color:#EEEEEE;border-right: 1px solid #9F9F9F;font: normal 12px/1.4em Monaco, Lucida Console, monospace;"><div>18<br />19<br />20<br />21<br />22<br />23<br />24<br />25<br />26<br /></div></td><td><div class="haskell codecolorer" style="padding:5px;font:normal 12px/1.4em Monaco, Lucida Console, monospace;white-space:nowrap">navSplice links <span style="color: #339933; font-weight: bold;">=</span> <span style="color: green;">&#40;</span>:<span style="color: green;">&#91;</span><span style="color: green;">&#93;</span><span style="color: green;">&#41;</span> <span style="color: #339933; font-weight: bold;">.</span> X<span style="color: #339933; font-weight: bold;">.</span>Element <span style="background-color: #3cb371;">&quot;ul&quot;</span> <span style="color: green;">&#91;</span><span style="color: green;">&#40;</span><span style="background-color: #3cb371;">&quot;class&quot;</span><span style="color: #339933; font-weight: bold;">,</span> <span style="background-color: #3cb371;">&quot;nav&quot;</span><span style="color: green;">&#41;</span><span style="color: green;">&#93;</span> <span style="color: #339933; font-weight: bold;">&lt;$&gt;</span> <span style="color: #06c; font-weight: bold;">do</span><br />
&nbsp; currentURI <span style="color: #339933; font-weight: bold;">&lt;-</span> lift <span style="color: #339933; font-weight: bold;">$</span> rqURI <span style="color: #339933; font-weight: bold;">&lt;$&gt;</span> getRequest<br />
&nbsp; <span style="color: #5d478b; font-style: italic;">-- add the 'active' class if the href is a prefix of the current URI</span><br />
&nbsp; <span style="color: #06c; font-weight: bold;">let</span> li path<br />
&nbsp; &nbsp; &nbsp; &nbsp; <span style="color: #339933; font-weight: bold;">|</span> path `B<span style="color: #339933; font-weight: bold;">.</span>isPrefixOf` <span style="color: green;">&#40;</span>currentURI `B<span style="color: #339933; font-weight: bold;">.</span>append` <span style="background-color: #3cb371;">&quot;/&quot;</span><span style="color: green;">&#41;</span> <span style="color: #339933; font-weight: bold;">=</span> &nbsp;X<span style="color: #339933; font-weight: bold;">.</span>Element <span style="background-color: #3cb371;">&quot;li&quot;</span> <span style="color: green;">&#91;</span><span style="color: green;">&#40;</span><span style="background-color: #3cb371;">&quot;class&quot;</span><span style="color: #339933; font-weight: bold;">,</span> <span style="background-color: #3cb371;">&quot;active&quot;</span><span style="color: green;">&#41;</span><span style="color: green;">&#93;</span><br />
&nbsp; &nbsp; &nbsp; &nbsp; <span style="color: #339933; font-weight: bold;">|</span> <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:otherwise"><span style="font-weight: bold;">otherwise</span></a> <span style="color: #339933; font-weight: bold;">=</span> X<span style="color: #339933; font-weight: bold;">.</span>Element <span style="background-color: #3cb371;">&quot;li&quot;</span> <span style="color: green;">&#91;</span><span style="color: green;">&#93;</span><br />
&nbsp; <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:return"><span style="font-weight: bold;">return</span></a> <span style="color: #339933; font-weight: bold;">$</span> <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:map"><span style="font-weight: bold;">map</span></a> <span style="color: green;">&#40;</span>\<span style="color: green;">&#40;</span>path<span style="color: #339933; font-weight: bold;">,</span> title<span style="color: green;">&#41;</span> <span style="color: #339933; font-weight: bold;">-&gt;</span> li path <span style="color: green;">&#91;</span>buildLink path title<span style="color: green;">&#93;</span><span style="color: green;">&#41;</span> links<br />
&nbsp; &nbsp;<span style="color: #5d478b; font-style: italic;">-- build a link to the path with the given text</span><br />
&nbsp; &nbsp; <span style="color: #06c; font-weight: bold;">where</span> buildLink path title <span style="color: #339933; font-weight: bold;">=</span> X<span style="color: #339933; font-weight: bold;">.</span>Element <span style="background-color: #3cb371;">&quot;a&quot;</span> <span style="color: green;">&#91;</span><span style="color: green;">&#40;</span><span style="background-color: #3cb371;">&quot;href&quot;</span><span style="color: #339933; font-weight: bold;">,</span> decodeUtf8 path<span style="color: green;">&#41;</span><span style="color: green;">&#93;</span> <span style="color: green;">&#91;</span>X<span style="color: #339933; font-weight: bold;">.</span>TextNode title<span style="color: green;">&#93;</span></div></td></tr></tbody></table></div>
<p>Look at the do-block first. Line 19 just gets the current URI out. Lines 21-23 are interesting; what we&#8217;re doing here is declaring a function of type <code class="codecolorer haskell default"><span class="haskell">li <span style="color: #339933; font-weight: bold;">::</span> B<span style="color: #339933; font-weight: bold;">.</span>ByteString <span style="color: #339933; font-weight: bold;">-&gt;</span> <span style="color: green;">&#91;</span>X<span style="color: #339933; font-weight: bold;">.</span>Node<span style="color: green;">&#93;</span> <span style="color: #339933; font-weight: bold;">-&gt;</span> X<span style="color: #339933; font-weight: bold;">.</span>Node</span></code>. The way an HTML element is constructed in Text.XmlHtml is through the Element constructor, which has type <code class="codecolorer text default"><span class="text">T.Text -&gt; [(T.Text, T.Text)] -&gt; [X.Node] -&gt; X.Node</span></code>. The first Text is the tag; the array of Text tuples is the list of attributes, and the list of Nodes is the list of children. So, here we&#8217;re partially applying the tag (always &#8220;li&#8221;) and the attributes (which is either empty or <code class="codecolorer text default"><span class="text">class=&quot;active&quot;</span></code>). We apply the &#8220;active&#8221; class only if the path is a prefix of the current URI; we append a &#8220;/&#8221; to the end of the current URI to make sure that trailing slashes are ignored.</p>
<p>Next, look at line 26; buildLink just builds a link node looking like <code class="codecolorer text default"><span class="text">&lt;a href=&quot;path&quot;&gt;title&lt;/a&gt;</span></code>. <code class="codecolorer text default"><span class="text">X.TextNode</span></code> is, obviously, the constructor for text Nodes.</p>
<p>On the last line of the do block, we map over the <code class="codecolorer text default"><span class="text">(path, title)</span></code> tuples, build up a list of <code class="codecolorer text default"><span class="text">&lt;li&gt;</span></code> elements, and return that list. Finally, on line 18 we construct an unordered list element with the &#8220;nav&#8221; class. Finally, we construct a single-element list using <code class="codecolorer text default"><span class="text">(:[])</span></code> (which some people call the monkey function), which just constructs a list with its argument inside. My actual code uses return instead, but I decided that this would be clearer.</p>
<p>Adding that splice to the default list of splices is as simple as adding</p>
<div class="codecolorer-container haskell default" style="overflow:auto;white-space:nowrap;border:1px solid #9F9F9F;width:435px;"><div class="haskell codecolorer" style="padding:5px;font:normal 12px/1.4em Monaco, Lucida Console, monospace;white-space:nowrap">pages <span style="color: #339933; font-weight: bold;">::</span> <span style="color: green;">&#91;</span><span style="color: green;">&#40;</span>B<span style="color: #339933; font-weight: bold;">.</span>ByteString<span style="color: #339933; font-weight: bold;">,</span> T<span style="color: #339933; font-weight: bold;">.</span>Text<span style="color: green;">&#41;</span><span style="color: green;">&#93;</span><br />
pages <span style="color: #339933; font-weight: bold;">=</span> <span style="color: green;">&#91;</span> <span style="color: green;">&#40;</span><span style="background-color: #3cb371;">&quot;/chargen/&quot;</span><span style="color: #339933; font-weight: bold;">,</span> <span style="background-color: #3cb371;">&quot;Character generator&quot;</span><span style="color: green;">&#41;</span><br />
&nbsp; &nbsp; &nbsp; &nbsp; <span style="color: #339933; font-weight: bold;">,</span> <span style="color: green;">&#40;</span><span style="background-color: #3cb371;">&quot;/logify/&quot;</span><span style="color: #339933; font-weight: bold;">,</span> <span style="background-color: #3cb371;">&quot;Chatlog formatter&quot;</span><span style="color: green;">&#41;</span><br />
&nbsp; &nbsp; &nbsp; &nbsp; <span style="color: #339933; font-weight: bold;">,</span> <span style="color: green;">&#40;</span><span style="background-color: #3cb371;">&quot;/scalemate/&quot;</span><span style="color: #339933; font-weight: bold;">,</span> <span style="background-color: #3cb371;">&quot;Scalemate generator&quot;</span><span style="color: green;">&#41;</span><br />
&nbsp; &nbsp; &nbsp; &nbsp; <span style="color: green;">&#93;</span></div></div>
<p>to the toplevel of Site.hs and adding</p>
<div class="codecolorer-container haskell default" style="overflow:auto;white-space:nowrap;border:1px solid #9F9F9F;width:435px;"><div class="haskell codecolorer" style="padding:5px;font:normal 12px/1.4em Monaco, Lucida Console, monospace;white-space:nowrap">addSplices <span style="color: green;">&#91;</span><span style="color: green;">&#40;</span><span style="background-color: #3cb371;">&quot;nav&quot;</span><span style="color: #339933; font-weight: bold;">,</span> liftHeist <span style="color: #339933; font-weight: bold;">$</span> navSplice pages<span style="color: green;">&#41;</span><span style="color: green;">&#93;</span></div></div>
<p>to the app initializer. Now <code class="codecolorer text default"><span class="text">&lt;nav/&gt;</span></code> can be used in the template to automatically insert the nav link list and highlight the current page!</p>
<p>One small annoyance of this is that the generated HTML is all in one line, although since it&#8217;s not handwritten you probably won&#8217;t care so much, especially since Firebug and Chrome&#8217;s debugging tools will automatically do the indentation for you and let you collapse/expand child nodes at will. </p>
]]></content:encoded>
			<wfw:commentRss>http://www.amateurtopologist.com/blog/2012/01/15/writing-heist-splices-for-snap/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Name Your Type Variables!</title>
		<link>http://www.amateurtopologist.com/blog/2011/10/11/name-your-type-variables/</link>
		<comments>http://www.amateurtopologist.com/blog/2011/10/11/name-your-type-variables/#comments</comments>
		<pubDate>Tue, 11 Oct 2011 22:07:53 +0000</pubDate>
		<dc:creator>Patrick Hurst</dc:creator>
				<category><![CDATA[Computers]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[haskell]]></category>

		<guid isPermaLink="false">http://www.amateurtopologist.com/blog/?p=1310</guid>
		<description><![CDATA[Haskell&#8217;s type system is commonly touted as one of the most powerful features of the language; it&#8217;s often said that if a program compiles, it&#8217;s pretty likely to be correct. And while there are always going to be errors your type system can&#8217;t catch (logic errors, off-by-one-errors, etc.), I&#8217;ve found that the type system helps [...]]]></description>
			<content:encoded><![CDATA[<p>Haskell&#8217;s type system is commonly touted as one of the most powerful features of the language; it&#8217;s often said that if a program compiles, it&#8217;s pretty likely to be correct. And while there are always going to be errors your type system can&#8217;t catch (logic errors, off-by-one-errors, etc.), I&#8217;ve found that the type system helps ensure that your programs are put together correctly. If it typechecks, you&#8217;re probably not making a higher-level logic error; you might be trying to fit a red peg into a blue hole, but you&#8217;re not trying to fit a square peg into a round hole, so to speak.</p>
<p>The problem is that figuring out what the type variables in a polymorphic type (i.e., type like <code class="codecolorer haskell default"><span class="haskell"><a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:length"><span style="font-weight: bold;">length</span></a> <span style="color: #339933; font-weight: bold;">::</span> <span style="color: green;">&#91;</span>a<span style="color: green;">&#93;</span> <span style="color: #339933; font-weight: bold;">-&gt;</span> <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Int"><span style="color: #cccc00; font-weight: bold;">Int</span></a></span></code>) mean. Sure, in simple cases it&#8217;s simple; you look at a type signature like <code class="codecolorer haskell default"><span class="haskell">ifM <span style="color: #339933; font-weight: bold;">::</span> <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Monad"><span style="color: #cccc00; font-weight: bold;">Monad</span></a> m <span style="color: #339933; font-weight: bold;">=&gt;</span> m <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Bool"><span style="color: #cccc00; font-weight: bold;">Bool</span></a> <span style="color: #339933; font-weight: bold;">-&gt;</span> m a <span style="color: #339933; font-weight: bold;">-&gt;</span> m a <span style="color: #339933; font-weight: bold;">-&gt;</span> m a</span></code> and you know that <code class="codecolorer haskell default"><span class="haskell">m</span></code> is going to be some monad and <code class="codecolorer haskell default"><span class="haskell">a</span></code> is some arbitrary action. But take a look at <code class="codecolorer haskell default"><span class="haskell">validate <span style="color: #339933; font-weight: bold;">::</span> <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Monad"><span style="color: #cccc00; font-weight: bold;">Monad</span></a> m <span style="color: #339933; font-weight: bold;">=&gt;</span> Form m i e v a <span style="color: #339933; font-weight: bold;">-&gt;</span> Validator m e a <span style="color: #339933; font-weight: bold;">-&gt;</span> Form m i e v a</span></code>, from <a href="http://hackage.haskell.org/packages/archive/digestive-functors/0.1.0.2/doc/html/Text-Digestive-Validate.html">digestive-functors</a>. What do m, i, e, v, and a stand for? It&#8217;s pretty clear that <code class="codecolorer haskell default"><span class="haskell">m</span></code> is some monad, but what about the others? It turns out that:</p>
<ul>
<li><code class="codecolorer haskell default"><span class="haskell">i</span></code> represents the input to the form, or its environment (i.e., the submitted parameters)</li>
<li><code class="codecolorer haskell default"><span class="haskell">e</span></code> represents the the error type that can be produced</li>
<li><code class="codecolorer haskell default"><span class="haskell">v</span></code> represents the &#8216;view&#8217; of the form (how it&#8217;s represented to the user)</li>
<li><code class="codecolorer haskell default"><span class="haskell">a</span></code> represents the actual evaluation of a form (for example, in a registration form, it might be <code class="codecolorer haskell default"><span class="haskell"><span style="color: #06c; font-weight: bold;">data</span> Registration <span style="color: #339933; font-weight: bold;">=</span> Registration Text ByteString</span></code>)</li>
</ul>
<p>So my argument is that it might be better to describe it as <code class="codecolorer haskell default"><span class="haskell">Form m input err view result <span style="color: #339933; font-weight: bold;">-&gt;</span> Validator m err result <span style="color: #339933; font-weight: bold;">-&gt;</span> Form m input err view result</span></code>; this way, it&#8217;s clearer exactly what each type variable corresponds to.</p>
<p>Again, I&#8217;m not saying that single-letter type variables should be completely banned; something like <code class="codecolorer haskell default"><span class="haskell"><span style="color: green;">&#40;</span><span style="color: #339933; font-weight: bold;">&gt;&gt;=</span><span style="color: green;">&#41;</span> <span style="color: #339933; font-weight: bold;">::</span> <span style="color: green;">&#40;</span><a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Monad"><span style="color: #cccc00; font-weight: bold;">Monad</span></a> m<span style="color: green;">&#41;</span> <span style="color: #339933; font-weight: bold;">=&gt;</span> m a <span style="color: #339933; font-weight: bold;">-&gt;</span> <span style="color: green;">&#40;</span>a <span style="color: #339933; font-weight: bold;">-&gt;</span> m b<span style="color: green;">&#41;</span> <span style="color: #339933; font-weight: bold;">-&gt;</span> m b</span></code> is simple enough. The conventions that <code class="codecolorer haskell default"><span class="haskell">a</span></code> and <code class="codecolorer haskell default"><span class="haskell">b</span></code> stand for the to type variables in a generic function and that <code class="codecolorer haskell default"><span class="haskell">m</span></code> means &#8216;some arbitrary monad&#8217; are strong enough that it&#8217;s like using <code class="codecolorer haskell default"><span class="haskell">i</span></code> in a for loop in Python or whatever.</p>
<p>(Full disclosure: yes, lots of my own Haskell code uses single-letter type variables in places where I shouldn&#8217;t. I do intend to fix this).</p>
<p>But if you&#8217;re trying to learn some new framework or module, imagine how much nicer it would be if the types that the Haddock gives you actually told you something about what it&#8217;s doing (especially given that most Haskell modules seem to be lightly documented outside of their Haddock documentation, lacking example use cases). Programmers outgrew using single-letter variable names decades ago; we shouldn&#8217;t make the same mistake in the type system. This is part of the reason why I&#8217;m making such slow progress learning the Snaplet framework in the <a href="https://github.com/snapframework/snap/tree/0.6">dev version of snap</a>; it&#8217;s hard for me to get an intuition as to what the types are when I keep seeing <code class="codecolorer haskell default"><span class="haskell">Handler b v a</span></code> (<code class="codecolorer haskell default"><span class="haskell">b</span></code> is the base app/snaplet, <code class="codecolorer haskell default"><span class="haskell">v</span></code> is what&#8217;s being &#8216;focused on&#8217;, and <code class="codecolorer haskell default"><span class="haskell">a</span></code> is what the Handler &#8216;evaluates to&#8217;; <code class="codecolorer haskell default"><span class="haskell">Handler b v</span></code> has a Monad (and Functor, and MonadPlus, etc.) instance</code>).</p>
<p>By the way, the Snaplet framework, though slightly complicated, does wind up making a good deal of sense once you get used to it; I plan on writing up a post about what the commonly-used types/type constructors 'mean', as well as a post about how to make a very simple login Snap app. And I think, ultimately, documentation is one of the things Haskell sorely needs; not just more documentation on what individual functions do, but how those functions combine into a larger whole. Imagine trying to learn Django just by looking at the module documentation without having the benefit of the tutorial! But I think that's a subject for another post; I'm trying to get this blog active again, after all.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.amateurtopologist.com/blog/2011/10/11/name-your-type-variables/feed/</wfw:commentRss>
		<slash:comments>5</slash:comments>
		</item>
		<item>
		<title>A Haskell Newbie&#8217;s Guide to Text.JSON</title>
		<link>http://www.amateurtopologist.com/blog/2010/11/05/a-haskell-newbies-guide-to-text-json/</link>
		<comments>http://www.amateurtopologist.com/blog/2010/11/05/a-haskell-newbies-guide-to-text-json/#comments</comments>
		<pubDate>Fri, 05 Nov 2010 20:28:45 +0000</pubDate>
		<dc:creator>Patrick Hurst</dc:creator>
				<category><![CDATA[Computers]]></category>
		<category><![CDATA[haskell]]></category>

		<guid isPermaLink="false">http://www.amateurtopologist.com/?p=1027</guid>
		<description><![CDATA[JSON parsing is practically required for any modern language to be able to interface with web-based applications; most of them offer JSON as a reply format, and the alternative (usually XML) can be cumbersome to work with. But Haskell and its strong type system seem like they&#8217;d be extremely ill-suited to parsing JSON; an object&#8217;s [...]]]></description>
			<content:encoded><![CDATA[<p>JSON parsing is practically required for any modern language to be able to interface with web-based applications; most of them offer JSON as a reply format, and the alternative (usually XML) can be cumbersome to work with. But Haskell and its strong type system seem like they&#8217;d be extremely ill-suited to parsing JSON; an object&#8217;s values can be arbitrary JSON objects, including different types in the same object, and arrays can contain different types of objects. How do you deal with this? Well, if you&#8217;re going to be parsing JSON, then you have to have some kind of format that you&#8217;re expecting; you know that you&#8217;ll get, say, an array of objects each of which has a specific key that has an integer as a value, and that integer is all you care about. Fortunately, <a href="http://hackage.haskell.org/package/json-0.4.4">Text.JSON</a> exists, and once you get your head around how to use it, it&#8217;s simple. (Then again, so are many things in Haskell, but that doesn&#8217;t help me understand Arrows any better!)</p>
<p>So, let&#8217;s look at an example: getting a user&#8217;s public timeline from Twitter, and turning it into an array of Status values. We can ignore the process of actually sending Twitter the request and pulling the JSON out of the response, and for the sake of brevity we can ignore a bunch of the irrelevant data that Twitter returns, such as whether the tweet is a reply, the source, etc. Here&#8217;s the result of asking for the last 2 tweets from the <a href="http://twitter.com/twitter">official Twitter account</a>, with irrelevant detail stripped:</p>
<div class="codecolorer-container javascript default" style="overflow:auto;white-space:nowrap;border:1px solid #9F9F9F;width:435px;"><div class="javascript codecolorer" style="padding:5px;font:normal 12px/1.4em Monaco, Lucida Console, monospace;white-space:nowrap"><span style="color: #009900;">&#91;</span><br />
&nbsp; &nbsp; <span style="color: #009900;">&#123;</span><br />
&nbsp; &nbsp; <span style="color: #3366CC;">&quot;user&quot;</span><span style="color: #339933;">:</span> <span style="color: #009900;">&#123;</span> <span style="color: #3366CC;">&quot;screen_name&quot;</span><span style="color: #339933;">:</span> <span style="color: #3366CC;">&quot;twitter&quot;</span> <span style="color: #009900;">&#125;</span><span style="color: #339933;">,</span><br />
&nbsp; &nbsp; <span style="color: #3366CC;">&quot;text&quot;</span><span style="color: #339933;">:</span> <span style="color: #3366CC;">&quot;Read this guest post from @FiresideInt on his experience in Haiti http:<span style="color: #000099; font-weight: bold;">\/</span><span style="color: #000099; font-weight: bold;">\/</span>t.co<span style="color: #000099; font-weight: bold;">\/</span>mbMU56R&quot;</span><br />
&nbsp; &nbsp; <span style="color: #009900;">&#125;</span><span style="color: #339933;">,</span><br />
&nbsp; &nbsp; <span style="color: #009900;">&#123;</span><br />
&nbsp; &nbsp; <span style="color: #3366CC;">&quot;user&quot;</span><span style="color: #339933;">:</span> <span style="color: #009900;">&#123;</span> <span style="color: #3366CC;">&quot;screen_name&quot;</span><span style="color: #339933;">:</span> <span style="color: #3366CC;">&quot;twitter&quot;</span> <span style="color: #009900;">&#125;</span><span style="color: #339933;">,</span><br />
&nbsp; &nbsp; <span style="color: #3366CC;">&quot;text&quot;</span><span style="color: #339933;">:</span> <span style="color: #3366CC;">&quot;Do you use Twitter for a business, school, community group or another local organization? Follow @TwitterBusiness for tips and useful info!&quot;</span><br />
<span style="color: #009900;">&#125;</span><br />
<span style="color: #009900;">&#93;</span></div></div>
<p>So, what we have here is a list of objects; each object has a <code class="codecolorer text default"><span class="text">user</span></code> attribute whose <code class="codecolorer text default"><span class="text">screen_name</span></code> is the actual username; the object&#8217;s <code class="codecolorer text default"><span class="text">text</span></code> attribute then contains the actual text of the tweet. Let&#8217;s get to work.</p>
<h2>Making the JSON value</h2>
<p>It&#8217;s helpful to play around with whatever we&#8217;re trying to manipulate in ghci; so let&#8217;s load up the JSON into a String, json, and try to parse it:</p>
<div class="codecolorer-container haskell default" style="overflow:auto;white-space:nowrap;border:1px solid #9F9F9F;width:435px;"><div class="haskell codecolorer" style="padding:5px;font:normal 12px/1.4em Monaco, Lucida Console, monospace;white-space:nowrap"><a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html"><span style="color: #06c; font-weight: bold;">Prelude</span></a> Text<span style="color: #339933; font-weight: bold;">.</span>JSON<span style="color: #339933; font-weight: bold;">&gt;</span> json <span style="color: #339933; font-weight: bold;">&lt;-</span> <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:readFile"><span style="font-weight: bold;">readFile</span></a> <span style="background-color: #3cb371;">&quot;/Users/phurst/json&quot;</span><br />
<a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html"><span style="color: #06c; font-weight: bold;">Prelude</span></a> Text<span style="color: #339933; font-weight: bold;">.</span>JSON<span style="color: #339933; font-weight: bold;">&gt;</span> decode json<br />
<br />
<span style="color: #339933; font-weight: bold;">&lt;</span>interactive<span style="color: #339933; font-weight: bold;">&gt;</span>:<span style="color: red;">1</span>:<span style="color: red;">0</span>:<br />
&nbsp; &nbsp; Ambiguous <span style="color: #06c; font-weight: bold;">type</span> variable `a' <span style="color: #06c; font-weight: bold;">in</span> the constraint:<br />
&nbsp; &nbsp; &nbsp; `JSON a' arising from a use <span style="color: #06c; font-weight: bold;">of</span> `decode' at <span style="color: #339933; font-weight: bold;">&lt;</span>interactive<span style="color: #339933; font-weight: bold;">&gt;</span>:<span style="color: red;">1</span>:<span style="color: red;">0</span><span style="color: #339933; font-weight: bold;">-</span><span style="color: red;">10</span><br />
&nbsp; &nbsp; Probable fix: add a <span style="color: #06c; font-weight: bold;">type</span> signature that fixes these <span style="color: #06c; font-weight: bold;">type</span> variable<span style="color: green;">&#40;</span>s<span style="color: green;">&#41;</span></div></div>
<p>Why doesn&#8217;t this work? Well, <code class="codecolorer haskell default"><span class="haskell">decode</span></code> has type <code class="codecolorer haskell default"><span class="haskell"><span style="color: green;">&#40;</span>JSON a<span style="color: green;">&#41;</span> <span style="color: #339933; font-weight: bold;">=&gt;</span> <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:String"><span style="color: #cccc00; font-weight: bold;">String</span></a> <span style="color: #339933; font-weight: bold;">-&gt;</span> Result a</span></code>. So you can decode a string of JSON into anything in the JSON typeclass. Well, JSValue is in the JSON typeclass, so let&#8217;s try that:</p>
<div class="codecolorer-container haskell default" style="overflow:auto;white-space:nowrap;border:1px solid #9F9F9F;width:435px;"><div class="haskell codecolorer" style="padding:5px;font:normal 12px/1.4em Monaco, Lucida Console, monospace;white-space:nowrap"><a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html"><span style="color: #06c; font-weight: bold;">Prelude</span></a> Text<span style="color: #339933; font-weight: bold;">.</span>JSON<span style="color: #339933; font-weight: bold;">&gt;</span> decode json <span style="color: #339933; font-weight: bold;">::</span> Result JSValue<br />
Ok <span style="color: green;">&#40;</span>JSArray <span style="color: green;">&#91;</span>JSObject <span style="color: green;">&#40;</span>JSONObject <span style="color: green;">&#123;</span>fromJSObject <span style="color: #339933; font-weight: bold;">=</span> <span style="color: green;">&#91;</span><span style="color: green;">&#40;</span><span style="background-color: #3cb371;">&quot;user&quot;</span><span style="color: #339933; font-weight: bold;">,</span>JSObject <span style="color: green;">&#40;</span>JSONObject <span style="color: green;">&#123;</span>fromJSObject <span style="color: #339933; font-weight: bold;">=</span> <span style="color: green;">&#91;</span><span style="color: green;">&#40;</span><span style="background-color: #3cb371;">&quot;screen_name&quot;</span><span style="color: #339933; font-weight: bold;">,</span>JSString <span style="color: green;">&#40;</span>JSONString <span style="color: green;">&#123;</span>fromJSString <span style="color: #339933; font-weight: bold;">=</span> <span style="background-color: #3cb371;">&quot;twitter&quot;</span><span style="color: green;">&#125;</span><span style="color: green;">&#41;</span><span style="color: green;">&#41;</span><span style="color: green;">&#93;</span><span style="color: green;">&#125;</span><span style="color: green;">&#41;</span><span style="color: green;">&#41;</span><span style="color: #339933; font-weight: bold;">,</span> <span style="color: green;">&#40;</span>rest <span style="color: #06c; font-weight: bold;">of</span> line omitted<span style="color: green;">&#41;</span></div></div>
<p>Wordy. But we did get a successful parse (as indicated by the Ok); we then have a JSArray which contains the two JSONObjects. But in order to get at the things inside the JSArray, we&#8217;d have to manually remove the constructor via <code class="codecolorer text default"><span class="text">(\(JSArray x) -&gt; x)</span></code> or something. And then if we didn&#8217;t get an array (because we got an error!), we would get an unfriendly &#8220;Non-exhaustive patterns in lambda&#8221; exception. So, what do we do? Well, we&#8217;re trying to get a list of values, so let&#8217;s ask decode to give us one:</p>
<div class="codecolorer-container haskell default" style="overflow:auto;white-space:nowrap;border:1px solid #9F9F9F;width:435px;"><div class="haskell codecolorer" style="padding:5px;font:normal 12px/1.4em Monaco, Lucida Console, monospace;white-space:nowrap"><a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html"><span style="color: #06c; font-weight: bold;">Prelude</span></a> Text<span style="color: #339933; font-weight: bold;">.</span>JSON<span style="color: #339933; font-weight: bold;">&gt;</span> decode json <span style="color: #339933; font-weight: bold;">::</span> Result <span style="color: green;">&#91;</span>JSValue<span style="color: green;">&#93;</span><br />
Ok <span style="color: green;">&#91;</span>JSObject <span style="color: green;">&#40;</span>JSONObject <span style="color: green;">&#123;</span>fromJSObject <span style="color: #339933; font-weight: bold;">=</span> <span style="color: green;">&#91;</span><span style="color: green;">&#40;</span><span style="background-color: #3cb371;">&quot;user&quot;</span><span style="color: #339933; font-weight: bold;">,</span>JSObject <span style="color: green;">&#40;</span>JSONObject <span style="color: green;">&#123;</span>fromJSObject <span style="color: #339933; font-weight: bold;">=</span> <span style="color: green;">&#91;</span><span style="color: green;">&#40;</span><span style="background-color: #3cb371;">&quot;screen_name&quot;</span><span style="color: #339933; font-weight: bold;">,</span>JSString <span style="color: green;">&#40;</span>JSONString <span style="color: green;">&#123;</span>fromJSString <span style="color: #339933; font-weight: bold;">=</span> <span style="background-color: #3cb371;">&quot;twitter&quot;</span><span style="color: green;">&#125;</span><span style="color: green;">&#41;</span><span style="color: green;">&#41;</span><span style="color: green;">&#93;</span><span style="color: green;">&#125;</span><span style="color: green;">&#41;</span><span style="color: green;">&#41;</span><span style="color: #339933; font-weight: bold;">,</span> <span style="color: green;">&#40;</span>rest omitted<span style="color: green;">&#41;</span></div></div>
<p>Awesome! We have an array of JSObjects. But again, we&#8217;re still stuck inside that JSObject &#8216;wrapper&#8217;. This annoyed me for a while, until I realized that JSObject is both a data constructor in the JSValue type, and its own type! So we can &#8216;ask&#8217; decode to give us a list of JSObjects:</p>
<div class="codecolorer-container haskell default" style="overflow:auto;white-space:nowrap;border:1px solid #9F9F9F;width:435px;"><div class="haskell codecolorer" style="padding:5px;font:normal 12px/1.4em Monaco, Lucida Console, monospace;white-space:nowrap"><a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html"><span style="color: #06c; font-weight: bold;">Prelude</span></a> Text<span style="color: #339933; font-weight: bold;">.</span>JSON<span style="color: #339933; font-weight: bold;">&gt;</span> <span style="color: #06c; font-weight: bold;">let</span> decoded <span style="color: #339933; font-weight: bold;">=</span> decode json <span style="color: #339933; font-weight: bold;">::</span> Result <span style="color: green;">&#91;</span>JSObject JSValue<span style="color: green;">&#93;</span><br />
Ok <span style="color: green;">&#91;</span>JSONObject <span style="color: green;">&#123;</span>fromJSObject <span style="color: #339933; font-weight: bold;">=</span> <span style="color: green;">&#91;</span><span style="color: green;">&#40;</span><span style="background-color: #3cb371;">&quot;user&quot;</span><span style="color: #339933; font-weight: bold;">,</span>JSObject <span style="color: green;">&#40;</span>JSONObject <span style="color: green;">&#123;</span>fromJSObject <span style="color: #339933; font-weight: bold;">=</span> <span style="color: green;">&#91;</span><span style="color: green;">&#40;</span><span style="background-color: #3cb371;">&quot;screen_name&quot;</span><span style="color: #339933; font-weight: bold;">,</span>JSString <span style="color: green;">&#40;</span>JSONString <span style="color: green;">&#123;</span>fromJSString <span style="color: #339933; font-weight: bold;">=</span> <span style="background-color: #3cb371;">&quot;twitter&quot;</span><span style="color: green;">&#125;</span><span style="color: green;">&#41;</span><span style="color: green;">&#41;</span><span style="color: green;">&#93;</span><span style="color: green;">&#125;</span><span style="color: green;">&#41;</span><span style="color: green;">&#41;</span><span style="color: #339933; font-weight: bold;">,</span> <span style="color: green;">&#40;</span>rest omitted<span style="color: green;">&#41;</span></div></div>
<p>Now we&#8217;re in business. We have a list of JSObjects, which is as good as we&#8217;re going to get. Now we need to actually deal with getting data out of them. It&#8217;s a good idea to split the &#8216;parse an individual item&#8217; logic off into its own function, which I&#8217;ll call makeStatus.</p>
<h2>Writing makeStatus, dealing with nested objects</h2>
<p>Now, we could call <code class="codecolorer haskell default"><span class="haskell">fromJSObject <span style="color: #339933; font-weight: bold;">::</span> JSObject e <span style="color: #339933; font-weight: bold;">-&gt;</span> <span style="color: green;">&#91;</span><span style="color: green;">&#40;</span><a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:String"><span style="color: #cccc00; font-weight: bold;">String</span></a><span style="color: #339933; font-weight: bold;">,</span> e<span style="color: green;">&#41;</span><span style="color: green;">&#93;</span></span></code>, search through the pairs, and then deal with them manually. But that&#8217;d be messy, and we wouldn&#8217;t get error handling if for some reason Twitter mysteriously didn&#8217;t give us a &#8220;user&#8221; object. Instead, we should take advantage of the function <code class="codecolorer haskell default"><span class="haskell">valFromObj <span style="color: #339933; font-weight: bold;">::</span> JSON a <span style="color: #339933; font-weight: bold;">=&gt;</span> <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:String"><span style="color: #cccc00; font-weight: bold;">String</span></a> <span style="color: #339933; font-weight: bold;">-&gt;</span> JSObject JSValue <span style="color: #339933; font-weight: bold;">-&gt;</span> Result a</span></code>, and the fact that Result is a monad. Together, these mean that we can write simple code:</p>
<div class="codecolorer-container haskell default" style="overflow:auto;white-space:nowrap;border:1px solid #9F9F9F;width:435px;"><div class="haskell codecolorer" style="padding:5px;font:normal 12px/1.4em Monaco, Lucida Console, monospace;white-space:nowrap"><span style="color: #06c; font-weight: bold;">data</span> Status <span style="color: #339933; font-weight: bold;">=</span> Status <span style="color: green;">&#123;</span> user <span style="color: #339933; font-weight: bold;">::</span> <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:String"><span style="color: #cccc00; font-weight: bold;">String</span></a><span style="color: #339933; font-weight: bold;">,</span> text <span style="color: #339933; font-weight: bold;">::</span> <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:String"><span style="color: #cccc00; font-weight: bold;">String</span></a> <span style="color: green;">&#125;</span><br />
<br />
makeStatus <span style="color: #339933; font-weight: bold;">::</span> JSObject JSValue <span style="color: #339933; font-weight: bold;">-&gt;</span> Result Status<br />
makeStatus tweet <span style="color: #339933; font-weight: bold;">=</span> <span style="color: #06c; font-weight: bold;">let</span> <span style="color: green;">&#40;</span><span style="color: #339933; font-weight: bold;">!</span><span style="color: green;">&#41;</span> <span style="color: #339933; font-weight: bold;">=</span> <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:flip"><span style="font-weight: bold;">flip</span></a> valFromObj <span style="color: #06c; font-weight: bold;">in</span> <span style="color: #06c; font-weight: bold;">do</span><br />
&nbsp; &nbsp; userObject <span style="color: #339933; font-weight: bold;">&lt;-</span> tweet <span style="color: #339933; font-weight: bold;">!</span> <span style="background-color: #3cb371;">&quot;user&quot;</span><br />
&nbsp; &nbsp; user <span style="color: #339933; font-weight: bold;">&lt;-</span> userObject <span style="color: #339933; font-weight: bold;">!</span> <span style="background-color: #3cb371;">&quot;screen_name&quot;</span><br />
&nbsp; &nbsp; text <span style="color: #339933; font-weight: bold;">&lt;-</span> tweet <span style="color: #339933; font-weight: bold;">!</span> <span style="background-color: #3cb371;">&quot;text&quot;</span><br />
&nbsp; &nbsp; <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:return"><span style="font-weight: bold;">return</span></a> Status <span style="color: green;">&#123;</span>user <span style="color: #339933; font-weight: bold;">=</span> user<span style="color: #339933; font-weight: bold;">,</span> text <span style="color: #339933; font-weight: bold;">=</span> text<span style="color: green;">&#125;</span></div></div>
<p>Here, I&#8217;ve defined (!) for brevity&#8217;s sake, then used the Monad instance of Result to &#8216;chain together&#8217; my calls to (!). At the end, I wrap the user and text into a Status value, then &#8216;return&#8217; it back into the Result monad. Let&#8217;s see it:</p>
<div class="codecolorer-container haskell default" style="overflow:auto;white-space:nowrap;border:1px solid #9F9F9F;width:435px;"><div class="haskell codecolorer" style="padding:5px;font:normal 12px/1.4em Monaco, Lucida Console, monospace;white-space:nowrap"><a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html"><span style="color: #06c; font-weight: bold;">Prelude</span></a> Text<span style="color: #339933; font-weight: bold;">.</span>JSON<span style="color: #339933; font-weight: bold;">&gt;</span> <span style="color: #06c; font-weight: bold;">let</span> tweet <span style="color: #339933; font-weight: bold;">=</span> <span style="color: green;">&#40;</span>\<span style="color: green;">&#40;</span>Ok x<span style="color: green;">&#41;</span> <span style="color: #339933; font-weight: bold;">-&gt;</span> x<span style="color: green;">&#41;</span> decoded <span style="color: #339933; font-weight: bold;">!!</span> <span style="color: red;">0</span> <span style="color: #5d478b; font-style: italic;">-- just to get a non-monadic JSObject for now</span><br />
<a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html"><span style="color: #06c; font-weight: bold;">Prelude</span></a> Text<span style="color: #339933; font-weight: bold;">.</span>JSON<span style="color: #339933; font-weight: bold;">&gt;</span> makeStatus tweet<br />
Ok <span style="color: green;">&#40;</span>Status <span style="color: green;">&#123;</span>user <span style="color: #339933; font-weight: bold;">=</span> <span style="background-color: #3cb371;">&quot;twitter&quot;</span><span style="color: #339933; font-weight: bold;">,</span> text <span style="color: #339933; font-weight: bold;">=</span> <span style="background-color: #3cb371;">&quot;Read this guest post from @FiresideInt on his experience in Haiti http://t.co/mbMU56R&quot;</span><span style="color: green;">&#125;</span><span style="color: green;">&#41;</span></div></div>
<p>We&#8217;ve successfully parsed a status update into its components! If we cared, we could pull more information out of the original object, such as real name, avatar URLs, time of posting, etc. But first, we have a more interesting problem: how do we join these two together?</p>
<h2>Combining decoding and parsing</h2>
<p>Look at the type for our decoding function and for our parse function:</p>
<div class="codecolorer-container haskell default" style="overflow:auto;white-space:nowrap;border:1px solid #9F9F9F;width:435px;"><div class="haskell codecolorer" style="padding:5px;font:normal 12px/1.4em Monaco, Lucida Console, monospace;white-space:nowrap"><a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html"><span style="color: #06c; font-weight: bold;">Prelude</span></a> Text<span style="color: #339933; font-weight: bold;">.</span>JSON<span style="color: #339933; font-weight: bold;">&gt;</span> :t \json <span style="color: #339933; font-weight: bold;">-&gt;</span> decode json <span style="color: #339933; font-weight: bold;">::</span> Result <span style="color: green;">&#91;</span>JSObject JSValue<span style="color: green;">&#93;</span><br />
\json <span style="color: #339933; font-weight: bold;">-&gt;</span> decode json <span style="color: #339933; font-weight: bold;">::</span> Result <span style="color: green;">&#91;</span>JSObject JSValue<span style="color: green;">&#93;</span><br />
&nbsp; <span style="color: #339933; font-weight: bold;">::</span> <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:String"><span style="color: #cccc00; font-weight: bold;">String</span></a> <span style="color: #339933; font-weight: bold;">-&gt;</span> Result <span style="color: green;">&#91;</span>JSObject JSValue<span style="color: green;">&#93;</span><br />
<a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html"><span style="color: #06c; font-weight: bold;">Prelude</span></a> Text<span style="color: #339933; font-weight: bold;">.</span>JSON<span style="color: #339933; font-weight: bold;">&gt;</span> :t makeStatus<br />
makeStatus <span style="color: #339933; font-weight: bold;">::</span> JSObject JSValue <span style="color: #339933; font-weight: bold;">-&gt;</span> Result Status</div></div>
<p>Clearly, we&#8217;d like it if we could put those in one function with little effort. So, let&#8217;s abstract out the specifics: we have functions <code class="codecolorer text default"><span class="text">f :: a -&gt; m [b]</span></code> and <code class="codecolorer text default"><span class="text">g :: b -&gt; m c</span></code>. We want <code class="codecolorer text default"><span class="text">h :: a -&gt; m [c]</span></code>. It&#8217;s obvious we want to map g, but a normal map isn&#8217;t right, since we&#8217;d get a function of type <code class="codecolorer text default"><span class="text">[b] -&gt; [m c]</span></code>; we want the monad to be <b>outside</b> the list! So we use the monadic map, <code class="codecolorer text default"><span class="text">mapM g :: [b] -&gt; m [c]</span></code>.</p>
<p>Now, we have our two functions, and we could use do-block syntax to combine them:</p>
<div class="codecolorer-container haskell default" style="overflow:auto;white-space:nowrap;border:1px solid #9F9F9F;width:435px;"><div class="haskell codecolorer" style="padding:5px;font:normal 12px/1.4em Monaco, Lucida Console, monospace;white-space:nowrap">parseTimeline json <span style="color: #339933; font-weight: bold;">=</span> <span style="color: #06c; font-weight: bold;">do</span><br />
&nbsp; &nbsp; decoded <span style="color: #339933; font-weight: bold;">&lt;-</span> decode json <span style="color: #339933; font-weight: bold;">::</span> Result <span style="color: green;">&#91;</span>JSObject JSValue<span style="color: green;">&#93;</span><br />
&nbsp; &nbsp; <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:mapM"><span style="font-weight: bold;">mapM</span></a> makeStatus decoded</div></div>
<p>But do-block syntax isn&#8217;t terribly &#8216;Haskell-y&#8217;, and there&#8217;s only two lines of it. Surely there&#8217;s a way to combine them! And if we use Hoogle and <a href="http://www.haskell.org/hoogle/?hoogle=(a+-%3E+m+b')+-%3E+(b'+-%3E+m+c')+-%3E+(a+-%3E+m+c')">search for <code class="codecolorer text default"><span class="text">(a -&gt; m b') -&gt; (b' -&gt; m c') -&gt; (a -&gt; m c')</span></code></a> (using primes to represent lists), we find that <a href="http://haskell.org/ghc/docs/6.12.1/html/libraries/base-4.2.0.0/Control-Monad.html#v:%3E=%3E">(>=>) in Control.Monad</a> does exactly what we want! So we can rewrite it as a one-liner:</p>
<div class="codecolorer-container haskell default" style="overflow:auto;white-space:nowrap;border:1px solid #9F9F9F;width:435px;"><div class="haskell codecolorer" style="padding:5px;font:normal 12px/1.4em Monaco, Lucida Console, monospace;white-space:nowrap">parseTimeline <span style="color: #339933; font-weight: bold;">::</span> <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:String"><span style="color: #cccc00; font-weight: bold;">String</span></a> <span style="color: #339933; font-weight: bold;">-&gt;</span> Result <span style="color: green;">&#91;</span>Status<span style="color: green;">&#93;</span><br />
parseTimeline <span style="color: #339933; font-weight: bold;">=</span> decode <span style="color: #339933; font-weight: bold;">&gt;=&gt;</span> <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:mapM"><span style="font-weight: bold;">mapM</span></a> makeStatus</div></div>
<p>Two things to notice: first, the explicit type declaration for decode isn&#8217;t necessary. In fact, it wasn&#8217;t necessary in the above version either. This generally happens once you&#8217;ve actually written the processing part of your JSON handler; the type signature of the processor forces the types in the parser! Second, the function is now pointfree; there&#8217;s no point in including argument, so we might as well omit it.</p>
<h2>Errors</h2>
<p>Now, there&#8217;s one problem here that I haven&#8217;t addressed. While we do get error handling for &#8216;free&#8217;, since monadic handling of Result values will pass through errors, the errors are typically unhelpful; they only show what failed to parse. And if we failed to parse the initial array, for example, that probably means that Twitter gave us an error message instead, and we&#8217;d like to know what it says! Finally, our output is stuck in the Result monad until we get it out.</p>
<p>The solution here is to write an error handler combinator; it takes a processor and a JSON string, and tries to process it; if the result pattern-matches against <code class="codecolorer text default"><span class="text">Ok x</span></code>, then we parsed successfully; if it doesn&#8217;t, then we parse it again looking for the error message and handle that according to however your program deals with errors.<br />
For my part, I <a href="https://github.com/veinor/askitter/blob/master/Web/Twitter.hs#L81">kind of cheat</a>; I don&#8217;t use the JSON in the error combinator, I use the raw HTML response, and if the parse fails, I throw an exception according to to the access code returned. But I eventually do plan to actually grab the error message, which will simplify the control flow of the library and give me more specifics on what went wrong.</p>
<hr />
This entire post was inspired by my experiences writing <a href="https://github.com/veinor/askitter">askitter</a>, a Haskell Twitter library using OAuth for authentication. Most of the &#8216;final&#8217; code in here is copied straight from there, aside from various wrapping/unwrapping functions. It&#8217;s been very useful for learning lots of things; it&#8217;s been suggested that I &#8216;hide&#8217; the fact that Twitter only gives you chunks of 20 tweets at a time by using <a href="http://hackage.haskell.org/package/enumerator">enumerators</a>; when/if I get around to that, I&#8217;ll write an explanation.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.amateurtopologist.com/blog/2010/11/05/a-haskell-newbies-guide-to-text-json/feed/</wfw:commentRss>
		<slash:comments>7</slash:comments>
		</item>
		<item>
		<title>Security vulnerability in Haskell with CGI</title>
		<link>http://www.amateurtopologist.com/blog/2010/04/23/security-vulnerability-in-haskell-with-cgi/</link>
		<comments>http://www.amateurtopologist.com/blog/2010/04/23/security-vulnerability-in-haskell-with-cgi/#comments</comments>
		<pubDate>Fri, 23 Apr 2010 19:18:11 +0000</pubDate>
		<dc:creator>Patrick Hurst</dc:creator>
				<category><![CDATA[Computers]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[cgi]]></category>
		<category><![CDATA[haskell]]></category>
		<category><![CDATA[planet sipb]]></category>
		<category><![CDATA[security]]></category>

		<guid isPermaLink="false">http://www.amateurtopologist.com/?p=821</guid>
		<description><![CDATA[Compiled Haskell programs all include special RTS (Run Time System) options, that change things like the number of cores that it runs on, various internal things relating to how often garbage collection runs, etc. They&#8217;re specified by invoking the program like ./foo +RTS -m10 -k2000 -RTS to run the GHC-compiled program &#8216;foo&#8217;, reserving 10% of [...]]]></description>
			<content:encoded><![CDATA[<p>Compiled Haskell programs all include special <a title="RTS (Run Time System) options" href="http://www.haskell.org/ghc/docs/latest/html/users_guide/runtime-control.html">RTS (Run Time System) options</a>, that change things like the number of cores that it runs on, various internal things relating to how often garbage collection runs, etc. They&#8217;re specified by invoking the program like ./foo +RTS -m10 -k2000 -RTS to run the GHC-compiled program &#8216;foo&#8217;, reserving 10% of the heap for allocation and setting each thread&#8217;s stack size to a maximum of 2000 bytes. In the current build of GHC, there is no way to disable these options from working (although the option &#8211;RTS will make all further options be interpreted as normal, non-RTS options). The problem is that the option -tout will write profiling data to the file out. So, if your program is setuid root, anybody who runs it can write the profiling data to, say /etc/passwd and render the system unusable. They don&#8217;t get to pick what gets written, so they can&#8217;t add a backdoor for themselves, but they can essentially scribble over whatever files they want. This is bug <a href="http://hackage.haskell.org/trac/ghc/ticket/3910">#3910</a>, and the fix (disabling RTS by default) has been uploaded.</p>
<p>Now, one of the more little-known features of CGI is that if you pass a <a class="zem_slink" title="Query string" rel="wikipedia" href="http://en.wikipedia.org/wiki/Query_string">query string</a> that does not contain any = signs to a CGI script, the httpd may pass the string along as command-line arguments. This is specified in section 4.4 of <a href="http://www.ietf.org/rfc/rfc3875">RFC 3875</a>, and it specifies how the query string SHOULD be turned into arguments (although it does not say anything about whether the httpd should behave this way, only that some do). <a href="http://code.amateurtopologist.com/args.pl?foo%20bar+%2BRTS+2">This</a> is an example script that only outputs its arguments in a comma-separated list; the link gives it some sample arguments. Note that by URL-escaping, you can send arbitrary strings through&#8230; including +RTS. So if that were, say, a Haskell script, I could pass the query string ?%2BRTS+-tindex.html+-RTS and overwrite index.html.</p>
<p>There are three ways to get around this: first, GHC 6.12.2 has the -no-rtsopts option, which will obviously disable RTS options. So if you just recompile your script with that, it&#8217;ll be safe. Note that 6.14 will disable the RTS options by default; the 6.12.2 patch didn&#8217;t for backwards-compatibility reasons. Second, if you don&#8217;t want to use 6.12.2 for whatever reason, you can wrap it in a shell script that calls it with no options. For example, replace the Haskell script with a shell script called, say, hscript.cgi (if your Haskell program is called hscript) that calls it with no arguments, e.g.</p>
<div class="codecolorer-container bash default" style="overflow:auto;white-space:nowrap;border:1px solid #9F9F9F;width:435px;"><div class="bash codecolorer" style="padding:5px;font:normal 12px/1.4em Monaco, Lucida Console, monospace;white-space:nowrap"><span style="color: #666666; font-style: italic;">#!/bin/bash</span><br />
.<span style="color: #000000; font-weight: bold;">/</span>hscript.real</div></div>
<p>and rename the Haskell script to hscript.real, so that it doesn&#8217;t get run as CGI (I&#8217;m assuming that .real files don&#8217;t get run as CGI on your machine!) Another thing you can do is to add the following to your .htaccess, which will give 403 Forbidden errors to anybody passing RTS arguments in the URL:</p>
<div class="codecolorer-container text default" style="overflow:auto;white-space:nowrap;border:1px solid #9F9F9F;width:435px;"><div class="text codecolorer" style="padding:5px;font:normal 12px/1.4em Monaco, Lucida Console, monospace;white-space:nowrap">RewriteEngine on<br />
RewriteCond %{QUERY_STRING} ^(?:[^=]*\+)?(?:%2[bB]|(?:-|%2[dD]){1,2})(?:%52|R)(?:%54|T)(?:%53|S)(?:\+[^=]*)?$<br />
RewriteRule ^ - [F]</div></div>
<p>This will solve it for every Haskell script you use, but relies on the regex being correct, which isn&#8217;t something I can guarantee.</p>
<div class="zemanta-pixie" style="margin-top: 10px; height: 15px;"><img class="zemanta-pixie-img" style="border: none; float: right;" src="http://img.zemanta.com/pixy.gif?x-id=dc920732-9bc7-483f-86ba-973d77aa0634" alt="" /><span class="zem-script more-related pretty-attribution"><script src="http://static.zemanta.com/readside/loader.js" type="text/javascript"></script></span></div>
]]></content:encoded>
			<wfw:commentRss>http://www.amateurtopologist.com/blog/2010/04/23/security-vulnerability-in-haskell-with-cgi/feed/</wfw:commentRss>
		<slash:comments>6</slash:comments>
		</item>
		<item>
		<title>dissociated-blogosphere: never have to write an original post again!</title>
		<link>http://www.amateurtopologist.com/blog/2010/04/06/dissociated-blogosphere-never-have-to-write-an-original-post-again/</link>
		<comments>http://www.amateurtopologist.com/blog/2010/04/06/dissociated-blogosphere-never-have-to-write-an-original-post-again/#comments</comments>
		<pubDate>Wed, 07 Apr 2010 01:18:30 +0000</pubDate>
		<dc:creator>Patrick Hurst</dc:creator>
				<category><![CDATA[Computers]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[dissociated blogosphere]]></category>
		<category><![CDATA[haskell]]></category>
		<category><![CDATA[planet sipb]]></category>

		<guid isPermaLink="false">http://www.amateurtopologist.com/?p=796</guid>
		<description><![CDATA[For the past two weeks or so, I&#8217;ve been working off and on on a project called dissociated blogosphere (OSX and Linux binaries here). It takes a bunch of URLs, looks through them for an RSS for the raw content of the posts, and then stores the words of the posts in an array. It [...]]]></description>
			<content:encoded><![CDATA[<p>For the past two weeks or so, I&#8217;ve been working off and on on a project called <a href="http://github.com/veinor/dissociated-blogosphere">dissociated blogosphere</a> (OSX and Linux binaries <a href="http://code.amateurtopologist.com/dissociated-blogosphere/bin">here</a>). It takes a bunch of URLs, looks through them for an RSS for the raw content of the posts, and then stores the words of the posts in an array. It then picks N random, consecutive words (where in this case N is 2), and starts generating new text, by picking a new word x% of the time if x% of the time, the previous N words were followed by that word. For example, if 90% of the time, the words &#8216;the quick&#8217; were followed by &#8216;brown&#8217;, and the other 10% of the time, they were followed by &#8216;red&#8217;, then when the two-word phrase &#8216;the quick&#8217; was randomly generated, it would pick &#8216;brown&#8217; 9 times out of 10, and &#8216;red&#8217; 1 time out of 10. This is the algorithm <a class="zem_slink" title="Emacs" rel="homepage" href="http://www.gnu.org/software/emacs/">Emacs</a>&#8216;s <a class="zem_slink" title="Dissociated press" rel="wikipedia" href="http://en.wikipedia.org/wiki/Dissociated_press">dissociated press</a> feature uses, hence the name. Running it a few times on this site and picking some of my favorite sentences gives:</p>
<blockquote><p>
Second, I ignored the axes of the work you envision. So start small, and think about the free group on two generators, which is obviously highly undesirable behavior. However, it does have the web interface, I&#8217;ll have it up by last week, but that obviously didnt happen. Taking into account the fact that I&#8217;m using. The central thing that makes MS Paint Adventures unique to the point where it&#8217;s my go-to language for random programs (I still use Python for that), but if we pick two of them and rotate one of the set of all rotations that you have some custom function you want soup or salad, both is not a valid answer.</p></blockquote>
</blockquote>
<p>It&#8217;s my first medium-scale project written in <a class="zem_slink" title="Haskell (programming language)" rel="homepage" href="http://haskell.org">Haskell</a> (even though there isn&#8217;t a lot of code, what little was there was not trivial to write), and I&#8217;ve learned several lessons from it:</p>
<ul>
<li><strong>The <a title="Haskell wiki" href="http://www.haskell.org/haskellwiki/Haskell">Haskell wiki</a> is an excellent resource.</strong> When I was trying to learn how to use HXT, the <a title="HXT" href="http://www.fh-wedel.de/~si/HXmlToolbox/">Haskell XML Toolbox</a>, I found the provided documentation somewhat inadequate. But the <a title="HXT article on the Haskell wiki" href="http://www.haskell.org/haskellwiki/HXT">HXT article on the Haskell wiki</a> is an excellent introduction to the filter abstraction, which is all that I need for the basic stuff that I&#8217;m using.</li>
<li><strong>Read the Haddock documentation.</strong> The HXT article, as useful as it was, didn&#8217;t cover a couple essential things I needed to know (such as how to pull all elements with type &#8220;application/rss+xml&#8221;). So I look at the documentation for <a title="documentation for Text.XML.HXT.Arrow.XmlArrow" href="http://hackage.haskell.org/packages/archive/hxt/8.5.2/doc/html/Text-XML-HXT-Arrow-XmlArrow.html">Text.XML.HXT.Arrow.XmlArrow</a> (the module containing the arrows that HXT uses to filter XML), and saw that <code class="codecolorer haskell default"><span class="haskell">hasAttrValue <span style="color: #339933; font-weight: bold;">::</span> <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:String"><span style="color: #cccc00; font-weight: bold;">String</span></a> <span style="color: #339933; font-weight: bold;">-&gt;</span> <span style="color: green;">&#40;</span><a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:String"><span style="color: #cccc00; font-weight: bold;">String</span></a> <span style="color: #339933; font-weight: bold;">-&gt;</span> <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Bool"><span style="color: #cccc00; font-weight: bold;">Bool</span></a><span style="color: green;">&#41;</span> <span style="color: #339933; font-weight: bold;">-&gt;</span> a XmlTree XmlTree</span></code> looks about right; from the type, I can guess (correctly) that I need to pass it the attribute and a prediate on the value of the attribute (i.e., <code class="codecolorer haskell default"><span class="haskell">hasAttrValue <span style="background-color: #3cb371;">&quot;href&quot;</span> <span style="color: green;">&#40;</span><span style="color: #339933; font-weight: bold;">==</span> <span style="background-color: #3cb371;">&quot;application/rss+xml&quot;</span><span style="color: green;">&#41;</span></span></code>).</li>
<li><strong>One goal at a time.</strong> This isn&#8217;t specific to Haskell. When I started on this, I meant for it to require you to provide the RSS feed. Then, I realized that having a larger corpus might be better, so I added the ability to pull from multiple feeds. Then I decided that expecting people to find the RSS feed by hand might be a bit much, so I rewrote it to pull the RSS feed from the site. And I eventually plan to write a CGI frontend so that you can just run it online. If I had decided from the start to do all these things, I probably never would&#8217;ve gotten started. As <a href="http://web.archive.org/web/20050404020308/http://www.linuxtimes.net/modules.php?name=News&amp;file=article&amp;sid=145">Linus Torvalds said</a>:<br />
<blockquote><p>Nobody should start to undertake a large project. You start with a small trivial project, and you should never expect it to get large. If you do, you&#8217;ll just overdesign and generally think it is more important than it likely is at that stage. Or worse, you might be scared away by the sheer size of the work you envision. So start small, and think about the details. Don&#8217;t think about some big picture and fancy design. If it doesn&#8217;t solve some fairly immediate need, it&#8217;s almost certainly over-designed.</p></blockquote>
</li>
<li><strong>Strip and gzip your executables if you&#8217;re going to distribute them.</strong> Due to the fact that I&#8217;m statically linking in HXT, which is a sizeable library, the compiled, non-stripped version of dissociated-blogosphere is a whopping 12 megabytes. This isn&#8217;t due to inefficiencies in my own code, but due to the sheer size of the HXT library. Running the Unix command line utility <a href="http://en.wikipedia.org/wiki/Strip_(Unix)">strip</a> (which only removes internal debugging information) cuts it down to about 5 MB, and then gzipping the binaries takes it down to a little over a megabyte.</li>
<li><strong>Split things into libraries where it&#8217;s appropriate.</strong> Part of the problem with using HXT is that it makes recompilation slow; if I could do it all over again, I might have used <a href="http://www.haskell.org/HaXml/">HaXml</a>, but HXT has the advantage of having nontrivial amounts of documentation written about it (on the Haskell wiki). If I had instead split the RSS parsing code into its own library, I could have only recompiled those parts whenever I touched them, which wasn&#8217;t nearly as often as I touched the code frontend. Plus, it&#8217;s just good programming practice.</li>
</ul>
<p>So what do I have planned for dissociated-blogosphere? First off, I plan to make it faster by caching RSS lookups; by storing a map from page URLs to RSS feed, I can cut the number of network requests in half. Second, I plan to implement actual error handling; right now if you give it a bad URL it fails and doesn&#8217;t produce any useful output, regardless of whether other URLs are good. Third, I&#8217;m going to split out the RSS part into its own library, which I might make its own package on hackage. Fourth, I intend to eventually write a web interface (either in Haskell or in Python) so that you don&#8217;t have to download and install it. I originally intended to have the web interface up by last week, but that obviously didn&#8217;t happen. Taking into account the fact that it&#8217;ll take longer than I think it does, I&#8217;m guessing I&#8217;ll have it up by two weeks from now (so, a month). And finally, when/if I do the web interface, I&#8217;ll have it color the text according to which blog it&#8217;s from, or maybe even output xterm color codes if I don&#8217;t write the web interface.</p>
<div class="zemanta-pixie" style="margin-top: 10px; height: 15px;"><img class="zemanta-pixie-img" style="border: none; float: right;" src="http://img.zemanta.com/pixy.gif?x-id=d52a7644-8d19-4dd2-b6d2-4603793b4e7c" alt="" /><span class="zem-script more-related pretty-attribution"><script src="http://static.zemanta.com/readside/loader.js" type="text/javascript"></script></span></div>
]]></content:encoded>
			<wfw:commentRss>http://www.amateurtopologist.com/blog/2010/04/06/dissociated-blogosphere-never-have-to-write-an-original-post-again/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Why I Love Currying</title>
		<link>http://www.amateurtopologist.com/blog/2010/02/12/why-i-love-currying/</link>
		<comments>http://www.amateurtopologist.com/blog/2010/02/12/why-i-love-currying/#comments</comments>
		<pubDate>Sat, 13 Feb 2010 01:35:54 +0000</pubDate>
		<dc:creator>Patrick Hurst</dc:creator>
				<category><![CDATA[Computers]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[haskell]]></category>
		<category><![CDATA[planet sipb]]></category>

		<guid isPermaLink="false">http://www.amateurtopologist.com/?p=613</guid>
		<description><![CDATA[So I&#8217;ve been playing around with Haskell a lot lately and using it for various random stuff; I haven&#8217;t progressed to the point where it&#8217;s my go-to language for random programs (I still use Python for that), but I at least have an idea of how to use it. And there&#8217;s one feature of Haskell [...]]]></description>
			<content:encoded><![CDATA[<p>So I&#8217;ve been playing around with <a href="http://www.haskell.org/">Haskell</a> a lot lately and using it for various random stuff; I haven&#8217;t progressed to the point where it&#8217;s my go-to language for random programs (I still use Python for that), but I at least have an idea of how to use it. And there&#8217;s one feature of Haskell that I miss sorely when I write code in Python, or pretty much any other vaguely functional language: currying.</p>
<p>In Haskell, every function takes a single argument. A function of multiple arguments, such as <code class="codecolorer haskell default"><span class="haskell"><a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:map"><span style="font-weight: bold;">map</span></a></span></code>, which applies a function to every element in a list, actually only has one argument; for example, map can be interpreted either as taking a function and a list and returning a list, or as taking a function and returning a function that takes a list and returns a list. More formally, in Haskell, these two type declarations are equivalent:</p>
<div class="codecolorer-container haskell default" style="overflow:auto;white-space:nowrap;border:1px solid #9F9F9F;width:435px;"><div class="haskell codecolorer" style="padding:5px;font:normal 12px/1.4em Monaco, Lucida Console, monospace;white-space:nowrap"><a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:map"><span style="font-weight: bold;">map</span></a> <span style="color: #339933; font-weight: bold;">::</span> <span style="color: green;">&#40;</span>a <span style="color: #339933; font-weight: bold;">-&gt;</span> b<span style="color: green;">&#41;</span> <span style="color: #339933; font-weight: bold;">-&gt;</span> <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><br />
<a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:map"><span style="font-weight: bold;">map</span></a> <span style="color: #339933; font-weight: bold;">::</span> <span style="color: green;">&#40;</span>a <span style="color: #339933; font-weight: bold;">-&gt;</span> b<span style="color: green;">&#41;</span> <span style="color: #339933; font-weight: bold;">-&gt;</span> <span style="color: green;">&#40;</span><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: green;">&#41;</span></div></div>
<p>This process, of taking a multi-argument function and converting it into a series of single-argument functions is known as currying, after the mathematician <a href="http://en.wikipedia.org/wiki/Haskell_Curry">Haskell Curry</a> (who, obviously, is also the source of the name Haskell); the process of partially applying arguments to a function in this way is known as &#8216;partial application&#8217;, but is also called currying. One of the most obvious examples of currying is in sections: the function <code class="codecolorer haskell default"><span class="haskell"><span style="color: green;">&#40;</span><span style="color: red;">0</span> <span style="color: #339933; font-weight: bold;">==</span><span style="color: green;">&#41;</span></span></code> is syntactic sugar for <code class="codecolorer haskell default"><span class="haskell"><span style="color: green;">&#40;</span><span style="color: #339933; font-weight: bold;">==</span><span style="color: green;">&#41;</span> <span style="color: red;">0</span></span></code>, and returns whether its argument is equal to zero. Furthermore, we can also partially apply the predicate to filter, to make a function that filters its argument on a fixed predicate. So, these three examples are completely equivalent:</p>
<div class="codecolorer-container haskell default" style="overflow:auto;white-space:nowrap;border:1px solid #9F9F9F;width:435px;"><div class="haskell codecolorer" style="padding:5px;font:normal 12px/1.4em Monaco, Lucida Console, monospace;white-space:nowrap">removeZeros <span style="color: #339933; font-weight: bold;">::</span> <span style="color: green;">&#91;</span><a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Integer"><span style="color: #cccc00; font-weight: bold;">Integer</span></a><span style="color: green;">&#93;</span> <span style="color: #339933; font-weight: bold;">-&gt;</span> <span style="color: green;">&#91;</span><a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Integer"><span style="color: #cccc00; font-weight: bold;">Integer</span></a><span style="color: green;">&#93;</span><br />
removeZeros xs <span style="color: #339933; font-weight: bold;">=</span> <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:filter"><span style="font-weight: bold;">filter</span></a> <span style="color: green;">&#40;</span>\x <span style="color: #339933; font-weight: bold;">-&gt;</span> x <span style="color: #339933; font-weight: bold;">/=</span> <span style="color: red;">0</span><span style="color: green;">&#41;</span> xs<br />
removeZeros xs <span style="color: #339933; font-weight: bold;">=</span> <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:filter"><span style="font-weight: bold;">filter</span></a> <span style="color: green;">&#40;</span><span style="color: #339933; font-weight: bold;">/=</span> <span style="color: red;">0</span><span style="color: green;">&#41;</span> xs<br />
removeZeros <span style="color: #339933; font-weight: bold;">=</span> <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:filter"><span style="font-weight: bold;">filter</span></a> <span style="color: green;">&#40;</span><span style="color: #339933; font-weight: bold;">/=</span> <span style="color: red;">0</span><span style="color: green;">&#41;</span></div></div>
<p>(where <code class="codecolorer haskell default"><span class="haskell"><span style="color: #339933; font-weight: bold;">/=</span></span></code> is Haskell&#8217;s not-equal operator). The first is the most explicitly-written version, using no currying at all. The second curries the predicate; <code class="codecolorer haskell default"><span class="haskell"><span style="color: green;">&#40;</span><span style="color: #339933; font-weight: bold;">/=</span> <span style="color: red;">0</span><span style="color: green;">&#41;</span> x</span></code> is the same as <code class="codecolorer haskell default"><span class="haskell">x <span style="color: #339933; font-weight: bold;">/=</span> <span style="color: red;">0</span></span></code>. Finally, since <code class="codecolorer haskell default"><span class="haskell">removeZeroes</span></code> applied to an argument is the same as applying <code class="codecolorer haskell default"><span class="haskell"><a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:filter"><span style="font-weight: bold;">filter</span></a> <span style="color: green;">&#40;</span><span style="color: #339933; font-weight: bold;">/=</span> <span style="color: red;">0</span><span style="color: green;">&#41;</span></span></code> to it, we might as well define the former as the latter. Or, to take another example, look at the sortBy: it has type <code class="codecolorer haskell default"><span class="haskell"><span style="color: green;">&#40;</span>a <span style="color: #339933; font-weight: bold;">-&gt;</span> a <span style="color: #339933; font-weight: bold;">-&gt;</span> <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Ordering"><span style="color: #cccc00; font-weight: bold;">Ordering</span></a><span style="color: green;">&#41;</span> <span style="color: #339933; font-weight: bold;">-&gt;</span> <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>a<span style="color: green;">&#93;</span></span></code>, where Ordering is a datatype that can either be <code class="codecolorer haskell default"><span class="haskell">EQ<span style="color: #339933; font-weight: bold;">,</span> LT</span></code> or <code class="codecolorer haskell default"><span class="haskell">GT</span></code> for equal, less than, or greater than. So if you have some custom function you want to sort a list on, you can just say <code class="codecolorer haskell default"><span class="haskell">mySort <span style="color: #339933; font-weight: bold;">=</span> sortBy f</span></code> and it will be the same as writing <code class="codecolorer haskell default"><span class="haskell">mySort xs <span style="color: #339933; font-weight: bold;">=</span> sortBy f xs</span></code>, only cleaner and neater. Or in <a href="http://github.com/veinor/nimber/blob/master/Data/Nimber.hs">my Data.Nimber module</a> (specifically lines <a href="http://github.com/veinor/nimber/blob/master/Data/Nimber.hs#L38">38</a>, <a href="http://github.com/veinor/nimber/blob/master/Data/Nimber.hs#L39">39</a>, and <a href="http://github.com/veinor/nimber/blob/master/Data/Nimber.hs#L43">43</a>), many operations on Nimbers that&#8217;re required in order for me to call then &#8216;numbers&#8217; are just the identity operation. So instead of saying <code class="codecolorer haskell default"><span class="haskell"><a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:abs"><span style="font-weight: bold;">abs</span></a> x <span style="color: #339933; font-weight: bold;">=</span> x</span></code>, I can just say <code class="codecolorer haskell default"><span class="haskell"><a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:abs"><span style="font-weight: bold;">abs</span></a> <span style="color: #339933; font-weight: bold;">=</span> <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:id"><span style="font-weight: bold;">id</span></a></span></code>.</p>
<p>Furthermore, without currying, you couldn&#8217;t have <a href="http://www.amateurtopologist.com/2010/01/12/variadic-functions-in-haskell/">variadic functions</a>; in order to work inside Haskell&#8217;s type system, the two types <code class="codecolorer haskell default"><span class="haskell">a <span style="color: #339933; font-weight: bold;">-&gt;</span> b <span style="color: #339933; font-weight: bold;">-&gt;</span> c</span></code> and <code class="codecolorer haskell default"><span class="haskell">a <span style="color: #339933; font-weight: bold;">-&gt;</span> <span style="color: green;">&#40;</span>b <span style="color: #339933; font-weight: bold;">-&gt;</span> c<span style="color: green;">&#41;</span></span></code> have to be the same type. The full explanation involves typeclasses, and is (in my opinion) worth a read, because it&#8217;s a good explanation of a pretty horriblexcellent (it&#8217;s both at once, you see) type system hack.</p>
<p>As an aside, this also means that <code class="codecolorer haskell default"><span class="haskell"><a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:id"><span style="font-weight: bold;">id</span></a> <span style="color: #339933; font-weight: bold;">::</span> a <span style="color: #339933; font-weight: bold;">-&gt;</span> a</span></code>, the identity function, is in a sense the same thing as <code class="codecolorer haskell default"><span class="haskell"><span style="color: green;">&#40;</span><span style="color: #339933; font-weight: bold;">$</span><span style="color: green;">&#41;</span> <span style="color: #339933; font-weight: bold;">::</span> <span style="color: green;">&#40;</span>a <span style="color: #339933; font-weight: bold;">-&gt;</span> b<span style="color: green;">&#41;</span> <span style="color: #339933; font-weight: bold;">-&gt;</span> a <span style="color: #339933; font-weight: bold;">-&gt;</span> b</span></code>, which is function application. You can see this by substituting <code class="codecolorer haskell default"><span class="haskell"><span style="color: green;">&#40;</span>b <span style="color: #339933; font-weight: bold;">-&gt;</span> c<span style="color: green;">&#41;</span></span></code> for <code class="codecolorer haskell default"><span class="haskell">a</span></code> in the type of id, then removing parentheses:</p>
<div class="codecolorer-container haskell default" style="overflow:auto;white-space:nowrap;border:1px solid #9F9F9F;width:435px;"><div class="haskell codecolorer" style="padding:5px;font:normal 12px/1.4em Monaco, Lucida Console, monospace;white-space:nowrap"><a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:id"><span style="font-weight: bold;">id</span></a> <span style="color: #339933; font-weight: bold;">::</span> a <span style="color: #339933; font-weight: bold;">-&gt;</span> a<br />
<a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:id"><span style="font-weight: bold;">id</span></a> <span style="color: #339933; font-weight: bold;">::</span> <span style="color: green;">&#40;</span>b <span style="color: #339933; font-weight: bold;">-&gt;</span> c<span style="color: green;">&#41;</span> <span style="color: #339933; font-weight: bold;">-&gt;</span> <span style="color: green;">&#40;</span>b <span style="color: #339933; font-weight: bold;">-&gt;</span> c<span style="color: green;">&#41;</span><br />
<a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:id"><span style="font-weight: bold;">id</span></a> <span style="color: #339933; font-weight: bold;">::</span> <span style="color: green;">&#40;</span>b <span style="color: #339933; font-weight: bold;">-&gt;</span> c<span style="color: green;">&#41;</span> <span style="color: #339933; font-weight: bold;">-&gt;</span> b <span style="color: #339933; font-weight: bold;">-&gt;</span> c</div></div>
<p>So, in particular, <code class="codecolorer haskell default"><span class="haskell">f `<a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:id"><span style="font-weight: bold;">id</span></a>` x</span></code> is the same as <code class="codecolorer haskell default"><span class="haskell">f <span style="color: #339933; font-weight: bold;">$</span> x</span></code>, which is just <code class="codecolorer haskell default"><span class="haskell">f x</span></code>. Another way to think of this is that <code class="codecolorer haskell default"><span class="haskell">f `<a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:id"><span style="font-weight: bold;">id</span></a>` x <span style="color: #339933; font-weight: bold;">=</span> <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:id"><span style="font-weight: bold;">id</span></a> f x <span style="color: #339933; font-weight: bold;">=</span> <span style="color: green;">&#40;</span><a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:id"><span style="font-weight: bold;">id</span></a> f<span style="color: green;">&#41;</span> x <span style="color: #339933; font-weight: bold;">=</span> f x</span></code>.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.amateurtopologist.com/blog/2010/02/12/why-i-love-currying/feed/</wfw:commentRss>
		<slash:comments>9</slash:comments>
		</item>
		<item>
		<title>Variadic Functions in Haskell</title>
		<link>http://www.amateurtopologist.com/blog/2010/01/12/variadic-functions-in-haskell/</link>
		<comments>http://www.amateurtopologist.com/blog/2010/01/12/variadic-functions-in-haskell/#comments</comments>
		<pubDate>Tue, 12 Jan 2010 22:50:32 +0000</pubDate>
		<dc:creator>Patrick Hurst</dc:creator>
				<category><![CDATA[Computers]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[haskell]]></category>
		<category><![CDATA[planet sipb]]></category>

		<guid isPermaLink="false">http://www.amateurtopologist.com/?p=540</guid>
		<description><![CDATA[Most modern languages have some kind of printf analogue: a function that takes a format string, and a series of things to be inserted into that string, and formats them all accordingly. At first glance, Haskell&#8217;s strong type system would seem to preclude this. There&#8217;s no built-in system for writing functions that take variable numbers [...]]]></description>
			<content:encoded><![CDATA[<p>Most modern languages have some kind of printf analogue: a function that takes a format string, and a series of things to be inserted into that string, and formats them all accordingly. At first glance, <a href="http://en.wikipedia.org/wiki/Haskell">Haskell&#8217;s</a> strong type system would seem to preclude this. There&#8217;s no built-in system for writing functions that take variable numbers of arguments, and it seems like it would be difficult to write one. The standard approach is to take a list instead, but this fundamentally doesn&#8217;t work for printf, since you&#8217;re going to be wanting to print Integers, Strings, and Floats. It&#8217;s possible to just pre-apply show to everything, but that&#8217;s not really a good idea, because you might want to show them in a different way than the built-in show does. You can use an extension called existential types to create a list of PrintfWrappers which wrap integers/floats/strings (more on that below), but that requires your users to manually do the wrapping, which is, once again, not a good idea. Haskell&#8217;s <a href="http://haskell.org/ghc/docs/latest/html/libraries/base-4.2.0.0/Text-Printf.html">Text.Printf</a> module takes a third approach. Look at the following lines:</p>
<div class="codecolorer-container haskell default" style="overflow:auto;white-space:nowrap;border:1px solid #9F9F9F;width:435px;"><div class="haskell codecolorer" style="padding:5px;font:normal 12px/1.4em Monaco, Lucida Console, monospace;white-space:nowrap"><span style="color: #06c; font-weight: bold;">instance</span> <span style="color: green;">&#40;</span>IsChar c<span style="color: green;">&#41;</span> <span style="color: #339933; font-weight: bold;">=&gt;</span> PrintfType <span style="color: green;">&#91;</span>c<span style="color: green;">&#93;</span><br />
<span style="color: #06c; font-weight: bold;">instance</span> PrintfType <span style="color: green;">&#40;</span><a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:IO"><span style="color: #cccc00; font-weight: bold;">IO</span></a> a<span style="color: green;">&#41;</span><br />
<span style="color: #06c; font-weight: bold;">instance</span> <span style="color: green;">&#40;</span>PrintfArg a<span style="color: #339933; font-weight: bold;">,</span> PrintfType r<span style="color: green;">&#41;</span> <span style="color: #339933; font-weight: bold;">=&gt;</span> PrintfType <span style="color: green;">&#40;</span>a <span style="color: #339933; font-weight: bold;">-&gt;</span> r<span style="color: green;">&#41;</span><br />
<br />
<span style="color: #06c; font-weight: bold;">instance</span> PrintfArg <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Integer"><span style="color: #cccc00; font-weight: bold;">Integer</span></a><br />
<span style="color: #06c; font-weight: bold;">instance</span> <span style="color: green;">&#40;</span>IsChar c<span style="color: green;">&#41;</span> <span style="color: #339933; font-weight: bold;">=&gt;</span> PrintfArg <span style="color: green;">&#91;</span>c<span style="color: green;">&#93;</span><br />
<br />
printf <span style="color: #339933; font-weight: bold;">::</span> <span style="color: green;">&#40;</span>PrintfType r<span style="color: green;">&#41;</span> <span style="color: #339933; font-weight: bold;">=&gt;</span> <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:String"><span style="color: #cccc00; font-weight: bold;">String</span></a> <span style="color: #339933; font-weight: bold;">-&gt;</span> r</div></div>
<p>Here&#8217;s how to interpret this: PrintfType is the type of things that can be printed to. Printing to a <code class="codecolorer haskell default"><span class="haskell"><a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:String"><span style="color: #cccc00; font-weight: bold;">String</span></a></span></code> just gives you a string, much like sprintf in C or Perl, printing to an <code class="codecolorer haskell default"><span class="haskell"><a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:IO"><span style="color: #cccc00; font-weight: bold;">IO</span></a> <span style="color: green;">&#40;</span><span style="color: green;">&#41;</span></span></code> will actually print it out (so you can use it like a normal printf in do blocks, a behavior which I personally find distasteful.). However, printf will return undefined when asked to return an <code class="codecolorer haskell default"><span class="haskell"><a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:IO"><span style="color: #cccc00; font-weight: bold;">IO</span></a> r</span></code>; the reason that you can nevertheless return one is that only declaring IO () as an instance of PrintfType is invalid according to Haskell 98.</p>
<p><code class="codecolorer haskell default"><span class="haskell">PrintfArg</span></code>, by comparison, are the elements that are valid arguments to <code class="codecolorer haskell default"><span class="haskell">printf</span></code>; they basically consist of the various <code class="codecolorer haskell default"><span class="haskell">WordN<span style="color: #339933; font-weight: bold;">/</span>IntN</span></code> types, <code class="codecolorer haskell default"><span class="haskell"><a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Integer"><span style="color: #cccc00; font-weight: bold;">Integer</span></a><span style="color: #339933; font-weight: bold;">,</span> <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Float"><span style="color: #cccc00; font-weight: bold;">Float</span></a><span style="color: #339933; font-weight: bold;">,</span> <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Char"><span style="color: #cccc00; font-weight: bold;">Char</span></a></span></code>, and <code class="codecolorer haskell default"><span class="haskell"><span style="color: green;">&#40;</span>IsChar c<span style="color: green;">&#41;</span> <span style="color: #339933; font-weight: bold;">=&gt;</span> <span style="color: green;">&#91;</span>c<span style="color: green;">&#93;</span></span></code>. The point of the last instance is that, while you can&#8217;t have a specific version of a polymorphic type be an instance of a typeclass, you can restrict it to types whose parameters are themselves instance of another typeclass; the only instance of <code class="codecolorer haskell default"><span class="haskell">isChar</span></code> is <code class="codecolorer haskell default"><span class="haskell"><a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Char"><span style="color: #cccc00; font-weight: bold;">Char</span></a></span></code>.<br />
So now that we have that clarified, let&#8217;s suppose we want to call printf with &#8220;%s %d %f&#8221; &#8220;foo&#8221; 42 3.1, passing it the format string, String, an Integer, and a Float. This causes printf&#8217;s type to become</p>
<div class="codecolorer-container haskell default" style="overflow:auto;white-space:nowrap;border:1px solid #9F9F9F;width:435px;"><div class="haskell codecolorer" style="padding:5px;font:normal 12px/1.4em Monaco, Lucida Console, monospace;white-space:nowrap">printf <span style="color: #339933; font-weight: bold;">::</span> <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:String"><span style="color: #cccc00; font-weight: bold;">String</span></a> <span style="color: #339933; font-weight: bold;">-&gt;</span> <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:String"><span style="color: #cccc00; font-weight: bold;">String</span></a> <span style="color: #339933; font-weight: bold;">-&gt;</span> <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Integer"><span style="color: #cccc00; font-weight: bold;">Integer</span></a> <span style="color: #339933; font-weight: bold;">-&gt;</span> <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Float"><span style="color: #cccc00; font-weight: bold;">Float</span></a> <span style="color: #339933; font-weight: bold;">-&gt;</span> <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:String"><span style="color: #cccc00; font-weight: bold;">String</span></a></div></div>
<p>Does this match the pattern <code class="codecolorer haskell default"><span class="haskell"><span style="color: green;">&#40;</span>PrintfType r<span style="color: green;">&#41;</span> <span style="color: #339933; font-weight: bold;">=&gt;</span> <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:String"><span style="color: #cccc00; font-weight: bold;">String</span></a> <span style="color: #339933; font-weight: bold;">-&gt;</span> r</span></code>? Let&#8217;s go in reverse. <code class="codecolorer haskell default"><span class="haskell"><a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:String"><span style="color: #cccc00; font-weight: bold;">String</span></a></span></code> is an instance of <code class="codecolorer haskell default"><span class="haskell">PrintfType</span></code>, and <code class="codecolorer haskell default"><span class="haskell"><a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Float"><span style="color: #cccc00; font-weight: bold;">Float</span></a></span></code> is an instance of <code class="codecolorer haskell default"><span class="haskell">PrintfArg</span></code>, so <code class="codecolorer haskell default"><span class="haskell"><a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Float"><span style="color: #cccc00; font-weight: bold;">Float</span></a> <span style="color: #339933; font-weight: bold;">-&gt;</span> <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:String"><span style="color: #cccc00; font-weight: bold;">String</span></a></span></code> is an instance of <code class="codecolorer haskell default"><span class="haskell">PrintfType</span></code>. Therefore, <code class="codecolorer haskell default"><span class="haskell"><a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Integer"><span style="color: #cccc00; font-weight: bold;">Integer</span></a> <span style="color: #339933; font-weight: bold;">-&gt;</span> <span style="color: green;">&#40;</span><a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Float"><span style="color: #cccc00; font-weight: bold;">Float</span></a> <span style="color: #339933; font-weight: bold;">-&gt;</span> <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:String"><span style="color: #cccc00; font-weight: bold;">String</span></a><span style="color: green;">&#41;</span></span></code> is an instance of <code class="codecolorer haskell default"><span class="haskell">PrintfArg</span></code>, and so is <code class="codecolorer haskell default"><span class="haskell"><a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:String"><span style="color: #cccc00; font-weight: bold;">String</span></a> <span style="color: #339933; font-weight: bold;">-&gt;</span> <span style="color: green;">&#40;</span><a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Integer"><span style="color: #cccc00; font-weight: bold;">Integer</span></a> <span style="color: #339933; font-weight: bold;">-&gt;</span> <span style="color: green;">&#40;</span><a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Float"><span style="color: #cccc00; font-weight: bold;">Float</span></a> <span style="color: #339933; font-weight: bold;">-&gt;</span> <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:String"><span style="color: #cccc00; font-weight: bold;">String</span></a><span style="color: green;">&#41;</span><span style="color: green;">&#41;</span></span></code>. Dropping parentheses, this becomes <code class="codecolorer haskell default"><span class="haskell"><a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:String"><span style="color: #cccc00; font-weight: bold;">String</span></a> <span style="color: #339933; font-weight: bold;">-&gt;</span> <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Integer"><span style="color: #cccc00; font-weight: bold;">Integer</span></a> <span style="color: #339933; font-weight: bold;">-&gt;</span> <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Float"><span style="color: #cccc00; font-weight: bold;">Float</span></a> <span style="color: #339933; font-weight: bold;">-&gt;</span> <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:String"><span style="color: #cccc00; font-weight: bold;">String</span></a></span></code>. So the types all check out. If you pass an invalid type, then you&#8217;ll run into something that isn&#8217;t an instance of <code class="codecolorer haskell default"><span class="haskell">PrintfArg</span></code> and so the types won&#8217;t check.</p>
<p>I mentioned above that if you use something called &#8216;existential types&#8217;, you can do something similar. The way it works is that you define a new type whose data constructor only requires that its argument be of a given typeclass. Look at the following example</p>
<div class="codecolorer-container haskell default" style="overflow:auto;white-space:nowrap;border:1px solid #9F9F9F;width:435px;"><div class="haskell codecolorer" style="padding:5px;font:normal 12px/1.4em Monaco, Lucida Console, monospace;white-space:nowrap"><span style="color: #5d478b; font-style: italic;">{-# LANGUAGE ExistentialQuantifiers #-}</span><br />
<span style="color: #06c; font-weight: bold;">data</span> Box <span style="color: #339933; font-weight: bold;">=</span> <span style="color: #06c; font-weight: bold;">forall</span> s<span style="color: #339933; font-weight: bold;">.</span> <span style="color: green;">&#40;</span><a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Show"><span style="color: #cccc00; font-weight: bold;">Show</span></a> s<span style="color: green;">&#41;</span> <span style="color: #339933; font-weight: bold;">=&gt;</span> Box s<br />
<br />
boxes <span style="color: #339933; font-weight: bold;">=</span> <span style="color: green;">&#91;</span>Box <span style="color: red;">2</span><span style="color: #339933; font-weight: bold;">,</span> Box <span style="background-color: #3cb371;">&quot;f&quot;</span><span style="color: #339933; font-weight: bold;">,</span> Box <span style="color: green;">&#91;</span><span style="color: red;">8</span><span style="color: #339933; font-weight: bold;">,</span><span style="color: red;">3</span><span style="color: green;">&#93;</span><span style="color: green;">&#93;</span>\<br />
<br />
showBoxes <span style="color: #339933; font-weight: bold;">::</span> <span style="color: green;">&#91;</span>Box<span style="color: green;">&#93;</span> <span style="color: #339933; font-weight: bold;">-&gt;</span> <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:String"><span style="color: #cccc00; font-weight: bold;">String</span></a><br />
showBoxes <span style="color: green;">&#91;</span><span style="color: green;">&#93;</span> <span style="color: #339933; font-weight: bold;">=</span> <span style="background-color: #3cb371;">&quot;&quot;</span><br />
showBoxes <span style="color: green;">&#40;</span><span style="color: green;">&#40;</span>Box x<span style="color: green;">&#41;</span>:xs<span style="color: green;">&#41;</span> <span style="color: #339933; font-weight: bold;">=</span> <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:show"><span style="font-weight: bold;">show</span></a> x <span style="color: #339933; font-weight: bold;">++</span> <span style="background-color: #3cb371;">&quot; &quot;</span> <span style="color: #339933; font-weight: bold;">++</span> showBoxes xs</div></div>
<p>When you run <code class="codecolorer haskell default"><span class="haskell">showBoxes boxes</span></code>, you get <code class="codecolorer text default"><span class="text">2 &quot;f&quot; 83</span></code>, exactly as you&#8217;d expect. Note that, however, the function <code class="codecolorer haskell default"><span class="haskell">unbox <span style="color: green;">&#40;</span>Box x<span style="color: green;">&#41;</span> <span style="color: #339933; font-weight: bold;">=</span> x</span></code> cannot be written; it would have to be of type <code class="codecolorer haskell default"><span class="haskell"><span style="color: green;">&#40;</span><a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Show"><span style="color: #cccc00; font-weight: bold;">Show</span></a> s<span style="color: green;">&#41;</span> <span style="color: #339933; font-weight: bold;">=&gt;</span> Box <span style="color: #339933; font-weight: bold;">-&gt;</span> s</span></code>, and there&#8217;s just no real way to do that. So once you&#8217;ve wrapped something up in a Box, you can only get at it by <code class="codecolorer haskell default"><span class="haskell"><a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:show"><span style="font-weight: bold;">show</span></a></span></code>ing it. From this, you can see how to pass a heterogeneous list to <code class="codecolorer haskell default"><span class="haskell">printf</span></code>. The reason that this approach is suboptimal is that it would require Text.Printf to export a Printf data constructor which would wrap up everything to make it of the appropriate type, and that would be rather annoying, especially since it relies on show preserving enough information for you to format the number after <code class="codecolorer haskell default"><span class="haskell"><a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:read"><span style="font-weight: bold;">read</span></a></span></code>ing it back in.</p>
<p>This pattern can obviously extended to any other variadic, heterogeneous function, as long as you can define a suitable typeclass that its arguments must all be instances of. And that&#8217;s not really a restriction at all; if you can&#8217;t specify a behavior that the instances must have, then you don&#8217;t really know what you can do with the arguments, and so you can&#8217;t do anything at all!</p>
]]></content:encoded>
			<wfw:commentRss>http://www.amateurtopologist.com/blog/2010/01/12/variadic-functions-in-haskell/feed/</wfw:commentRss>
		<slash:comments>5</slash:comments>
		</item>
		<item>
		<title>Data.MemoCombinators and You</title>
		<link>http://www.amateurtopologist.com/blog/2009/11/22/data-memocombinators-and-you/</link>
		<comments>http://www.amateurtopologist.com/blog/2009/11/22/data-memocombinators-and-you/#comments</comments>
		<pubDate>Sun, 22 Nov 2009 17:44:18 +0000</pubDate>
		<dc:creator>Patrick Hurst</dc:creator>
				<category><![CDATA[Computers]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[haskell]]></category>

		<guid isPermaLink="false">http://www.amateurtopologist.com/?p=446</guid>
		<description><![CDATA[Part of the beauty of Haskell is that it allows you to simply write recursive functions. But part of the problem with recursive functions is that they tend to have absolutely horrible big-O run times. The usual solution to this problem is to use what&#8217;s known as memoization, which is memorization without the &#8216;r&#8217;, since [...]]]></description>
			<content:encoded><![CDATA[<p>Part of the beauty of Haskell is that it allows you to simply write recursive functions. But part of the problem with recursive functions is that they tend to have absolutely horrible big-O run times. The usual solution to this problem is to use what&#8217;s known as <a href="http://en.wikipedia.org/wiki/Memoization">memoization</a>, which is memorization without the &#8216;r&#8217;, since programmers have to have special names for everything. Memoization is usually implemented as an associative array (or a plain array in the common case where the function takes a single non-negative integer as an argument); the function attempts to look up the return value for its arguments in an associative array. If it finds it, it can return without doing expensive computation; if it doesn&#8217;t, then it performs the computation, stores the result in its array, and then returns. In Python, a memoized Fibonacci function might be written as follows:</p>
<div class="codecolorer-container python default" style="overflow:auto;white-space:nowrap;border:1px solid #9F9F9F;width:435px;"><div class="python codecolorer" style="padding:5px;font:normal 12px/1.4em Monaco, Lucida Console, monospace;white-space:nowrap">fib_cache <span style="color: #66cc66;">=</span> <span style="color: black;">&#123;</span><span style="color: black;">&#125;</span><br />
<span style="color: #ff7700;font-weight:bold;">def</span> fib<span style="color: black;">&#40;</span>n<span style="color: black;">&#41;</span>:<br />
&nbsp; &nbsp; <span style="color: #ff7700;font-weight:bold;">if</span> <span style="color: black;">&#40;</span>n <span style="color: #66cc66;">&lt;</span> <span style="color: #ff4500;">2</span><span style="color: black;">&#41;</span>: <span style="color: #ff7700;font-weight:bold;">return</span> n<br />
&nbsp; &nbsp; <span style="color: #ff7700;font-weight:bold;">if</span> n <span style="color: #ff7700;font-weight:bold;">not</span> <span style="color: #ff7700;font-weight:bold;">in</span> fib_cache: fib_cache<span style="color: black;">&#91;</span>n<span style="color: black;">&#93;</span> <span style="color: #66cc66;">=</span> fib<span style="color: black;">&#40;</span>n-<span style="color: #ff4500;">1</span><span style="color: black;">&#41;</span> + fib<span style="color: black;">&#40;</span>n-<span style="color: #ff4500;">2</span><span style="color: black;">&#41;</span><br />
&nbsp; &nbsp; <span style="color: #ff7700;font-weight:bold;">return</span> fib_cache<span style="color: black;">&#91;</span>n<span style="color: black;">&#93;</span></div></div>
<p>The speed savings gained by this are enormous; on my test machine, fib(35) takes 15 seconds to compute without memoization, whereas fib(1000) computes almost instantly with memoization. In terms of big-O running times, I believe that the memoized version takes <img src='http://s.wordpress.com/latex.php?latex=O%28n%5E2%29&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='O(n^2)' title='O(n^2)' class='latex' /> time, whereas the unmemoized version takes <img src='http://s.wordpress.com/latex.php?latex=%5CTheta%28%5Cphi%5En%29&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='\Theta(\phi^n)' title='\Theta(\phi^n)' class='latex' />, which is interesting since the Fibonacci numbers themselves are <img src='http://s.wordpress.com/latex.php?latex=%5CTheta%28%5Cphi%5En%29&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='\Theta(\phi^n)' title='\Theta(\phi^n)' class='latex' />. In any case, the memoized version is clearly superior.</p>
<p>But how do you do this in a language such as Haskell? You can&#8217;t carry state between the various incarnations of the function, since that could potentially lead to the function&#8217;s values not solely depending on its arguments, violating referential transparency. You can&#8217;t carry the state around in a monad because then different calls to the function would each have separate caches, so you&#8217;d have to pull some kind of trick where the function returns itself and its value, then pass the function around and it would just be a huge mess. So instead what you do is you use <a href="http://hackage.haskell.org/packages/archive/data-memocombinators/0.3/doc/html/Data-MemoCombinators.html">Data.MemoCombinators</a>, which is a package that lets you turn functions into other, memoized functions. So how do you use it? It&#8217;s not too hard, especially if you&#8217;re memoizing functions that only use builtin types. An example, straight from the Data.MemoCombinators page:</p>
<div class="codecolorer-container haskell default" style="overflow:auto;white-space:nowrap;border:1px solid #9F9F9F;width:435px;"><div class="haskell codecolorer" style="padding:5px;font:normal 12px/1.4em Monaco, Lucida Console, monospace;white-space:nowrap">fib <span style="color: #339933; font-weight: bold;">=</span> Memo<span style="color: #339933; font-weight: bold;">.</span>integral fib'<br />
&nbsp; &nbsp; <span style="color: #06c; font-weight: bold;">where</span><br />
&nbsp; &nbsp; fib' <span style="color: red;">0</span> <span style="color: #339933; font-weight: bold;">=</span> <span style="color: red;">0</span><br />
&nbsp; &nbsp; fib' <span style="color: red;">1</span> <span style="color: #339933; font-weight: bold;">=</span> <span style="color: red;">1</span><br />
&nbsp; &nbsp; fib' x <span style="color: #339933; font-weight: bold;">=</span> fib <span style="color: green;">&#40;</span>x<span style="color: #339933; font-weight: bold;">-</span><span style="color: red;">1</span><span style="color: green;">&#41;</span> <span style="color: #339933; font-weight: bold;">+</span> fib <span style="color: green;">&#40;</span>x<span style="color: #339933; font-weight: bold;">-</span><span style="color: red;">2</span><span style="color: green;">&#41;</span></div></div>
<p>There are two things to note here: first, the memoized version, fib, is generated from the non-memoized by calling Memo.integral on it. This is how you create memoized versions of single-variable functions: you apply the appropriate combinator. Second, fib&#8217; calls fib inside it. This is very important: if fib&#8217; called fib&#8217;, then you couldn&#8217;t save time within the fib function, only outside of it. With fib&#8217; calling fib, on the other hand, then the first time you call fib 1000, not only will it return before the heat death of the universe, but you&#8217;ll also get fib 999, fib 998, etc. cached.</p>
<p>But what if your function to be memoized isn&#8217;t one of the standard types? That&#8217;s why there&#8217;s Memo.wrap. You just have to define two mappings: one from your type to some combination of MemoCombinator types, and one that goes from that combination back. An example will make it clear:</p>
<div class="codecolorer-container haskell default" style="overflow:auto;white-space:nowrap;border:1px solid #9F9F9F;width:435px;"><div class="haskell codecolorer" style="padding:5px;font:normal 12px/1.4em Monaco, Lucida Console, monospace;white-space:nowrap"><span style="color: #06c; font-weight: bold;">data</span> Foo <span style="color: #339933; font-weight: bold;">=</span> Foo <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:String"><span style="color: #cccc00; font-weight: bold;">String</span></a> <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Int"><span style="color: #cccc00; font-weight: bold;">Int</span></a> <span style="color: #06c; font-weight: bold;">deriving</span> <span style="color: green;">&#40;</span><a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Show"><span style="color: #cccc00; font-weight: bold;">Show</span></a><span style="color: green;">&#41;</span><br />
memoFoo <span style="color: #339933; font-weight: bold;">=</span> Memo<span style="color: #339933; font-weight: bold;">.</span>wrap toFoo fromFoo <span style="color: green;">&#40;</span>Memo<span style="color: #339933; font-weight: bold;">.</span>pair memoString Memo<span style="color: #339933; font-weight: bold;">.</span>integral<span style="color: green;">&#41;</span> <span style="color: #06c; font-weight: bold;">where</span><br />
&nbsp; &nbsp; memoString <span style="color: #339933; font-weight: bold;">=</span> Memo<span style="color: #339933; font-weight: bold;">.</span>list Memo<span style="color: #339933; font-weight: bold;">.</span>char<br />
&nbsp; &nbsp; toFoo <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: #339933; font-weight: bold;">=</span> Foo a b<br />
&nbsp; &nbsp; fromFoo <span style="color: green;">&#40;</span>Foo a b<span style="color: green;">&#41;</span> <span style="color: #339933; font-weight: bold;">=</span> <span style="color: green;">&#40;</span>a<span style="color: #339933; font-weight: bold;">,</span> b<span style="color: green;">&#41;</span><br />
f <span style="color: #339933; font-weight: bold;">=</span> memoFoo f' <span style="color: #06c; font-weight: bold;">where</span><br />
&nbsp; &nbsp; f' <span style="color: green;">&#40;</span>Foo x y<span style="color: green;">&#41;</span> <span style="color: #339933; font-weight: bold;">=</span> x</div></div>
<p>So as you can see, first you build up a memoString type which can memoize Strings; since a String is just a list of Chars, you can just apply Memo.list to Memo.char. Then you define toFoo and fromFoo, which send you from the abstracted Foo type to a tuple of a String and an Int. Finally, you use Memo.wrap to &#8216;wrap&#8217; the pair of a memoized String and a memoized Int (constructed using Memo.pair, naturally) up in an abstract memoFoo memoizer.</p>
<p>The other thing you can do with MemoCombinators is memoize functions of multiple variables. Take this sample of code from <a href="http://github.com/veinor/nimber">a project I&#8217;m working on</a>:</p>
<div class="codecolorer-container haskell default" style="overflow:auto;white-space:nowrap;border:1px solid #9F9F9F;width:435px;"><div class="haskell codecolorer" style="padding:5px;font:normal 12px/1.4em Monaco, Lucida Console, monospace;white-space:nowrap">memoNimber <span style="color: #339933; font-weight: bold;">=</span> memoNimber <span style="color: #339933; font-weight: bold;">=</span> Memo<span style="color: #339933; font-weight: bold;">.</span>wrap toNimber fromNimber Memo<span style="color: #339933; font-weight: bold;">.</span>integral<br />
<span style="color: green;">&#40;</span><span style="color: #339933; font-weight: bold;">*</span><span style="color: green;">&#41;</span> <span style="color: #339933; font-weight: bold;">=</span> Memo<span style="color: #339933; font-weight: bold;">.</span>memo2 memoNimber memoNimber <span style="color: green;">&#40;</span><span style="color: #339933; font-weight: bold;">*!</span><span style="color: green;">&#41;</span> <span style="color: #06c; font-weight: bold;">where</span><br />
&nbsp; &nbsp; &nbsp; x <span style="color: #339933; font-weight: bold;">*!</span> <span style="color: green;">&#40;</span>Nimber <span style="color: red;">1</span><span style="color: green;">&#41;</span> <span style="color: #339933; font-weight: bold;">=</span> x<br />
&nbsp; &nbsp; &nbsp; <span style="color: green;">&#40;</span>Nimber <span style="color: red;">1</span><span style="color: green;">&#41;</span> <span style="color: #339933; font-weight: bold;">*!</span> x <span style="color: #339933; font-weight: bold;">=</span> x<br />
&nbsp; &nbsp; &nbsp; a <span style="color: #339933; font-weight: bold;">*!</span> b <span style="color: #339933; font-weight: bold;">=</span> mex <span style="color: #339933; font-weight: bold;">$</span> liftM2 combine <span style="color: green;">&#91;</span><span style="color: red;">0</span> <span style="color: #339933; font-weight: bold;">..</span> <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:pred"><span style="font-weight: bold;">pred</span></a> a<span style="color: green;">&#93;</span> <span style="color: green;">&#91;</span><span style="color: red;">0</span> <span style="color: #339933; font-weight: bold;">..</span> <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:pred"><span style="font-weight: bold;">pred</span></a> b<span style="color: green;">&#93;</span><br />
&nbsp; &nbsp; &nbsp; &nbsp; <span style="color: #06c; font-weight: bold;">where</span><br />
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; mex xs <span style="color: #339933; font-weight: bold;">=</span> fromJust <span style="color: #339933; font-weight: bold;">$</span> find <span style="color: green;">&#40;</span>`<a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:notElem"><span style="font-weight: bold;">notElem</span></a>` xs<span style="color: green;">&#41;</span> <span style="color: green;">&#91;</span><span style="color: red;">0</span><span style="color: #339933; font-weight: bold;">..</span><span style="color: green;">&#93;</span><br />
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; combine a' b' <span style="color: #339933; font-weight: bold;">=</span> a <span style="color: #339933; font-weight: bold;">*</span> b' <span style="color: #339933; font-weight: bold;">+</span> a' <span style="color: #339933; font-weight: bold;">*</span> b <span style="color: #339933; font-weight: bold;">+</span> a' <span style="color: #339933; font-weight: bold;">*</span> b'</div></div>
<p>The actual definition of *! isn&#8217;t important, I&#8217;m only including it for completeness. Nor are the definitions of toNimber and fromNimber. What is important is Memo.memo2: you use it to generate a memoized function of multiple arguments. You just pass it memoizers for each of its arguments (since * takes two Nimbers, I pass it memoNimber twice) and the unmemoized version, and it gives you a memoized version.</p>
<p>As for how Data.MemoCombinators works, I can&#8217;t really explain that. I know it has to do with the fact that expressions in function definitions are cached, but beyond that my knowledge fails. Maybe if I ever learn it I&#8217;ll return to this and explain it.</p>
<p>Edit: After I wrote this I realized that <a href="http://hackage.haskell.org/cgi-bin/hackage-scripts/package/MemoTrie">Data.MemoTrie</a> exists; while it has cleaner syntax for memoizing functions (the memoizer doesn&#8217;t need to know the types of the arguments), it has a disadvantage in that it&#8217;s not immediately obvious how to memoize the types it doesn&#8217;t give you. But if you&#8217;re just memoizing functions of Ints or something, go ahead and use MemoTrie.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.amateurtopologist.com/blog/2009/11/22/data-memocombinators-and-you/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
	</channel>
</rss>

<!-- Performance optimized by W3 Total Cache. Learn more: http://www.w3-edge.com/wordpress-plugins/

Page Caching using apc
Database Caching 1/31 queries in 0.012 seconds using apc
Object Caching 6064/6124 objects using apc

Served from: www.amateurtopologist.com @ 2012-02-05 20:28:10 -->
