<?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>Lab49 Blog &#187; Functional Programming</title>
	<atom:link href="http://blog.lab49.com/archives/category/functional-programming/feed" rel="self" type="application/rss+xml" />
	<link>http://blog.lab49.com</link>
	<description>Technology and industry insights from Lab49.</description>
	<lastBuildDate>Wed, 08 Feb 2012 09:02:55 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.0.1</generator>
		<item>
		<title>Verbs over Dependencies in order to build decoupled systems</title>
		<link>http://blog.lab49.com/archives/5496</link>
		<comments>http://blog.lab49.com/archives/5496#comments</comments>
		<pubDate>Sun, 24 Jul 2011 22:57:27 +0000</pubDate>
		<dc:creator>Thorsten Lorenz</dc:creator>
				<category><![CDATA[Design Patterns]]></category>
		<category><![CDATA[Functional Programming]]></category>
		<category><![CDATA[JavaScript]]></category>

		<guid isPermaLink="false">http://blog.lab49.com/?p=5496</guid>
		<description><![CDATA[There is no doubt that most programming languages used today already exhibit strong functional support or are on their way to adding it. With that in mind I examined the good old Dependency Injection pattern and how we could improve on it. In my recent post I discuss how our systems could become even less [...]]]></description>
			<content:encoded><![CDATA[<p>There is no doubt that most programming languages used today already exhibit strong functional support or are on their way to adding it. With that in mind I examined the good old Dependency Injection pattern and how we could improve on it.</p>
<p>In my recent post I discuss how our systems could become even less coupled when we pass functions &#8211; &#8220;Verbs&#8221; &#8211; around, instead of passing entire Dependencies.</p>
<p>Examples are given in CoffeeScript and C# using MEF.</p>
<p><a href="http://thorstenlorenz.wordpress.com/2011/07/23/dependency-injection-is-dead-long-live-verbs/">Read more here &#8230;</a></p>
]]></content:encoded>
			<wfw:commentRss>http://blog.lab49.com/archives/5496/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Calling Excel Math Functions From PowerShell</title>
		<link>http://feedproxy.google.com/~r/DevelopmentInABlink/~3/-1Em1PVhAeE/</link>
		<comments>http://feedproxy.google.com/~r/DevelopmentInABlink/~3/-1Em1PVhAeE/#comments</comments>
		<pubDate>Wed, 06 Apr 2011 01:19:04 +0000</pubDate>
		<dc:creator>Doug Finke</dc:creator>
				<category><![CDATA[.Net]]></category>
		<category><![CDATA[Functional Programming]]></category>
		<category><![CDATA[PowerShell]]></category>

		<guid isPermaLink="false">http://www.dougfinke.com/blog/index.php/2011/04/05/calling-excel-math-functions-from-powershell/</guid>
		<description><![CDATA[I came across this post Calling Excel Math Functions From F# FSI and figured it would be very useful to do from PowerShell. This can also be done a line at a time in the PowerShell command line REPL (Read Eval Print Loop). Meaning, you can create different arrays and multidimensional arrays at the command [...]]]></description>
			<content:encoded><![CDATA[<p>I came across this post <a href="http://blogs.msdn.com/b/jackhu/archive/2011/04/05/using-excel-math-functions-from-f-fsi.aspx">Calling Excel Math Functions From F# FSI</a> and figured it would be very useful to do from PowerShell.</p>
<p>This can also be done a line at a time in the PowerShell command line REPL (Read Eval Print Loop). Meaning, you can create different arrays and multidimensional arrays at the command line and then type and call the Excel functions.</p>
<p>Plus, these are only 4 of the many Excel functions available.</p>
<p>If you want to find out the other Excel math functions available, type this line at the command line (run the first three lines of code up to the WorksheetFunction first):</p>
<p><em>$wf | Get-Member -MemberType method | Out-GridView</em></p>
<pre class="PowerShellColorizedScript" style="width: 454px; height: 430px;"><span style="color: #006400;"># Calling Excel Math Functions From PowerShell</span>            

<span style="color: #ff4500;">$xl</span>        <span style="color: #a9a9a9;">=</span> <span style="color: #0000ff;">New-Object</span> <span style="color: #000080;">-ComObject</span> <span style="color: #8a2be2;">Excel.Application</span>
<span style="color: #ff4500;">$xlprocess</span> <span style="color: #a9a9a9;">=</span> <span style="color: #0000ff;">Get-Process</span> <span style="color: #8a2be2;">excel</span>            

<span style="color: #ff4500;">$wf</span>   <span style="color: #a9a9a9;">=</span> <span style="color: #ff4500;">$xl</span><span style="color: #a9a9a9;">.</span><span style="color: #000000;">WorksheetFunction</span>
<span style="color: #ff4500;">$data</span> <span style="color: #a9a9a9;">=</span> <span style="color: #800080;">1</span><span style="color: #a9a9a9;">,</span><span style="color: #800080;">2</span><span style="color: #a9a9a9;">,</span><span style="color: #800080;">3</span><span style="color: #a9a9a9;">,</span><span style="color: #800080;">4</span>
<span style="color: #ff4500;">$m</span>    <span style="color: #a9a9a9;">=</span> <span style="color: #000000;">(</span><span style="color: #000000;">(</span><span style="color: #800080;">1</span><span style="color: #a9a9a9;">,</span><span style="color: #800080;">2</span><span style="color: #a9a9a9;">,</span><span style="color: #800080;">3</span><span style="color: #000000;">)</span><span style="color: #a9a9a9;">,</span><span style="color: #000000;">(</span><span style="color: #800080;">4</span><span style="color: #a9a9a9;">,</span><span style="color: #800080;">5</span><span style="color: #a9a9a9;">,</span><span style="color: #800080;">6</span><span style="color: #000000;">)</span><span style="color: #a9a9a9;">,</span><span style="color: #000000;">(</span><span style="color: #800080;">7</span><span style="color: #a9a9a9;">,</span><span style="color: #800080;">8</span><span style="color: #a9a9a9;">,</span><span style="color: #800080;">9</span><span style="color: #000000;">)</span><span style="color: #000000;">)</span>            

<span style="color: #0000ff;">Write-Host</span> <span style="color: #000080;">-ForegroundColor</span> <span style="color: #8a2be2;">green</span> <span style="color: #8a2be2;">Median</span>
<span style="color: #ff4500;">$wf</span><span style="color: #a9a9a9;">.</span><span style="color: #000000;">Median</span><span style="color: #000000;">(</span><span style="color: #ff4500;">$data</span><span style="color: #000000;">)</span>            

<span style="color: #0000ff;">Write-Host</span> <span style="color: #000080;">-ForegroundColor</span> <span style="color: #8a2be2;">green</span> <span style="color: #8a2be2;">StDev</span>
<span style="color: #ff4500;">$wf</span><span style="color: #a9a9a9;">.</span><span style="color: #000000;">StDev</span><span style="color: #000000;">(</span><span style="color: #ff4500;">$data</span><span style="color: #000000;">)</span>            

<span style="color: #0000ff;">Write-Host</span> <span style="color: #000080;">-ForegroundColor</span> <span style="color: #8a2be2;">green</span> <span style="color: #8a2be2;">Var</span>
<span style="color: #ff4500;">$wf</span><span style="color: #a9a9a9;">.</span><span style="color: #000000;">Var</span><span style="color: #000000;">(</span><span style="color: #ff4500;">$data</span><span style="color: #000000;">)</span>            

<span style="color: #0000ff;">Write-Host</span> <span style="color: #000080;">-ForegroundColor</span> <span style="color: #8a2be2;">green</span> <span style="color: #8a2be2;">MInverse</span>
<span style="color: #ff4500;">$wf</span><span style="color: #a9a9a9;">.</span><span style="color: #000000;">MInverse</span><span style="color: #000000;">(</span><span style="color: #ff4500;">$m</span><span style="color: #000000;">)</span>            

<span style="color: #ff4500;">$xl</span><span style="color: #a9a9a9;">.</span><span style="color: #000000;">quit</span><span style="color: #000000;">(</span><span style="color: #000000;">)</span>
<span style="color: #ff4500;">$xlprocess</span> <span style="color: #a9a9a9;">|</span> <span style="color: #0000ff;">kill</span></pre>
<pre class="PowerShellColorizedScript" style="width: 237px; height: 327px;"><span style="color: #006400;"># Results</span>
<span style="color: #8b0000;"><span style="color: #80ff00;"><span style="color: #008000;">Median</span>
</span>2.5
<span style="color: #008000;">StDev</span>
1.29099444873581
<span style="color: #008000;">Var</span>
1.66666666666667
<span style="color: #008000;">MInverse</span>
-4.5035996273705E+15
9.00719925474099E+15
-4.5035996273705E+15
9.007199254741E+15
-1.8014398509482E+16
9.00719925474099E+15
-4.5035996273705E+15
9.00719925474099E+15
-4.5035996273705E+15</span></pre>
<h3>Grab the Code</h3>
<p>I put the code up on my <a href="https://github.com/dfinke/powershell/blob/master/Calling%20Excel%20Functions%20From%20PowerShell/Invoke-ExcelFunction.ps1">GitHub PowerShell Repository</a>.</p>
<p><a class="a2a_dd addtoany_share_save" href="http://www.addtoany.com/share_save#url=http%3A%2F%2Fwww.dougfinke.com%2Fblog%2Findex.php%2F2011%2F04%2F05%2Fcalling-excel-math-functions-from-powershell%2F&amp;title=Calling%20Excel%20Math%20Functions%20From%20PowerShell"><img src="http://www.dougfinke.com/blog/wp-content/plugins/add-to-any/share_save_171_16.png" width="171" height="16" alt="Share"/></a> </p>
<p><img src="http://feeds.feedburner.com/~r/DevelopmentInABlink/~4/-1Em1PVhAeE" height="1" width="1"/></p>
]]></content:encoded>
			<wfw:commentRss>http://feedproxy.google.com/~r/DevelopmentInABlink/~3/-1Em1PVhAeE/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Need to get this tee shirt</title>
		<link>http://feedproxy.google.com/~r/DevelopmentInABlink/~3/vakqLaxaAqk/</link>
		<comments>http://feedproxy.google.com/~r/DevelopmentInABlink/~3/vakqLaxaAqk/#comments</comments>
		<pubDate>Mon, 07 Feb 2011 13:34:59 +0000</pubDate>
		<dc:creator>Doug Finke</dc:creator>
				<category><![CDATA[Functional Programming]]></category>
		<category><![CDATA[PowerShell]]></category>

		<guid isPermaLink="false">http://www.dougfinke.com/blog/?p=1159</guid>
		<description><![CDATA[Found this, &#8220;Practical Haskell Programming: Scripting with Types&#8221; from Don Stewart, on Lambda the Ultimate.]]></description>
			<content:encoded><![CDATA[<p>Found this, &#8220;<a href="http://donsbot.files.wordpress.com/2009/01/semicolon.pdf">Practical Haskell  Programming: Scripting with Types</a>&#8221; from Don Stewart, on <a href="http://lambda-the-ultimate.org/">Lambda the Ultimate</a>.</p>
<p style="text-align: center;"><a href="http://www.dougfinke.com/blog/wp-content/uploads/2011/02/script.jpg"><img class="size-medium wp-image-1160 aligncenter" title="script" src="http://www.dougfinke.com/blog/wp-content/uploads/2011/02/script-300x300.jpg" alt="" width="300" height="300" /></a></p>
<p><a class="a2a_dd addtoany_share_save" href="http://www.addtoany.com/share_save#url=http%3A%2F%2Fwww.dougfinke.com%2Fblog%2Findex.php%2F2011%2F02%2F07%2Fneed-to-get-this-tee-shirt%2F&amp;title=Need%20to%20get%20this%20tee%20shirt"><img src="http://www.dougfinke.com/blog/wp-content/plugins/add-to-any/share_save_171_16.png" width="171" height="16" alt="Share"/></a> </p>
<p><img src="http://feeds.feedburner.com/~r/DevelopmentInABlink/~4/vakqLaxaAqk" height="1" width="1"/></p>
]]></content:encoded>
			<wfw:commentRss>http://feedproxy.google.com/~r/DevelopmentInABlink/~3/vakqLaxaAqk/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>PowerShell Inside of Visual Studio – NuGet (formerly known as NuPack)</title>
		<link>http://feedproxy.google.com/~r/DevelopmentInABlink/~3/O1kLwa4cjXQ/</link>
		<comments>http://feedproxy.google.com/~r/DevelopmentInABlink/~3/O1kLwa4cjXQ/#comments</comments>
		<pubDate>Fri, 29 Oct 2010 19:22:36 +0000</pubDate>
		<dc:creator>Doug Finke</dc:creator>
				<category><![CDATA[Functional Programming]]></category>
		<category><![CDATA[PowerShell]]></category>

		<guid isPermaLink="false">http://www.dougfinke.com/blog/index.php/2010/10/29/powershell-inside-of-visual-studio-nuget-formerly-known-as-nupack/</guid>
		<description><![CDATA[Scott Hanselman demoed the PowerShell Package Manager at PDC10. PowerShell inside Visual Studio 2010 That’s right, PowerShell inside Visual Studio 2010. Interesting possibilities. He also demoed (code that won’t will be shipped) where he worked Visual Studio like a puppet on strings from the PowerShell console. Again, interesting possibilities. NuPack is a free, open source [...]]]></description>
			<content:encoded><![CDATA[<p><a href="http://www.hanselman.com/blog/">Scott Hanselman</a> demoed the PowerShell Package Manager at <a href="http://player.microsoftpdc.com/Session/e0c3ce51-9869-456c-a197-63dc0283f57e">PDC10</a>. </p>
<h3>PowerShell inside Visual Studio 2010</h3>
<p>That’s right, PowerShell inside Visual Studio 2010. Interesting possibilities. He also demoed (code that <strike>won’t</strike> <em>will</em> be shipped) where he worked Visual Studio like a puppet on strings from the PowerShell console. Again, interesting possibilities.</p>
<p><a href="http://nupack.codeplex.com/">NuPack</a> is a free, open source developer focused package management system for the .NET platform. I’ve blogged on NuPack and Power Console. PowerConsole has been re-released as part of NuPack.</p>
<ul>
<li><a href="http://www.dougfinke.com/blog/index.php/2010/10/21/check-available-net-packages-without-nupack-installed/">Check Available .NET Packages without NuPack Installed</a> </li>
<li><a href="http://www.dougfinke.com/blog/index.php/2010/10/06/nupack-open-source-package-manager-for-net-includes-a-powershell-interface/">NuPack &#8211; Open Source Package Manager for .NET &#8211; Includes a PowerShell Interface</a> </li>
<li><a href="http://www.dougfinke.com/blog/index.php/2010/05/16/visual-studio-keymaps-using-powershell/">Visual Visual Studio Keymaps using PowerShell</a> </li>
<li><a href="http://www.dougfinke.com/blog/index.php/2010/05/16/accessing-visual-studios-automation-api-from-powershell/">Accessing Visual Studio’s Automation API From PowerShell</a> </li>
<li><a href="http://www.dougfinke.com/blog/index.php/2010/04/02/powershell-and-f-consoles-in-visual-studio-2010/">PowerShell and F# Consoles in Visual Studio 2010</a> </li>
<li><a href="http://www.dougfinke.com/blog/index.php/2010/03/14/powerconsole-powershell-integrated-with-visual-studio-2010/">PowerConsole &#8211; PowerShell Integrated with Visual Studio 2010</a> </li>
</ul>
<p><img src="http://feeds.feedburner.com/~r/DevelopmentInABlink/~4/O1kLwa4cjXQ" height="1" width="1"/></p>
]]></content:encoded>
			<wfw:commentRss>http://feedproxy.google.com/~r/DevelopmentInABlink/~3/O1kLwa4cjXQ/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Interview with Kalani Thielen: Trends in Programming Languages</title>
		<link>http://northhorizon.net/2010/interview-with-kalani-thielen-trends-in-programming-languages/</link>
		<comments>http://northhorizon.net/2010/interview-with-kalani-thielen-trends-in-programming-languages/#comments</comments>
		<pubDate>Mon, 27 Sep 2010 13:30:45 +0000</pubDate>
		<dc:creator>Daniel Moore</dc:creator>
				<category><![CDATA[.Net]]></category>
		<category><![CDATA[Functional Programming]]></category>
		<category><![CDATA[Lab49]]></category>
		<category><![CDATA[Python]]></category>
		<category><![CDATA[Ruby]]></category>

		<guid isPermaLink="false">http://northhorizon.net/?p=358</guid>
		<description><![CDATA[Last week I interviewed colleague Kalani Thielen, Lab49&#8242;s resident expert on programming language theory. We discussed some of the new languages we&#8217;ve seen this decade, the recent functional additions to imperative languages, and the role DSLs will play in the future. Read on for the full interview. DM F#, Clojure, and Scala are all fairly [...]]]></description>
			<content:encoded><![CDATA[<p>Last week I interviewed colleague <a href="http://blog.lab49.com/archives/author/kthielen">Kalani Thielen</a>, Lab49&#8242;s resident expert on programming language theory. We discussed some of the new languages we&#8217;ve seen this decade, the recent functional additions to imperative languages, and the role DSLs will play in the future. Read on for the full interview.<span id="more-358"></span></p>
<p><strong>DM</strong> F#, Clojure, and Scala are all fairly new and popular languages this decade, the former two with striking resemblance to OCaml and Lisp, respectively, and the lattermost being more original in syntax. In what way do these languages represent forward thinking in language design, or how do they fail to build upon lessons learned in more venerable languages like Haskell?</p>
<p><strong>KT</strong> It’s a common story in the world of software that time brings increasingly precise and accurate programs.  Anybody who grew up playing games on an Atari 2600 has witnessed this firsthand.  The image of a character has changed from one block, to five blocks, to fifty blocks, to (eventually) thousands of polygons.  By this modern analog of the Greeks’ method of exhaustion, Mario’s facial structure has become increasingly clear.  This inevitable progression, squeezed out between the increasing sophistication of programmers and the decreasing punishment of Moore’s Law, has primarily operated at three levels: the images produced by game programs, the logic of the game programs themselves, and finally the programming languages with which programs are produced.  It’s this last group that deserves special attention today.</p>
<p>The lambda calculus (and its myriad derivatives) exemplifies this progression at the level of programming languages.  In the broadest terms, you have the untyped lambda calculus at the least-defined end (which closely fits languages like Lisp, Scheme, Clojure, Ruby and Python), and the calculus of constructions at the most-defined end (which closely fits languages like Cayenne and Epigram).  With the least imposed structure, you can’t solve the halting problem, and with the most imposed structure you (trivially) can solve it.  With the language of the untyped lambda calculus, you get a blocky, imprecise image of what your program does, and in the calculus of constructions you get a crisp, precise image.</p>
<p>Languages like F#, Scala and Haskell each fall somewhere in between these two extremes.  None of them are precise enough to accept only halting programs (although Haskell is inching more and more toward a dependently-typed language every year).  Yet all of them are more precise than (say) Scheme, where fallible human convention alone determines whether or not the “+” function returns an integer or a chicken.  But even between these languages there is a gulf of expressiveness.  Where a language like C is monomorphically-typed (and an “int_list” must remain ever distinguished from a “char_list”), F# introduces principled polymorphic types (where, pun intended, you can have “’a list” for any type ‘a).  Beyond that, Haskell (and Scala) offer bounded polymorphism so that constraints can be imposed (or inferred) on any polymorphic type – you can correctly identify the “==” function as having type “Eq a =&gt; a -&gt; a -&gt; Bool” so that equality can be determined only on those types which have an equivalence relation, whereas F# has to make do with the imprecise claim that its “=” function can compare any types.</p>
<p>No modern programming language is perfect, but the problems that we face today and the history of our industry points the way toward ever more precise languages.  Logic, unreasonably effective in the field of computer science, has already set the ideal that we’re working toward.  Although today you might hear talk that referential transparency in functional languages makes a parallel map safe, tomorrow it will be that a type-level proof of associativity makes a parallel <em>reduce</em> safe.  Until then, it’s worth learning Haskell (or Scala if you must), where you can count the metaphorical fingers on Mario’s hands, though not yet the hairs of his moustache.</p>
<p><strong>DM</strong> One might assume that increased &#8220;precision&#8221; in a language would come at the cost of increased complexity in concepts and/or syntax. In a research scenario, the ability to solve the halting problem certainly has its merits, but is that useful for modern commercial application development, and, if so, does it justify the steeper learning curve?</p>
<p><strong>KT</strong> It&#8217;s absolutely true that languages that can express concepts more precisely also impose a burden on programmers, and that a major part of work in language design goes into making that burden as light as possible (hence type-inference, auto roll/unroll for recursive types, pack/unpack for existential types, etc).</p>
<p>However &#8212; to your point about the value of that increased precision – I would argue that it&#8217;s even <em>more</em> important in commercial application development than in academia.  For example, say you&#8217;ve just rolled out a new pricing server for a major client.  Does it halt?  There&#8217;s a lot more riding on that answer than you&#8217;re likely to find in academia.  And really, whether or not it halts is just one of the simplest questions you can ask.  What are its time/space characteristics?  Can it safely be run in parallel?  Is it monotonic?  In our business, these questions translate into dollars and reputation.  Frankly I think it&#8217;s amazing that we&#8217;ve managed to go on this long without formal verification.</p>
<p><strong>DM</strong> Most dynamic languages have some air of functional programming to them, while still being fundamentally imperative. Even more rigorous imperative languages like C# are picking up on a more functional style of programming. The two languages you mentioned earlier, Cayenne and Epigram, are both functional languages. Are we moving toward a pure functional paradigm, or will there continue to be a need for imperative/functional hybrids?</p>
<p><strong>KT</strong> What is a &#8220;functional language&#8221;?  If it&#8217;s a language with first-class functions, then C is a functional language.  If it&#8217;s a language that disallows hidden side-effects, then Haskell isn&#8217;t a functional language.  I think that, at least as far as discussing the design and development of programming languages is concerned, it&#8217;s well worth getting past that sort of &#8220;sales pitch&#8221;.</p>
<p>I believe that we&#8217;re moving toward programming languages that allow programmers to be increasingly precise about what their programs are supposed to do, up to the level of detail necessary.  The great thing about referential transparency is that it makes it very easy to reason about what a function does &#8212; it&#8217;s almost as easy as high school algebra.  However, if you&#8217;re not engaged in computational geometry, but rather need to transfer some files via FTP, there&#8217;s just no way around it.  You&#8217;ve got to do this, then this, then this, and you&#8217;ll need to switch to something more complicated, like Hoare logic, to reason about what your program is doing.  Even there, you have plenty of opportunity for precision &#8212; you expect to use hidden side-effects but only of a certain type (transfer files but don&#8217;t launch missiles).</p>
<p>But maybe the most important tool in programming is logic itself.  It&#8217;s a fundamental fact – well known in some circles as the &#8220;Curry-Howard isomorphism&#8221; – that programs and proofs are equivalent in a very subtle and profound way.  This fact has produced great wealth for CS researchers, who can take the results painstakingly derived by logicians 100 years ago and (almost mechanically) publish an outline of their computational analog.  Yet, although this amazing synthesis has taken place rivaling the unification of electricity and magnetism, most programmers in industry are scarcely aware of it.  It&#8217;s going to take some time.</p>
<p>I think there&#8217;s a good answer to your question in that correspondence between logic and programming.  The function, or &#8220;implication connective&#8221; (aka &#8220;-&gt;&#8221;), is an important tool and ought to feature in any modern language.  As well, there are other logical connectives that should be examined.  For example, conjunction is common (manifested as pair, tuple, or record types in a programming language), but disjunction (corresponding to variant types) is less common though no less important.  Negation (corresponding to continuations consuming the negated type), predicated quantified types, and so on.  The tools for building better software are there, but we need to work at recognizing them and putting them to good use.</p>
<p>Anybody interested in understanding these logical tools better should pick up a copy of Benjamin Pierce&#8217;s book<em> Types and Programming Languages</em>.</p>
<p><strong>DM </strong>Many frameworks have a one or more DSLs to express things as mundane as configuration to tasks as complicated as UI layout, in an effort to be more express specific kinds of ideas more concisely. Do you see this as an expanding part of the strategy for language designers to increase expressiveness in code? Is it possible that what we consider &#8220;general purpose languages&#8221; today will become more focused on marshalling data from one DSL to another, or will DSLs continue to remain a more niche tool?</p>
<p><strong>KT</strong> I guess it depends on what you mean by &#8220;DSL&#8221;.  Like you say, some people just have in mind some convenient shorthand serialization for data structures (I&#8217;ve heard some people refer to a text format for orders as a DSL, for example).  I&#8217;m sure that will always be around, and there&#8217;s nothing really profound about it.</p>
<p>On the other hand, by &#8220;DSL&#8221; you could mean some sub-Turing language with non-trivial semantics.  For example, context-free grammars or makefiles.  Modern programming languages, like Haskell, are often used to embed these &#8220;sub-languages&#8221; as combinator libraries (the &#8220;Composing Contracts&#8221; paper by Simon Peyton-Jones et al is a good example of this).  I think it&#8217;s likely that these will continue as valuable niche tools.  If you take monadic parser combinators for example, it&#8217;s very attractive the way that they fit together within the normal semantics of Haskell, however you&#8217;ve got to go through some severe mental gymnastics to determine for certain what the space/time characteristics of a given parser will be.  Contrast that with good old LALR(1) parsers, where if the LR table can be derived you know for certain what the space/time characteristics of your parser will be.</p>
<p>On the third hand, if a &#8220;DSL&#8221; is a data structure with semantics of any kind, your description of a future where programs are written as transformations between DSLs could reasonably describe the way that compilers are written today.  Generally a compiler is just a sequence of semantics-preserving transformations between data structures (up to assembly statements).  I happen to think that&#8217;s a great way to write software, so I hope it&#8217;s the case that it will become ever more successful.</p>
]]></content:encoded>
			<wfw:commentRss>http://northhorizon.net/2010/interview-with-kalani-thielen-trends-in-programming-languages/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>How To Load .NET Assemblies In A PowerShell Session</title>
		<link>http://feedproxy.google.com/~r/DevelopmentInABlink/~3/qhvxJXyfSww/</link>
		<comments>http://feedproxy.google.com/~r/DevelopmentInABlink/~3/qhvxJXyfSww/#comments</comments>
		<pubDate>Sun, 29 Aug 2010 17:08:00 +0000</pubDate>
		<dc:creator>Doug Finke</dc:creator>
				<category><![CDATA[.Net]]></category>
		<category><![CDATA[Functional Programming]]></category>
		<category><![CDATA[PowerShell]]></category>

		<guid isPermaLink="false">http://www.dougfinke.com/blog/index.php/2010/08/29/how-to-load-net-assemblies-in-a-powershell-session/</guid>
		<description><![CDATA[PowerShell is built on top of .NET. This allows you to tap into the power of the .NET framework as well as any DLLs/Assemblies you build. In version 2 of PowerShell the Add-type cmdlet was added which is the preferred way to load .NET assemblies. In PowerShell Version 1 that cmdlet is not available so [...]]]></description>
			<content:encoded><![CDATA[<p>PowerShell is built on top of .NET. This allows you to tap into the power of the .NET framework as well as any DLLs/Assemblies you build. In version 2 of PowerShell the <em><strong>Add-type</strong></em> cmdlet was added which is the preferred way to load .NET assemblies. </p>
<p>In PowerShell Version 1 that cmdlet is not available so you need to use the one of the Load* static methods found in System.Reflection.Assembly.</p>
<table border="0" cellspacing="0" cellpadding="2" width="565">
<tbody>
<tr>
<td valign="top" width="200"><span style="color: #008080">[Reflection.Assembly]</span><span style="color: #a9a9a9">::</span><span style="color: #000000">Load</span></td>
<td valign="top" width="363">
<p>Loads an assembly</p>
</td>
</tr>
<tr>
<td valign="top" width="200"><span style="color: #008080">[Reflection.Assembly]</span><span style="color: #a9a9a9">::</span><span style="color: #000000">LoadFile</span></td>
<td valign="top" width="363">Loads the contents of an assembly file on the specified path</td>
</tr>
<tr>
<td valign="top" width="200"><span style="color: #008080">[Reflection.Assembly]</span><span style="color: #a9a9a9">::</span><span style="color: #000000">LoadFrom</span> </td>
<td valign="top" width="363">Loads an assembly given its file name or path</td>
</tr>
<tr>
<td valign="top" width="200"><span style="color: #008080">[Reflection.Assembly]</span><span style="color: #a9a9a9">::</span><span style="color: #000000">LoadWithPartialName</span></td>
<td valign="top" width="363">Loads an assembly from the application directory or from the global assembly cache using a partial name</td>
</tr>
</tbody>
</table>
<h3>Why?</h3>
<p>For example, in PowerShell, if you want to encode a Url you can use the UrlEncode method found in the .NET HttpUtility Class.</p>
<p>If you fire up PowerShell and try to call the static method UrlEncode found in System.Web.HttpUtility you’ll get this error.</p>
<pre class="PowerShellColorizedScript"><span style="color: #008080">[System.Web.HttpUtility]</span><span style="color: #a9a9a9">::</span><span style="color: #000000">UrlEncode</span><span style="color: #000000">(</span><span style="color: #8b0000">&quot;this is a test&quot;</span><span style="color: #000000">)</span></pre>
<p><font color="#ff0000">Unable to find type [System.Web.HttpUtility]: make sure that the assembly containing this type is loaded.</font></p>
<p><font color="#000000">You can solve this by loading the System.Web .NET assembly. This is equivalent to being in the Visual Studio IDE, adding a reference and then adding a using statement.</font></p>
<h3>Using Reflection.Assembly in PowerShell Version 1</h3>
<p><font color="#ff0000"></font></p>
<pre class="PowerShellColorizedScript"><span style="color: #008080">[Reflection.Assembly]</span><span style="color: #a9a9a9">::</span><span style="color: #000000">LoadFile</span><span style="color: #000000">(</span> <span style="color: #000000">`
</span>  <span style="color: #8b0000">'C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\System.Web.dll'</span><span style="color: #000000">)</span><span style="color: #000000">`
</span>  <span style="color: #a9a9a9">|</span> <span style="color: #0000ff">out-null</span>            

<span style="color: #008080">[System.Web.HttpUtility]</span><span style="color: #a9a9a9">::</span><span style="color: #000000">UrlEncode</span><span style="color: #000000">(</span><span style="color: #8b0000">&quot;this is a test&quot;</span><span style="color: #000000">)</span></pre>
<h3>Using Add-Type in PowerShell Version 2</h3>
<pre class="PowerShellColorizedScript"><span style="color: #0000ff">Add-Type</span> <span style="color: #000080">-AssemblyName</span> <span style="color: #8a2be2">System.Web</span>
<span style="color: #008080">[System.Web.HttpUtility]</span><span style="color: #a9a9a9">::</span><span style="color: #000000">UrlEncode</span><span style="color: #000000">(</span><span style="color: #8b0000">&quot;this is a test&quot;</span><span style="color: #000000">)</span></pre>
<h3>Additional Reflection.Assembly usage</h3>
<pre style="width: 559px; height: 93px" class="PowerShellColorizedScript"><span style="color: #008080">[void]</span> <span style="color: #008080">[Reflection.Assembly]</span><span style="color: #a9a9a9">::</span><span style="color: #000000">LoadWithPartialName</span><span style="color: #000000">(</span><span style="color: #8b0000">&quot;System.Windows.Forms&quot;</span><span style="color: #000000">)</span>
<span style="color: #008080">[reflection.assembly]</span><span style="color: #a9a9a9">::</span><span style="color: #000000">Load</span><span style="color: #000000">(</span><span style="color: #8b0000">&quot;mscorlib.dll&quot;</span><span style="color: #000000">)</span> <span style="color: #a9a9a9">|</span> <span style="color: #0000ff">Out-Null</span>
<span style="color: #008080">[void]</span><span style="color: #008080">[system.reflection.assembly]</span><span style="color: #a9a9a9">::</span><span style="color: #000000">loadfrom</span><span style="color: #000000">(</span><span style="color: #8b0000">&quot;c:\windows\system32\inetsrv\microsoft.web.administration.dll&quot;</span><span style="color: #000000">)</span></pre>
<h3>Additional Add-Type usage</h3>
<pre style="width: 565px; height: 54px" class="PowerShellColorizedScript"><span style="color: #0000ff">Add-Type</span> <span style="color: #000080">-AssemblyName</span> <span style="color: #8b0000">&quot;System.Windows.Forms&quot;</span>
<span style="color: #0000ff">Add-Type</span> <span style="color: #000080">-AssemblyName</span> <span style="color: #8b0000">&quot;mscorlib.dll&quot;</span>
<span style="color: #0000ff">Add-Type</span> <span style="color: #000080">-Path</span> <span style="color: #8b0000">&quot;c:\windows\system32\inetsrv\microsoft.web.administration.dll&quot;</span></pre>
<h3>Compiling C# on the fly in Version 2</h3>
<pre class="PowerShellColorizedScript"><span style="color: #0000ff">Add-Type</span> <span style="color: #000080">-TypeDefinition</span> <span style="color: #8b0000">@&quot;
public class Test
{
    public static int Add(int n1, int n2)
    {
        return n1 + n2;
    }
}
&quot;@</span></pre>
<p>If you change the <em>signature</em> of the Add method you will get this error:</p>
<p><a href="http://dougfinke.com/uploadPictures/LoadingaDLLintoaPowerShellSession_114E7/image.png"><img style="border-right-width: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px" title="image" border="0" alt="image" src="http://dougfinke.com/uploadPictures/LoadingaDLLintoaPowerShellSession_114E7/image_thumb.png" width="540" height="18" /></a></p>
<p>When compiling code on the fly or loading assemblies they <em><strong>cannot </strong></em>be unloaded.</p>
<blockquote>
<p>.NET assemblies can&#8217;t be unloaded from a session (it&#8217;s a .NET thing, not a PowerShell thing) therefore DLLs can&#8217;t be unloaded from a session. This means that you can&#8217;t update a DLLs once it&#8217;s been loaded. We can&#8217;t even update the assembly on disk because the file is locked when the assembly is loaded.</p>
<p>- Bruce Payette <strong><a href="http://www.manning.com/payette2/">Windows PowerShell in Action, Second Edition</a></strong></p>
</blockquote>
<h3>Another way to use the –Path parameter on Add-Type</h3>
<p>You can point to a C# source code file directly.</p>
<pre class="PowerShellColorizedScript"><span style="color: #0000ff">Add-Type</span> <span style="color: #000080">–Path</span> <span style="color: #8a2be2">c:\test\Hello.cs</span></pre>
<h3>Add-Type is not limited to compiling only C#</h3>
<p>You can inline these languages using the –Language parameter CSharp, CSharpVersion3, VisualBasic, JScript.</p>
<p>Notice, F# is not supported. Here is a post <a href="http://www.dougfinke.com/blog/index.php/2010/04/18/how-to-add-an-f-type-to-a-powershell-session/">How to add an F# type to a PowerShell session</a> that inlines F#.</p>
<p><strong>NOTE: </strong>This uses the F# DLLs shipped with .NET 4.0</p>
<pre class="PowerShellColorizedScript"><span style="color: #0000ff">Add-TypeFSharp</span> <span style="color: #000080">-TypeDefinition</span> <span style="color: #8b0000">@&quot;
module MyModule

let Add a b = a + b;;
&quot;@</span>                        

<span style="color: #800080">1</span><span style="color: #a9a9a9">..</span><span style="color: #800080">10</span> <span style="color: #a9a9a9">|</span> <span style="color: #0000ff">%</span> <span style="color: #000000">{</span> <span style="color: #008080">[MyModule]</span><span style="color: #a9a9a9">::</span><span style="color: #000000">Add</span><span style="color: #000000">(</span> <span style="color: #ff4500">$_</span><span style="color: #a9a9a9">,</span> <span style="color: #ff4500">$_</span><span style="color: #a9a9a9">*</span><span style="color: #800080">2</span> <span style="color: #000000">)</span> <span style="color: #000000">}</span></pre>
<h3>Finally</h3>
<p>There are additional parameters that the Add-Type cmdlet supports. You can generate a DLL file for the assembly with the specified name in the location, specify compiler parameters, specify assemblies which your code depends on and use wild cards when loading assemblies.</p>
<p>Check out the <a href="http://technet.microsoft.com/en-us/library/dd315241.aspx">online help for Add-Type</a>.</p>
<p><img src="http://feeds.feedburner.com/~r/DevelopmentInABlink/~4/qhvxJXyfSww" height="1" width="1"/></p>
]]></content:encoded>
			<wfw:commentRss>http://feedproxy.google.com/~r/DevelopmentInABlink/~3/qhvxJXyfSww/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>How To Load .NET Assemblies In A PowerShell Session</title>
		<link>http://feedproxy.google.com/~r/DevelopmentInABlink/~3/_ql_tLMzTho/</link>
		<comments>http://feedproxy.google.com/~r/DevelopmentInABlink/~3/_ql_tLMzTho/#comments</comments>
		<pubDate>Wed, 25 Aug 2010 02:00:04 +0000</pubDate>
		<dc:creator>Doug Finke</dc:creator>
				<category><![CDATA[.Net]]></category>
		<category><![CDATA[Functional Programming]]></category>
		<category><![CDATA[PowerShell]]></category>

		<guid isPermaLink="false">http://www.dougfinke.com/blog/?p=1069</guid>
		<description><![CDATA[PowerShell is built on top of .NET. This allows you to tap into the power of the .NET framework as well as any DLLs/Assemblies you build. In version 2 of PowerShell the Add-type cmdlet was added which is the preferred way to load .NET assemblies. In PowerShell Version 1 that cmdlet is not available so [...]]]></description>
			<content:encoded><![CDATA[<p>PowerShell is built on top of .NET. This allows you to tap into the power of the .NET framework as well as any DLLs/Assemblies you build. In version 2 of PowerShell the <em><strong>Add-type</strong></em> cmdlet was added which is the preferred way to load .NET assemblies. </p>
<p>In PowerShell Version 1 that cmdlet is not available so you need to use the one of the Load* static methods found in System.Reflection.Assembly.</p>
<table border="0" cellspacing="0" cellpadding="2" width="565">
<tbody>
<tr>
<td valign="top" width="200"><span style="color: #008080">[Reflection.Assembly]</span><span style="color: #a9a9a9">::</span><span style="color: #000000">Load</span></td>
<td valign="top" width="363">
<p>Loads an assembly</p>
</td>
</tr>
<tr>
<td valign="top" width="200"><span style="color: #008080">[Reflection.Assembly]</span><span style="color: #a9a9a9">::</span><span style="color: #000000">LoadFile</span></td>
<td valign="top" width="363">Loads the contents of an assembly file on the specified path</td>
</tr>
<tr>
<td valign="top" width="200"><span style="color: #008080">[Reflection.Assembly]</span><span style="color: #a9a9a9">::</span><span style="color: #000000">LoadFrom</span> </td>
<td valign="top" width="363">Loads an assembly given its file name or path</td>
</tr>
<tr>
<td valign="top" width="200"><span style="color: #008080">[Reflection.Assembly]</span><span style="color: #a9a9a9">::</span><span style="color: #000000">LoadWithPartialName</span></td>
<td valign="top" width="363">Loads an assembly from the application directory or from the global assembly cache using a partial name</td>
</tr>
</tbody>
</table>
<h3>Why?</h3>
<p>For example, in PowerShell, if you want to encode a Url you can use the UrlEncode method found in the .NET HttpUtility Class.</p>
<p>If you fire up PowerShell and try to call the static method UrlEncode found in System.Web.HttpUtility you’ll get this error.</p>
<pre class="PowerShellColorizedScript"><span style="color: #008080">[System.Web.HttpUtility]</span><span style="color: #a9a9a9">::</span><span style="color: #000000">UrlEncode</span><span style="color: #000000">(</span><span style="color: #8b0000">&quot;this is a test&quot;</span><span style="color: #000000">)</span></pre>
<p><font color="#ff0000">Unable to find type [System.Web.HttpUtility]: make sure that the assembly containing this type is loaded.</font></p>
<p><font color="#000000">You can solve this by loading the System.Web .NET assembly. This is equivalent to being in the Visual Studio IDE, adding a reference and then adding a using statement.</font></p>
<h3>Using Reflection.Assembly in PowerShell Version 1</h3>
<p><font color="#ff0000"></font></p>
<pre class="PowerShellColorizedScript"><span style="color: #008080">[Reflection.Assembly]</span><span style="color: #a9a9a9">::</span><span style="color: #000000">LoadFile</span><span style="color: #000000">(</span> <span style="color: #000000">`
</span>  <span style="color: #8b0000">'C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\System.Web.dll'</span><span style="color: #000000">)</span><span style="color: #000000">`
</span>  <span style="color: #a9a9a9">|</span> <span style="color: #0000ff">out-null</span>            

<span style="color: #008080">[System.Web.HttpUtility]</span><span style="color: #a9a9a9">::</span><span style="color: #000000">UrlEncode</span><span style="color: #000000">(</span><span style="color: #8b0000">&quot;this is a test&quot;</span><span style="color: #000000">)</span></pre>
<h3>Using Add-Type in PowerShell Version 2</h3>
<pre class="PowerShellColorizedScript"><span style="color: #0000ff">Add-Type</span> <span style="color: #000080">-AssemblyName</span> <span style="color: #8a2be2">System.Web</span>
<span style="color: #008080">[System.Web.HttpUtility]</span><span style="color: #a9a9a9">::</span><span style="color: #000000">UrlEncode</span><span style="color: #000000">(</span><span style="color: #8b0000">&quot;this is a test&quot;</span><span style="color: #000000">)</span></pre>
<h3>Additional Reflection.Assembly usage</h3>
<pre style="width: 559px; height: 93px" class="PowerShellColorizedScript"><span style="color: #008080">[void]</span> <span style="color: #008080">[Reflection.Assembly]</span><span style="color: #a9a9a9">::</span><span style="color: #000000">LoadWithPartialName</span><span style="color: #000000">(</span><span style="color: #8b0000">&quot;System.Windows.Forms&quot;</span><span style="color: #000000">)</span>
<span style="color: #008080">[reflection.assembly]</span><span style="color: #a9a9a9">::</span><span style="color: #000000">Load</span><span style="color: #000000">(</span><span style="color: #8b0000">&quot;mscorlib.dll&quot;</span><span style="color: #000000">)</span> <span style="color: #a9a9a9">|</span> <span style="color: #0000ff">Out-Null</span>
<span style="color: #008080">[void]</span><span style="color: #008080">[system.reflection.assembly]</span><span style="color: #a9a9a9">::</span><span style="color: #000000">loadfrom</span><span style="color: #000000">(</span><span style="color: #8b0000">&quot;c:\windows\system32\inetsrv\microsoft.web.administration.dll&quot;</span><span style="color: #000000">)</span></pre>
<h3>Additional Add-Type usage</h3>
<pre style="width: 565px; height: 54px" class="PowerShellColorizedScript"><span style="color: #0000ff">Add-Type</span> <span style="color: #000080">-AssemblyName</span> <span style="color: #8b0000">&quot;System.Windows.Forms&quot;</span>
<span style="color: #0000ff">Add-Type</span> <span style="color: #000080">-AssemblyName</span> <span style="color: #8b0000">&quot;mscorlib.dll&quot;</span>
<span style="color: #0000ff">Add-Type</span> <span style="color: #000080">-Path</span> <span style="color: #8b0000">&quot;c:\windows\system32\inetsrv\microsoft.web.administration.dll&quot;</span></pre>
<h3>Compiling C# on the fly in Version 2</h3>
<pre class="PowerShellColorizedScript"><span style="color: #0000ff">Add-Type</span> <span style="color: #000080">-TypeDefinition</span> <span style="color: #8b0000">@&quot;
public class Test
{
    public static int Add(int n1, int n2)
    {
        return n1 + n2;
    }
}
&quot;@</span></pre>
<p>If you change the <em>signature</em> of the Add method you will get this error:</p>
<p><a href="http://dougfinke.com/uploadPictures/LoadingaDLLintoaPowerShellSession_114E7/image.png"><img style="border-right-width: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px" title="image" border="0" alt="image" src="http://dougfinke.com/uploadPictures/LoadingaDLLintoaPowerShellSession_114E7/image_thumb.png" width="540" height="18" /></a></p>
<p>When compiling code on the fly or loading assemblies they <em><strong>cannot </strong></em>be unloaded.</p>
<blockquote>
<p>.NET assemblies can&#8217;t be unloaded from a session (it&#8217;s a .NET thing, not a PowerShell thing) therefore DLLs can&#8217;t be unloaded from a session. This means that you can&#8217;t update a DLLs once it&#8217;s been loaded. We can&#8217;t even update the assembly on disk because the file is locked when the assembly is loaded.</p>
<p>- Bruce Payette <strong><a href="http://www.manning.com/payette2/">Windows PowerShell in Action, Second Edition</a></strong></p>
</blockquote>
<h3>Another way to use the –Path parameter on Add-Type</h3>
<p>You can point to a C# source code file directly.</p>
<pre class="PowerShellColorizedScript"><span style="color: #0000ff">Add-Type</span> <span style="color: #000080">–Path</span> <span style="color: #8a2be2">c:\test\Hello.cs</span></pre>
<h3>Add-Type is not limited to compiling only C#</h3>
<p>You can inline these languages using the –Language parameter CSharp, CSharpVersion3, VisualBasic, JScript.</p>
<p>Notice, F# is not supported. Here is a post <a href="http://www.dougfinke.com/blog/index.php/2010/04/18/how-to-add-an-f-type-to-a-powershell-session/">How to add an F# type to a PowerShell session</a> that inlines F#.</p>
<p><strong>NOTE: </strong>This uses the F# DLLs shipped with .NET 4.0</p>
<pre class="PowerShellColorizedScript"><span style="color: #0000ff">Add-TypeFSharp</span> <span style="color: #000080">-TypeDefinition</span> <span style="color: #8b0000">@&quot;
module MyModule

let Add a b = a + b;;
&quot;@</span>                        

<span style="color: #800080">1</span><span style="color: #a9a9a9">..</span><span style="color: #800080">10</span> <span style="color: #a9a9a9">|</span> <span style="color: #0000ff">%</span> <span style="color: #000000">{</span> <span style="color: #008080">[MyModule]</span><span style="color: #a9a9a9">::</span><span style="color: #000000">Add</span><span style="color: #000000">(</span> <span style="color: #ff4500">$_</span><span style="color: #a9a9a9">,</span> <span style="color: #ff4500">$_</span><span style="color: #a9a9a9">*</span><span style="color: #800080">2</span> <span style="color: #000000">)</span> <span style="color: #000000">}</span></pre>
<h3>Finally</h3>
<p>There are additional parameters that the Add-Type cmdlet supports. You can generate a DLL file for the assembly with the specified name in the location, specify compiler parameters, specify assemblies which your code depends on and use wild cards when loading assemblies.</p>
<p>Check out the <a href="http://technet.microsoft.com/en-us/library/dd315241.aspx">online help for Add-Type</a>.</p>
<p><img src="http://feeds.feedburner.com/~r/DevelopmentInABlink/~4/_ql_tLMzTho" height="1" width="1"/></p>
]]></content:encoded>
			<wfw:commentRss>http://feedproxy.google.com/~r/DevelopmentInABlink/~3/_ql_tLMzTho/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Forays into functional C# – Shared environment with closures</title>
		<link>http://lanshiva.blogspot.com/2010/07/forays-into-functional-c-shared.html</link>
		<comments>http://lanshiva.blogspot.com/2010/07/forays-into-functional-c-shared.html#comments</comments>
		<pubDate>Wed, 21 Jul 2010 02:21:00 +0000</pubDate>
		<dc:creator>Sivabalan Muthukumar</dc:creator>
				<category><![CDATA[.Net]]></category>
		<category><![CDATA[Functional Programming]]></category>
		<category><![CDATA[Technology]]></category>

		<guid isPermaLink="false"></guid>
		<description><![CDATA[One of the interesting features when dealing with closures is the ability to deal with multiple functions closed over the same environment. This feature opens up interesting possibilities (and nightmares if not careful) and proves really useful when cr...]]></description>
			<content:encoded><![CDATA[<p>One of the interesting features when dealing with closures is the ability to deal with multiple functions closed over the same environment. This feature opens up interesting possibilities (and nightmares if not careful) and proves really useful when creating more complex functional contexts.</p>
<p>Here is a quick trivial example that illustrates this:
<div class="wlWriterSmartContent" id="scid:9ce6104f-a9aa-4a17-a79f-3a39532ebf7c:8bbbfb27-3e51-4e50-aa7e-99b13516c8d1" style="display: inline; float: none; margin: 0px; padding: 0px;">
<div style="border: 1px solid rgb(0, 0, 128); color: black; font-family: 'Courier New',courier,monospace; font-size: 10pt;">
<div style="background: none repeat scroll 0% 0% rgb(221, 221, 221); max-height: 300px; overflow: auto;">
<ol style="background: none repeat scroll 0% 0% rgb(255, 255, 255); margin: 0px 0px 0px 2em; padding: 0px 0px 0px 5px;">
<li><span style="color: blue;">public</span> <span style="color: blue;">static</span> <span style="color: #2b91af;">Tuple</span>&lt;<span style="color: #2b91af;">Func</span>&lt;<span style="color: blue;">int</span>&gt;,<span style="color: #2b91af;">Func</span>&lt;<span style="color: blue;">int</span>&gt;&gt; SharedClosure(<span style="color: blue;">int</span> seed) </li>
<li style="background: none repeat scroll 0% 0% rgb(243, 243, 243);">&nbsp;&nbsp;&nbsp; { </li>
<li>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <span style="color: blue;">return</span> </li>
<li style="background: none repeat scroll 0% 0% rgb(243, 243, 243);">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <span style="color: #2b91af;">Tuple</span>.Create&lt;<span style="color: #2b91af;">Func</span>&lt;<span style="color: blue;">int</span>&gt;, <span style="color: #2b91af;">Func</span>&lt;<span style="color: blue;">int</span>&gt;&gt;( </li>
<li>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; () =&gt; (seed = seed + 1), </li>
<li style="background: none repeat scroll 0% 0% rgb(243, 243, 243);">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; () =&gt; (seed = seed &#8211; 1) </li>
<li>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; ); </li>
<li style="background: none repeat scroll 0% 0% rgb(243, 243, 243);">&nbsp;&nbsp;&nbsp; } </li>
</ol>
</div>
</div>
</div>
<p>The Tuple class used in the above snippet, represents a notion of an ordered set of elements (this will be available in .net 4.0 as part of the core framework). As usual, peeking into the above snippet using Reflector shows how the environment is shared as seen below:</p>
<div class="wlWriterSmartContent" id="scid:9ce6104f-a9aa-4a17-a79f-3a39532ebf7c:e7e03aac-b265-4397-ae31-4d28877bcdee" style="display: inline; float: none; margin: 0px; padding: 0px;">
<div style="border: 1px solid rgb(0, 0, 128); color: black; font-family: 'Courier New',courier,monospace; font-size: 10pt;">
<div style="background: none repeat scroll 0% 0% rgb(221, 221, 221); max-height: 300px; overflow: auto;">
<ol style="background: none repeat scroll 0% 0% rgb(255, 255, 255); margin: 0px 0px 0px 2.5em; padding: 0px 0px 0px 5px;">
<li>[<span style="color: #2b91af;">CompilerGenerated</span>] </li>
<li style="background: none repeat scroll 0% 0% rgb(243, 243, 243);"><span style="color: blue;">private</span> <span style="color: blue;">sealed</span> <span style="color: blue;">class</span> &lt;&gt;c__DisplayClass2 </li>
<li>{ </li>
<li style="background: none repeat scroll 0% 0% rgb(243, 243, 243);">&nbsp;&nbsp;&nbsp; <span style="color: green;">// Fields</span> </li>
<li>&nbsp;&nbsp;&nbsp; <span style="color: blue;">public</span> <span style="color: blue;">int</span> seed; </li>
<li style="background: none repeat scroll 0% 0% rgb(243, 243, 243);">&nbsp; </li>
<li>&nbsp;&nbsp;&nbsp; <span style="color: green;">// Methods</span> </li>
<li style="background: none repeat scroll 0% 0% rgb(243, 243, 243);">&nbsp;&nbsp;&nbsp; <span style="color: blue;">public</span> <span style="color: blue;">int</span> &lt;SharedClosure&gt;b__0() </li>
<li>&nbsp;&nbsp;&nbsp; { </li>
<li style="background: none repeat scroll 0% 0% rgb(243, 243, 243);">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <span style="color: blue;">return</span> ++<span style="color: blue;">this</span>.seed; </li>
<li>&nbsp;&nbsp;&nbsp; } </li>
<li style="background: none repeat scroll 0% 0% rgb(243, 243, 243);">&nbsp; </li>
<li>&nbsp;&nbsp;&nbsp; <span style="color: blue;">public</span> <span style="color: blue;">int</span> &lt;SharedClosure&gt;b__1() </li>
<li style="background: none repeat scroll 0% 0% rgb(243, 243, 243);">&nbsp;&nbsp;&nbsp; { </li>
<li>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <span style="color: blue;">return</span> &#8211;<span style="color: blue;">this</span>.seed; </li>
<li style="background: none repeat scroll 0% 0% rgb(243, 243, 243);">&nbsp;&nbsp;&nbsp; } </li>
<li>} </li>
</ol>
</div>
</div>
</div>
<p>Looking into the reflector output shows how both the Increment and Decrement functions are closed over the same environment. This can be tested by invoking the SharedClosure() as follows:</p>
<div class="wlWriterSmartContent" id="scid:9ce6104f-a9aa-4a17-a79f-3a39532ebf7c:0d4ff1ab-d7ce-46cd-aee9-0006bf7658ab" style="display: inline; float: none; margin: 0px; padding: 0px;">
<div style="border: 1px solid rgb(0, 0, 128); color: black; font-family: 'Courier New',courier,monospace; font-size: 10pt;">
<div style="background: none repeat scroll 0% 0% rgb(221, 221, 221); max-height: 300px; overflow: auto;">
<ol style="background: none repeat scroll 0% 0% rgb(255, 255, 255); margin: 0px 0px 0px 2em; padding: 0px 0px 0px 5px;">
<li><span style="color: blue;">int</span> i = 10; </li>
<li style="background: none repeat scroll 0% 0% rgb(243, 243, 243);"><span style="color: blue;">var</span> closureTuple = SharedClosure(i); </li>
<li><span style="color: #2b91af;">Console</span>.WriteLine(closureTuple.Item1()); </li>
<li style="background: none repeat scroll 0% 0% rgb(243, 243, 243);"><span style="color: #2b91af;">Console</span>.WriteLine(closureTuple.Item1()); </li>
<li><span style="color: #2b91af;">Console</span>.WriteLine(closureTuple.Item2()); </li>
<li style="background: none repeat scroll 0% 0% rgb(243, 243, 243);"><span style="color: #2b91af;">Console</span>.WriteLine(closureTuple.Item2()); </li>
</ol>
</div>
</div>
</div>
<p>The output, as expected, will be 11, 12, 11, 10. The interesting thing to note in this case is that even if the value of i is changed after the closure has been created the output will remain the same. This can be verified by changing the value of i after line 2. This is because only a copy of i was passed to the SharedClosure() method and any change in i will not impact the closure. But if the seed being passed to the SharedClosure() was a reference type, the closure will be affected by any change in the seed.</p>
<p>In conclusion, the ability to share the environment between multiple functions using closures is a very powerful feature but could also lead to some nasty side effects when handled incorrectly. In future posts, I will describe how this feature can be applied to achieve some interesting results.
<div class="blogger-post-footer"><img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/3920496645195141040-17220171920186013?l=lanshiva.blogspot.com' alt='' /></div>
]]></content:encoded>
			<wfw:commentRss>http://lanshiva.blogspot.com/2010/07/forays-into-functional-c-shared.html/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Forays into functional C# – Closures in C#</title>
		<link>http://lanshiva.blogspot.com/2010/07/forays-into-functional-c-closures-in-c.html</link>
		<comments>http://lanshiva.blogspot.com/2010/07/forays-into-functional-c-closures-in-c.html#comments</comments>
		<pubDate>Wed, 21 Jul 2010 02:00:00 +0000</pubDate>
		<dc:creator>Sivabalan Muthukumar</dc:creator>
				<category><![CDATA[.Net]]></category>
		<category><![CDATA[Functional Programming]]></category>
		<category><![CDATA[Technology]]></category>

		<guid isPermaLink="false"></guid>
		<description><![CDATA[Closures in C# have been around for a while starting with the introduction of anonymous methods in .net 2.0. But with the introduction of lambdas ( essentially a simpler way of creating anonymous methods) and the widespread proliferation of LINQ, the u...]]></description>
			<content:encoded><![CDATA[<p>Closures in C# have been around for a while starting with the introduction of anonymous methods in .net 2.0. But with the introduction of lambdas ( essentially a simpler way of creating anonymous methods) and the widespread proliferation of LINQ, the use of closures have increased a lot. For a detailed description of closures and its implementation in different languages, check out the <a href="http://en.wikipedia.org/wiki/Closure_%28computer_science%29" >wiki</a>.</p>
<p>A closure, by definition, captures the environment in which the function was created and makes it available over multiple invocation of the function. A simple example of a closure in C# is as follows:</p>
<div class="wlWriterSmartContent" id="scid:9ce6104f-a9aa-4a17-a79f-3a39532ebf7c:4c5d0af9-c4f9-4604-97ce-53c084c1e9c1" style="display: inline; float: none; margin: 0px; padding: 0px;">
<div style="border: 1px solid rgb(0, 0, 128); color: black; font-family: 'Courier New',courier,monospace; font-size: 10pt;">
<div style="background: none repeat scroll 0% 0% rgb(221, 221, 221); max-height: 300px; overflow: auto;">
<ol style="background: none repeat scroll 0% 0% rgb(255, 255, 255); margin: 0px 0px 0px 2em; padding: 0px 0px 0px 5px;">
<li><span style="color: blue;">int</span> i = 1; </li>
<li style="background: none repeat scroll 0% 0% rgb(243, 243, 243);"><span style="color: #2b91af;">Action</span> closure = () =&gt; <span style="color: #2b91af;">Console</span>.WriteLine(i); </li>
<li>i = 25; </li>
<li style="background: none repeat scroll 0% 0% rgb(243, 243, 243);">closure(); </li>
</ol>
</div>
</div>
</div>
<p>When the above snippet get executed, the value that gets printed is 25 instead of 1. In this case, the lambda is bound to a variable which is accessible outside the closure and whose value could be changed outside the closure. This is because in C#, the closure captures the reference to i and not its value. Analyzing the generated output using Reflector provides detailed insight into how closures are implemented in C#.</p>
<div class="wlWriterSmartContent" id="scid:9ce6104f-a9aa-4a17-a79f-3a39532ebf7c:3b83aa8f-32de-4c00-95c5-4cc2b8c84129" style="display: inline; float: none; margin: 0px; padding: 0px;">
<div style="border: 1px solid rgb(0, 0, 128); color: black; font-family: 'Courier New',courier,monospace; font-size: 10pt;">
<div style="background: none repeat scroll 0% 0% rgb(221, 221, 221); max-height: 300px; overflow: auto;">
<ol style="background: none repeat scroll 0% 0% rgb(255, 255, 255); margin: 0px 0px 0px 2.5em; padding: 0px 0px 0px 5px;">
<li>[CompilerGenerated] </li>
<li style="background: none repeat scroll 0% 0% rgb(243, 243, 243);"><span style="color: blue;">private</span> <span style="color: blue;">sealed</span> <span style="color: blue;">class</span> &lt;&gt;c__DisplayClass1 </li>
<li>{ </li>
<li style="background: none repeat scroll 0% 0% rgb(243, 243, 243);">&nbsp;&nbsp;&nbsp; <span style="color: green;">// Fields</span> </li>
<li>&nbsp;&nbsp;&nbsp; <span style="color: blue;">public</span> <span style="color: blue;">int</span> i; </li>
<li style="background: none repeat scroll 0% 0% rgb(243, 243, 243);">&nbsp; </li>
<li>&nbsp;&nbsp;&nbsp; <span style="color: green;">// Methods</span> </li>
<li style="background: none repeat scroll 0% 0% rgb(243, 243, 243);">&nbsp;&nbsp;&nbsp; <span style="color: blue;">public</span> <span style="color: blue;">void</span> &lt;Main&gt;b__0() </li>
<li>&nbsp;&nbsp;&nbsp; { </li>
<li style="background: none repeat scroll 0% 0% rgb(243, 243, 243);">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; Console.WriteLine(<span style="color: blue;">this</span>.i); </li>
<li>&nbsp;&nbsp;&nbsp; } </li>
<li style="background: none repeat scroll 0% 0% rgb(243, 243, 243);">} </li>
</ol>
</div>
</div>
</div>
<p>Going further and analyzing the generated output using ILDASM should give an indication how the actual value of i is getting updated.</p>
<div class="wlWriterSmartContent" id="scid:9ce6104f-a9aa-4a17-a79f-3a39532ebf7c:180da306-a4fd-4651-9375-74c9f8f557f3" style="display: inline; float: none; margin: 0px; padding: 0px;">
<div style="border: 1px solid rgb(0, 0, 128); color: black; font-family: 'Courier New',courier,monospace; font-size: 10pt;">
<div style="background: none repeat scroll 0% 0% rgb(221, 221, 221); max-height: 300px; overflow: auto;">
<ol style="background: none repeat scroll 0% 0% rgb(255, 255, 255); margin: 0px 0px 0px 2.5em; padding: 0px 0px 0px 5px;">
<li>.method <span style="color: blue;">private</span> hidebysig <span style="color: blue;">static</span> <span style="color: blue;">void</span>&nbsp; Main(<span style="color: blue;">string</span>[] args) cil managed </li>
<li style="background: none repeat scroll 0% 0% rgb(243, 243, 243);">{ </li>
<li>&nbsp; .entrypoint </li>
<li style="background: none repeat scroll 0% 0% rgb(243, 243, 243);">&nbsp; <span style="color: green;">// Code size&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; 50 (0&#215;32)</span> </li>
<li>&nbsp; .maxstack&nbsp; 3 </li>
<li style="background: none repeat scroll 0% 0% rgb(243, 243, 243);">&nbsp; .locals init ([0] <span style="color: blue;">class</span> [System.Core]System.Action closure, </li>
<li>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; [1] <span style="color: blue;">class</span> <span style="color: #2b91af;">FunctionalExtensions</span>.Core.Program/<span style="color: #a31515;">&#8216;&lt;&gt;c__DisplayClass1&#8242;</span> <span style="color: #a31515;">&#8216;CS$&lt;&gt;8__locals2&#8242;</span>) </li>
<li style="background: none repeat scroll 0% 0% rgb(243, 243, 243);">&nbsp; IL_0000:&nbsp; newobj&nbsp;&nbsp;&nbsp;&nbsp; instance <span style="color: blue;">void</span> FunctionalExtensions.Core.Program/<span style="color: #a31515;">&#8216;&lt;&gt;c__DisplayClass1&#8242;</span>::.ctor() </li>
<li>&nbsp; IL_0005:&nbsp; stloc.1 </li>
<li style="background: none repeat scroll 0% 0% rgb(243, 243, 243);">&nbsp; IL_0006:&nbsp; nop </li>
<li>&nbsp; IL_0007:&nbsp; ldloc.1 </li>
<li style="background: none repeat scroll 0% 0% rgb(243, 243, 243);">&nbsp; IL_0008:&nbsp; ldc.i4.1 </li>
<li>&nbsp; IL_0009:&nbsp; stfld&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; int32 FunctionalExtensions.Core.<span style="color: #2b91af;">Program</span>/<span style="color: #a31515;">&#8216;&lt;&gt;c__DisplayClass1&#8242;</span>::i </li>
<li style="background: none repeat scroll 0% 0% rgb(243, 243, 243);">&nbsp; IL_000e:&nbsp; ldloc.1 </li>
<li>&nbsp; IL_000f:&nbsp; ldftn&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; instance <span style="color: blue;">void</span> FunctionalExtensions.Core.Program/<span style="color: #a31515;">&#8216;&lt;&gt;c__DisplayClass1&#8242;</span>::<span style="color: #a31515;">&#8216;&lt;Main&gt;b__0&#8242;</span>() </li>
<li style="background: none repeat scroll 0% 0% rgb(243, 243, 243);">&nbsp; IL_0015:&nbsp; newobj&nbsp;&nbsp;&nbsp;&nbsp; instance <span style="color: blue;">void</span> [System.Core]System.<span style="color: #2b91af;">Action</span>::.ctor(<span style="color: blue;">object</span>, </li>
<li>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; native <span style="color: blue;">int</span>) </li>
<li style="background: none repeat scroll 0% 0% rgb(243, 243, 243);">&nbsp; IL_001a:&nbsp; stloc.0 </li>
<li>&nbsp; IL_001b:&nbsp; ldloc.1 </li>
<li style="background: none repeat scroll 0% 0% rgb(243, 243, 243);">&nbsp; IL_001c:&nbsp; ldc.i4.s&nbsp;&nbsp; 25 </li>
<li>&nbsp; IL_001e:&nbsp; stfld&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; int32 FunctionalExtensions.Core.<span style="color: #2b91af;">Program</span>/<span style="color: #a31515;">&#8216;&lt;&gt;c__DisplayClass1&#8242;</span>::i </li>
<li style="background: none repeat scroll 0% 0% rgb(243, 243, 243);">&nbsp; IL_0023:&nbsp; ldloc.0 </li>
<li>&nbsp; IL_0024:&nbsp; callvirt&nbsp;&nbsp; instance <span style="color: blue;">void</span> [System.Core]System.<span style="color: #2b91af;">Action</span>::Invoke() </li>
<li style="background: none repeat scroll 0% 0% rgb(243, 243, 243);">&nbsp; IL_0029:&nbsp; nop </li>
<li>&nbsp; IL_002a:&nbsp; call&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; valuetype [mscorlib]System.<span style="color: #2b91af;">ConsoleKeyInfo</span> [mscorlib]System.<span style="color: #2b91af;">Console</span>::ReadKey() </li>
<li style="background: none repeat scroll 0% 0% rgb(243, 243, 243);">&nbsp; IL_002f:&nbsp; pop </li>
<li>&nbsp; IL_0030:&nbsp; nop </li>
<li style="background: none repeat scroll 0% 0% rgb(243, 243, 243);">&nbsp; IL_0031:&nbsp; ret </li>
<li>} <span style="color: green;">// end of method Program::Main</span> </li>
</ol>
</div>
</div>
</div>
<p>Looking at line numbers 13 and 21 shows how the value of i is updated resulting in an output of 25 when the action is invoked.
<div class="blogger-post-footer"><img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/3920496645195141040-6307303944077908307?l=lanshiva.blogspot.com' alt='' /></div>
]]></content:encoded>
			<wfw:commentRss>http://lanshiva.blogspot.com/2010/07/forays-into-functional-c-closures-in-c.html/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Tabbles file organizer – &#8220;what WinFS should have been&#8221;</title>
		<link>http://feedproxy.google.com/~r/DevelopmentInABlink/~3/2GeqgccV0ic/</link>
		<comments>http://feedproxy.google.com/~r/DevelopmentInABlink/~3/2GeqgccV0ic/#comments</comments>
		<pubDate>Thu, 08 Jul 2010 02:15:59 +0000</pubDate>
		<dc:creator>Doug Finke</dc:creator>
				<category><![CDATA[Functional Programming]]></category>

		<guid isPermaLink="false">http://dougfinke.com/blog/index.php/2010/07/07/tabbles-file-organizer-what-winfs-should-have-been-3/</guid>
		<description><![CDATA[ 
Written mostly in F# via Don Syme
]]></description>
			<content:encoded><![CDATA[<p><a href="http://www.tabbles.net"><img style="border-bottom: 0px; border-left: 0px; display: inline; border-top: 0px; border-right: 0px" title="image" border="0" alt="image" src="http://dougfinke.com/blog/wp-content/uploads/2010/07/image.png" width="244" height="81" /></a> </p>
<p>Written mostly in F# via <a href="http://bit.ly/9ewwao">Don Syme</a></p>
<p><img src="http://feeds.feedburner.com/~r/DevelopmentInABlink/~4/2GeqgccV0ic" height="1" width="1"/></p>
]]></content:encoded>
			<wfw:commentRss>http://feedproxy.google.com/~r/DevelopmentInABlink/~3/2GeqgccV0ic/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>PowerShell is executable XML with a friendlier syntax</title>
		<link>http://feedproxy.google.com/~r/DevelopmentInABlink/~3/cwVGXS6GdBw/</link>
		<comments>http://feedproxy.google.com/~r/DevelopmentInABlink/~3/cwVGXS6GdBw/#comments</comments>
		<pubDate>Sat, 03 Jul 2010 13:54:23 +0000</pubDate>
		<dc:creator>Doug Finke</dc:creator>
				<category><![CDATA[Functional Programming]]></category>
		<category><![CDATA[PowerShell]]></category>

		<guid isPermaLink="false">http://dougfinke.com/blog/index.php/2010/07/03/powershell-is-executable-xml-with-a-friendlier-syntax/</guid>
		<description><![CDATA[This post presents a metaprogramming technique in PowerShell inspired by XML . After reading about Lisp, I started thinking how PowerShell could do similar things.
A&#160; Todo-List in XML
XML is really just a tree serialized to a human readable form. Another way to express that is, XML is a way to store information in a hierarchical [...]]]></description>
			<content:encoded><![CDATA[<p>This post presents a <a href="http://en.wikipedia.org/wiki/Metaprogramming">metaprogramming</a> technique in PowerShell inspired by XML . After <a href="http://www.defmacro.org/ramblings/lisp.html">reading about Lisp</a>, I started thinking how PowerShell could do similar things.</p>
<h3>A&#160; Todo-List in XML</h3>
<p>XML is really just a tree serialized to a human readable form. Another way to express that is, XML is a way to store information in a hierarchical form.</p>
<pre style="width: 524px; height: 121px" class="PowerShellColorizedScript"><span style="color: #a9a9a9">&lt;</span><span style="color: #8a2be2">todo</span> <span style="color: #8a2be2">name=&quot;housework&quot;&gt;</span>
    <span style="color: #a9a9a9">&lt;</span><span style="color: #8a2be2">task</span> <span style="color: #8a2be2">priority=&quot;high&quot;&gt;Clean</span> <span style="color: #8a2be2">the</span> <span style="color: #8a2be2">house.</task></span>
    <span style="color: #a9a9a9">&lt;</span><span style="color: #8a2be2">task</span> <span style="color: #8a2be2">priority=&quot;medium&quot;&gt;Wash</span> <span style="color: #8a2be2">the</span> <span style="color: #8a2be2">dishes.</task></span>
    <span style="color: #a9a9a9">&lt;</span><span style="color: #8a2be2">task</span> <span style="color: #8a2be2">priority=&quot;medium&quot;&gt;Buy</span> <span style="color: #8a2be2">more</span> <span style="color: #8a2be2">soap.</task></span>
<span style="color: #a9a9a9">&lt;</span><span style="color: #8a2be2">/todo&gt;</span>            </pre>
<h3>Parsing XML in PowerShell</h3>
<p>Here we use PowerShell’s accelerator<font color="#008080"> [xml]</font> with a here-string to create an XmlDocument. In the end we use dot notation to print out the tasks.</p>
<pre class="PowerShellColorizedScript"><span style="color: #ff4500">$xml</span> <span style="color: #a9a9a9">=</span> <span style="color: #008080">[xml]</span> <span style="color: #8b0000">@&quot;
&lt;todo name=&quot;housework&quot;&gt;
    &lt;task priority=&quot;high&quot;&gt;Clean the house.
    &lt;task priority=&quot;medium&quot;&gt;Wash the dishes.
    &lt;task priority=&quot;medium&quot;&gt;Buy more soap.
&lt;/todo&gt;
&quot;@</span>                        

<span style="color: #ff4500">$xml</span><span style="color: #a9a9a9">.</span><span style="color: #000000">todo</span><span style="color: #a9a9a9">.</span><span style="color: #000000">task</span>            

<span style="color: #006400"># Results</span>
<span style="color: #8b0000">priority #text
-------- -----
high     Clean the house.
medium   Wash the dishes.
medium   Buy more soap.
</span></pre>
<h3>Corresponding PowerShell Version</h3>
<p>Looks like this with the supporting PowerShell function described below.</p>
<pre class="PowerShellColorizedScript"><span style="color: #0000ff">New-TodoList</span> <span style="color: #8b0000">&quot;housework&quot;</span> <span style="color: #000000">{</span>
    <span style="color: #0000ff">New-Task</span> <span style="color: #8a2be2">high</span> <span style="color: #8b0000">&quot;Clean the house.&quot;</span>
    <span style="color: #0000ff">New-Task</span> <span style="color: #8a2be2">medium</span> <span style="color: #8b0000">&quot;Wash the dishes.&quot;</span>
    <span style="color: #0000ff">New-Task</span> <span style="color: #8a2be2">medium</span> <span style="color: #8b0000">&quot;Buy more soap.&quot;</span>
<span style="color: #000000">}</span></pre>
<h3>How To Make It Executable</h3>
<blockquote>
<p><a href="http://en.wikipedia.org/wiki/Metaprogramming">Metaprogramming</a> is the term used to describe the activity of writing programs that create or manipulate other programs.</p>
<p>PowerShell scriptblocks are at the center of most of the metaprogramming techniques.</p>
<p>– <a href="http://www.manning.com/payette2/">“PowerShell In Action”</a></p>
</blockquote>
<p>The PowerShell function <em><strong>New-TodoList</strong></em> takes a scriptblock as one of its parameters. We use the call operator “&amp;” to invoke the scriptblock passed in the $code parameter. The <em><strong>New-Task</strong></em> function creates and returns a PSObject with three properties Name, Priority and Task. </p>
<p><strong>Note</strong>: The inner function is able to “see” the $name variable in the outer functions parameter list.</p>
<pre class="PowerShellColorizedScript"><span style="color: #00008b">Function</span> <span style="color: #8a2be2">New-TodoList</span> <span style="color: #000000">(</span><span style="color: #ff4500">$name</span><span style="color: #a9a9a9">,</span> <span style="color: #008080">[ScriptBlock]</span> <span style="color: #ff4500">$code</span><span style="color: #000000">)</span> <span style="color: #000000">{</span>            

    <span style="color: #00008b">Function</span> <span style="color: #8a2be2">New-Task</span> <span style="color: #000000">(</span><span style="color: #ff4500">$priority</span><span style="color: #a9a9a9">,</span> <span style="color: #ff4500">$task</span><span style="color: #000000">)</span> <span style="color: #000000">{</span>
        <span style="color: #0000ff">New-Object</span> <span style="color: #8a2be2">PSObject</span> <span style="color: #000080">-Property</span> <span style="color: #000000">@{</span>
            <span style="color: #000000">Name</span>     <span style="color: #a9a9a9">=</span> <span style="color: #ff4500">$name</span>
            <span style="color: #000000">Priority</span> <span style="color: #a9a9a9">=</span> <span style="color: #ff4500">$priority</span>
            <span style="color: #000000">Task</span>     <span style="color: #a9a9a9">=</span> <span style="color: #ff4500">$task</span>
        <span style="color: #000000">}</span>
    <span style="color: #000000">}</span>            

    <span style="color: #a9a9a9">&amp;</span> <span style="color: #ff4500">$code</span>
<span style="color: #000000">}</span></pre>
<h3>Putting It Together</h3>
<p>You can look at this in few ways. We have used PowerShell and scriptblocks to construct a macro/domain specific language (DSL) to transform our Todo-List data. </p>
<pre class="PowerShellColorizedScript">

<span style="color: #0000ff">New-TodoList</span> <span style="color: #8b0000">&quot;housework&quot;</span> <span style="color: #000000">{</span>
    <span style="color: #0000ff">New-Task</span> <span style="color: #8a2be2">high</span> <span style="color: #8b0000">&quot;Clean the house.&quot;</span>
    <span style="color: #0000ff">New-Task</span> <span style="color: #8a2be2">medium</span> <span style="color: #8b0000">&quot;Wash the dishes.&quot;</span>
    <span style="color: #0000ff">New-Task</span> <span style="color: #8a2be2">medium</span> <span style="color: #8b0000">&quot;Buy more soap.&quot;</span>
<span style="color: #000000">}</span>            

<span style="color: #8b0000">
Name      Priority Task
----      -------- ----
housework high     Clean the house.
housework medium   Wash the dishes.
housework medium   Buy more soap.
</span>

<span style="color: #8b0000"></span>&#160;
</pre>
<p>The PowerShell functions here demonstrate one way to generate output. This example chose to present the data as an array of PSObjects. The data emitted could take .many shapes, for example nested hash tables.</p>
<h3>The POWER You Get That You Can’t Get With XML</h3>
<p>Jeffrey Snover, creator of PowerShell, pointed out this key aspect. By using PowerShell scriptblocks in our little language, it gives us the full power of PowerShell so we can do following, something we can’t get with XML.</p>
<pre style="width: 559px; height: 466px" class="PowerShellColorizedScript"><span style="color: #0000ff">New-TodoList</span> <span style="color: #8b0000">&quot;housework&quot;</span> <span style="color: #000000">{</span>
    <span style="color: #0000ff">New-Task</span> <span style="color: #8a2be2">high</span> <span style="color: #8b0000">&quot;Clean the house.&quot;</span>
    <span style="color: #0000ff">New-Task</span> <span style="color: #8a2be2">medium</span> <span style="color: #8b0000">&quot;Wash the dishes.&quot;</span>
    <span style="color: #0000ff">New-Task</span> <span style="color: #8a2be2">medium</span> <span style="color: #8b0000">&quot;Buy more soap.&quot;</span>            

    <span style="color: #00008b">ForEach</span> <span style="color: #000000">(</span><span style="color: #ff4500">$item</span> <span style="color: #00008b">in</span> <span style="color: #8b0000">“Soap”</span><span style="color: #a9a9a9">,</span><span style="color: #8b0000">”Beer”</span><span style="color: #a9a9a9">,</span><span style="color: #8b0000">”Doritos”</span><span style="color: #a9a9a9">,</span><span style="color: #8b0000">”Salsa”</span><span style="color: #a9a9a9">,</span><span style="color: #8b0000">”Microsoft Stock”</span><span style="color: #000000">)</span> <span style="color: #000000">{</span>
        <span style="color: #0000ff">New-Task</span> <span style="color: #8a2be2">medium</span> <span style="color: #8b0000">“Buy more $item.”</span>
    <span style="color: #000000">}</span>            

<span style="color: #000000">}</span>            

<span style="color: #006400"># Results</span>
<span style="color: #8b0000">Name      Priority Task
----      -------- ----
housework high     Clean the house.
housework medium   Wash the dishes.
housework medium   Buy more soap.
housework medium   Buy more Soap.
housework medium   Buy more Beer.
housework medium   Buy more Doritos.
housework medium   Buy more Salsa.
housework medium   Buy more Microsoft Stock.</span></pre>
<h3>Quick Summary</h3>
<p>XML has been used for a long time to create DSLs. A couple examples are ANT and NAnt which are specific to building projects.</p>
<p>Using DSLs to solve problems results in much more compact, maintainable, flexible programs. PowerShell helps take this abstraction further. Compare writing NAnt in pure C# and not using XML.</p>
<h3>Additional Reading</h3>
<p><a href="http://www.defmacro.org/ramblings/lisp.html">“The Nature of Lisp</a>” &#8211; Slava Akhmechet <a href="http://www.defmacro.org/">http://www.defmacro.org/</a></p>
<p><img src="http://feeds.feedburner.com/~r/DevelopmentInABlink/~4/cwVGXS6GdBw" height="1" width="1"/></p>
]]></content:encoded>
			<wfw:commentRss>http://feedproxy.google.com/~r/DevelopmentInABlink/~3/cwVGXS6GdBw/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Accessing Visual Studio’s Automation API From PowerShell</title>
		<link>http://feedproxy.google.com/~r/DevelopmentInABlink/~3/MBtqeQ5Ub78/</link>
		<comments>http://feedproxy.google.com/~r/DevelopmentInABlink/~3/MBtqeQ5Ub78/#comments</comments>
		<pubDate>Sun, 16 May 2010 18:44:25 +0000</pubDate>
		<dc:creator>Doug Finke</dc:creator>
				<category><![CDATA[Functional Programming]]></category>
		<category><![CDATA[PowerShell]]></category>

		<guid isPermaLink="false">http://dougfinke.com/blog/index.php/2010/05/16/accessing-visual-studios-automation-api-from-powershell/</guid>
		<description><![CDATA[Kurt Schelfthout blogs Accessing Visual Studio’s Automation API from F# Interactive and reasons: 
Because why anyone would want to write VBA in the Visual Studio macro editor is beyond me.

I agree!
Kurt lays out&#160; the “how to” for injecting the Visual Studio’s DTE object (Development Tools Extensibility) into the F# console. He also provides the link [...]]]></description>
			<content:encoded><![CDATA[<p>Kurt Schelfthout blogs <a href="http://fortysix-and-two.blogspot.com/2010/05/accessing-visual-studios-automation-api.html">Accessing Visual Studio’s Automation API from F# Interactive</a> and reasons: </p>
<blockquote><p>Because why anyone would want to write VBA in the Visual Studio macro editor is beyond me<font color="#111111">.</font></p>
</blockquote>
<p>I agree!</p>
<p>Kurt lays out&#160; the “how to” for injecting the Visual Studio’s DTE object (Development Tools Extensibility) into the F# console. He also provides the link to <a href="http://msdn.microsoft.com/en-us/library/za2b25t3(v=VS.71).aspx">Visual Studio .NET Automation Object Model</a>.</p>
<h3>PowerShell PowerConsole</h3>
<p>Makes accessing the Automation API simple. It brings the Visual Studio DTE automation object to your finger tips. Check this post for downloading <a href="http://dougfinke.com/blog/index.php/2010/03/14/powerconsole-powershell-integrated-with-visual-studio-2010/">PowerConsole &#8211; PowerShell Integrated with Visual Studio 2010</a>. </p>
<h3>$DTE.Solution.Projects | ForEach {$_.Fullname}</h3>
<div style="border-bottom: silver 1px solid; text-align: left; border-left: silver 1px solid; padding-bottom: 4px; line-height: 12pt; background-color: #f4f4f4; margin: 20px 0px 10px; padding-left: 4px; width: 97.5%; padding-right: 4px; font-family: &#39;Courier New&#39;, courier, monospace; direction: ltr; max-height: 200px; font-size: 8pt; overflow: auto; border-top: silver 1px solid; cursor: text; border-right: silver 1px solid; padding-top: 4px" id="codeSnippetWrapper">
<div style="border-bottom-style: none; text-align: left; padding-bottom: 0px; line-height: 12pt; border-right-style: none; background-color: #f4f4f4; padding-left: 0px; width: 100%; padding-right: 0px; font-family: &#39;Courier New&#39;, courier, monospace; direction: ltr; border-top-style: none; color: black; font-size: 8pt; border-left-style: none; overflow: visible; padding-top: 0px" id="codeSnippet">
<pre style="border-bottom-style: none; text-align: left; padding-bottom: 0px; line-height: 12pt; border-right-style: none; background-color: white; margin: 0em; padding-left: 0px; width: 100%; padding-right: 0px; font-family: &#39;Courier New&#39;, courier, monospace; direction: ltr; border-top-style: none; color: black; font-size: 8pt; border-left-style: none; overflow: visible; padding-top: 0px">PS&gt; $DTE.Solution.Projects | ForEach {$_.Fullname}</pre>
<p><!--CRLF--></p>
<pre style="border-bottom-style: none; text-align: left; padding-bottom: 0px; line-height: 12pt; border-right-style: none; background-color: #f4f4f4; margin: 0em; padding-left: 0px; width: 100%; padding-right: 0px; font-family: &#39;Courier New&#39;, courier, monospace; direction: ltr; border-top-style: none; color: black; font-size: 8pt; border-left-style: none; overflow: visible; padding-top: 0px">C:\PoShScripts\NYC Code Camp\CSharp\WPF+PoSh\Simple\Simple.csproj</pre>
<p><!--CRLF--></p>
<pre style="border-bottom-style: none; text-align: left; padding-bottom: 0px; line-height: 12pt; border-right-style: none; background-color: white; margin: 0em; padding-left: 0px; width: 100%; padding-right: 0px; font-family: &#39;Courier New&#39;, courier, monospace; direction: ltr; border-top-style: none; color: black; font-size: 8pt; border-left-style: none; overflow: visible; padding-top: 0px">C:\PoShScripts\NYC Code Camp\CSharp\WPF+PoSh\PowerShellExtensions\PowerShellExtensions.csproj</pre>
<p><!--CRLF--></p>
<pre style="border-bottom-style: none; text-align: left; padding-bottom: 0px; line-height: 12pt; border-right-style: none; background-color: #f4f4f4; margin: 0em; padding-left: 0px; width: 100%; padding-right: 0px; font-family: &#39;Courier New&#39;, courier, monospace; direction: ltr; border-top-style: none; color: black; font-size: 8pt; border-left-style: none; overflow: visible; padding-top: 0px">C:\PoShScripts\NYC Code Camp\CSharp\WPF+PoSh\HostAndAddVariables\HostAndAddVariables.csproj</pre>
<p><!--CRLF--></div>
</div>
<p><img src="http://feeds.feedburner.com/~r/DevelopmentInABlink/~4/MBtqeQ5Ub78" height="1" width="1"/></p>
]]></content:encoded>
			<wfw:commentRss>http://feedproxy.google.com/~r/DevelopmentInABlink/~3/MBtqeQ5Ub78/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>How to add an F# type to a PowerShell session</title>
		<link>http://feedproxy.google.com/~r/DevelopmentInABlink/~3/GOvkzWUX-W8/</link>
		<comments>http://feedproxy.google.com/~r/DevelopmentInABlink/~3/GOvkzWUX-W8/#comments</comments>
		<pubDate>Sun, 18 Apr 2010 20:18:27 +0000</pubDate>
		<dc:creator>Doug Finke</dc:creator>
				<category><![CDATA[.Net]]></category>
		<category><![CDATA[Functional Programming]]></category>
		<category><![CDATA[PowerShell]]></category>

		<guid isPermaLink="false">http://dougfinke.com/blog/index.php/2010/04/18/how-to-add-an-f-type-to-a-powershell-session/</guid>
		<description><![CDATA[The PowerShell Add-Type cmdlet lets you define a .NET Framework class in your Windows PowerShell session. It supports the following languages CSharp, CSharpVersion3, VisualBasic, JScript. It does not support FSharp directly.
No problem
Add-Type has a parameter CodeDomProvider and you can pass the FSharpCodeProvider to it (see the function Add-TypeFSharp).
Add-TypeFSharp lets you inline F# code. 
Add-TypeFSharp -TypeDefinition [...]]]></description>
			<content:encoded><![CDATA[<p>The PowerShell <em><strong>Add-Type</strong></em> cmdlet lets you define a .NET Framework class in your Windows PowerShell session. It supports the following languages CSharp, CSharpVersion3, VisualBasic, JScript. It does not support FSharp directly.</p>
<h3>No problem</h3>
<p>Add-Type has a parameter CodeDomProvider and you can pass the FSharpCodeProvider to it (see the function Add-TypeFSharp).</p>
<p>Add-TypeFSharp lets you inline F# code. </p>
<pre class="PowerShellColorizedScript"><span style="color: #0000ff">Add-TypeFSharp</span> <span style="color: #000080">-TypeDefinition</span> <span style="color: #8b0000">@&quot;
module MyModule

let Add a b = a + b;;
&quot;@</span>            

<span style="color: #800080">1</span><span style="color: #a9a9a9">..</span><span style="color: #800080">10</span> <span style="color: #a9a9a9">|</span> <span style="color: #0000ff">%</span> <span style="color: #000000">{</span> <span style="color: #008080">[MyModule]</span><span style="color: #a9a9a9">::</span><span style="color: #000000">Add</span><span style="color: #000000">(</span> <span style="color: #ff4500">$_</span><span style="color: #a9a9a9">,</span> <span style="color: #ff4500">$_</span><span style="color: #a9a9a9">*</span><span style="color: #800080">2</span> <span style="color: #000000">)</span> <span style="color: #000000">}</span></pre>
<p>&#160;<a href="http://dougfinke.com/uploadPictures/HowtoaddanFtypetoaPowerShellsession_D9E2/image.png"><img style="border-right-width: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px" title="image" border="0" alt="image" src="http://dougfinke.com/uploadPictures/HowtoaddanFtypetoaPowerShellsession_D9E2/image_thumb.png" width="558" height="263" /></a> </p>
<h3>Things TODO</h3>
<ul>
<li>Install .NET 4.0, VS 2010 installs this and the latest F# bits </li>
<li>Download and install <a href="http://fsharppowerpack.codeplex.com/">The F# PowerPack</a> </li>
<li>Update the registry so PowerShell can work with .NET 4.0 </li>
</ul>
<h4>Updating the registry</h4>
<p>This is a bit tricky, thanks to the help of the <a href="https://mvp.support.microsoft.com/communities/mvp.aspx?product=1&amp;competency=PowerShell&amp;page=1">PowerShell MVP community</a> (<a href="http://blogs.microsoft.co.il/blogs/ScriptFanatic/">Shay</a>, <a href="http://www.nivot.org/">Oisín</a>, <a href="http://marcoshaw.blogspot.com/">Marco</a> and <a href="https://mvp.support.microsoft.com/profile=6D90E2F1-24FE-4818-9FB3-D1B4F336C887">Vadims</a>)on getting this to work. </p>
<p>Before you are allowed to edit this entry, you need to change the permissions on that key and take full ownership.</p>
<p>Then change the <em><strong>RuntimeVersion</strong></em> value, under the following key, to <strong>v4.0.30319</strong>.</p>
<p><font size="2" face="Courier New">HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\PowerShell\1\PowerShellEngine</font></p>
<h3>Function Add-TypeFSharp</h3>
<pre class="PowerShellColorizedScript"><span style="color: #00008b">Function</span> <span style="color: #8a2be2">Add-TypeFSharp</span> <span style="color: #000000">{</span>
    <span style="color: #00008b">param</span><span style="color: #000000">(</span>
        <span style="color: #008080">[string]</span><span style="color: #ff4500">$TypeDefinition</span>
    <span style="color: #000000">)</span>            

    <span style="color: #0000ff">Add-Type</span> <span style="color: #000080">-Path</span> <span style="color: #000000">`
</span>        <span style="color: #8b0000">&quot;C:\Program Files\FSharpPowerPack-1.9.9.9\bin\FSharp.Compiler.CodeDom.dll&quot;</span>            

    <span style="color: #ff4500">$provider</span> <span style="color: #a9a9a9">=</span> <span style="color: #0000ff">New-Object</span> <span style="color: #000000">`
</span>        <span style="color: #8a2be2">Microsoft.FSharp.Compiler.CodeDom.FSharpCodeProvider</span>            

    <span style="color: #0000ff">Add-Type</span> <span style="color: #000080">-TypeDefinition</span> <span style="color: #ff4500">$TypeDefinition</span> <span style="color: #000080">-CodeDomProvider</span> <span style="color: #ff4500">$provider</span>
<span style="color: #000000">}</span></pre>
<h3>Notes</h3>
<ul>
<li>Investigate using a PowerShell Proxy command for Add-Type and extend the Language parameter </li>
<li>Enhance Add-TypeFSharp to take an F# file in addition to a string </li>
</ul>
<p><img src="http://feeds.feedburner.com/~r/DevelopmentInABlink/~4/GOvkzWUX-W8" height="1" width="1"/></p>
]]></content:encoded>
			<wfw:commentRss>http://feedproxy.google.com/~r/DevelopmentInABlink/~3/GOvkzWUX-W8/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>PowerShell and F# Consoles in Visual Studio 2010</title>
		<link>http://feedproxy.google.com/~r/DevelopmentInABlink/~3/I3TugzRefS0/</link>
		<comments>http://feedproxy.google.com/~r/DevelopmentInABlink/~3/I3TugzRefS0/#comments</comments>
		<pubDate>Sat, 03 Apr 2010 01:36:27 +0000</pubDate>
		<dc:creator>Doug Finke</dc:creator>
				<category><![CDATA[Functional Programming]]></category>
		<category><![CDATA[PowerShell]]></category>

		<guid isPermaLink="false">http://dougfinke.com/blog/index.php/2010/04/02/powershell-and-f-consoles-in-visual-studio-2010/</guid>
		<description><![CDATA[Who would have thought?
The PowerConsole also supports IronPython and IronRuby.



]]></description>
			<content:encoded><![CDATA[<p>Who would have thought?</p>
<p>The <a href="http://visualstudiogallery.msdn.microsoft.com/en-us/67620d8c-93dd-4e57-aa86-c9404acbd7b3">PowerConsole</a> also supports <a href="http://visualstudiogallery.msdn.microsoft.com/en-us/777407db-348b-4ac6-8106-ce4da1bd3bd2">IronPython and IronRuby</a>.</p>
</p>
<p><a href="http://dougfinke.com/uploadPictures/Whowouldhavethought_12E88/image.png"><img style="border-right-width: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px" title="image" border="0" alt="image" src="http://dougfinke.com/uploadPictures/Whowouldhavethought_12E88/image_thumb.png" width="570" height="119" /></a></p>
<p><img src="http://feeds.feedburner.com/~r/DevelopmentInABlink/~4/I3TugzRefS0" height="1" width="1"/></p>
]]></content:encoded>
			<wfw:commentRss>http://feedproxy.google.com/~r/DevelopmentInABlink/~3/I3TugzRefS0/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Programming Windows Azure</title>
		<link>http://feedproxy.google.com/~r/DevelopmentInABlink/~3/CrGMChNeSHI/</link>
		<comments>http://feedproxy.google.com/~r/DevelopmentInABlink/~3/CrGMChNeSHI/#comments</comments>
		<pubDate>Thu, 31 Dec 2009 02:38:30 +0000</pubDate>
		<dc:creator>Doug Finke</dc:creator>
				<category><![CDATA[Functional Programming]]></category>
		<category><![CDATA[Python]]></category>

		<guid isPermaLink="false">http://dougfinke.com/blog/index.php/2009/12/30/programming-windows-azure/</guid>
		<description><![CDATA[Available for pre-order. The author, Sriram Krishnan, has a blog. Plus he has posted Erlang and Python bindings for the Windows Azure storage API.
It’s not often that you get to spearhead the creation of a major new Microsoft API and it feels great to have seen this through from beginning to end

]]></description>
			<content:encoded><![CDATA[<p>Available for <a href="http://www.amazon.com/Programming-Windows-Azure-Krishnan-Sriram/dp/0596801971">pre-order</a>. The author, Sriram Krishnan, <a href="http://www.sriramkrishnan.com/blog/">has a blog</a>. Plus he has posted <a href="http://github.com/sriramk/winazureerl/tree/master">Erlang</a> and <a href="http://github.com/sriramk/winazurestorage/tree/master">Python</a> bindings for the Windows Azure storage API.</p>
<blockquote><p>It’s not often that you get to spearhead the creation of a major new Microsoft API and it feels great to have seen this through from beginning to end</p>
</blockquote>
<p><img src="http://feeds.feedburner.com/~r/DevelopmentInABlink/~4/CrGMChNeSHI" height="1" width="1"/></p>
]]></content:encoded>
			<wfw:commentRss>http://feedproxy.google.com/~r/DevelopmentInABlink/~3/CrGMChNeSHI/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Functional Homework</title>
		<link>http://goldmanalpha.wordpress.com/2009/12/26/functional-homework/</link>
		<comments>http://goldmanalpha.wordpress.com/2009/12/26/functional-homework/#comments</comments>
		<pubDate>Sat, 26 Dec 2009 01:34:38 +0000</pubDate>
		<dc:creator>Aaron Goldman</dc:creator>
				<category><![CDATA[.Net]]></category>
		<category><![CDATA[Functional Programming]]></category>
		<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false">http://goldmanalpha.wordpress.com/?p=347</guid>
		<description><![CDATA[As I mentioned last month, I want to learn a functional programming language.  Lucky for me, Dr. Erik Meijer (and his electric t-shirt) gave a course on Haskell in October and its posted on Channel 9.
I watched the first lecture over a week ago but haven’t had time to do the homework till now.
Here it [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=goldmanalpha.wordpress.com&#38;blog=9682964&#38;post=347&#38;subd=goldmanalpha&#38;ref=&#38;feed=1" />]]></description>
			<content:encoded><![CDATA[<div class='snap_preview'>
<p><a href="http://channel9.msdn.com/shows/Going+Deep/Lecture-Series-Erik-Meijer-Functional-Programming-Fundamentals-Chapter-1/" ><img style="display:inline;margin-left:0;margin-right:0;border-width:0;" title="MejerTShirt" src="http://goldmanalpha.files.wordpress.com/2009/12/mejertshirt.jpg?w=244&#038;h=237" border="0" alt="MejerTShirt" width="244" height="237" align="right" /></a>As I <a href="http://goldmanalpha.wordpress.com/2009/11/13/functionallanguage/" >mentioned last month,</a> I want to learn a functional programming language.  Lucky for me, Dr. Erik Meijer (and his electric t-shirt) gave a <a href="http://channel9.msdn.com/shows/Going+Deep/Lecture-Series-Erik-Meijer-Functional-Programming-Fundamentals-Chapter-1/" >course on Haskell</a> in October and its posted on Channel 9.</p>
<p>I watched the first lecture over a week ago but haven’t had time to do the homework till now.</p>
<p>Here it is in C#.  Its quicksort written as he described it in Haskell.  It doesn’t feel that different from the programming I usually do, but it is recursive (which I generally avoid), so maybe that’s something.  At least I did my homework, now I can go on to the second lecture <img src='http://s.wordpress.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> .</p>
<p>As long as I was making a program, I figured I’d expand my WPF horizons and used an attached behavior for the button.  Of course its MVVM which is just a habit now.</p>
<h3>Attached Behaviors</h3>
<p>It wasn&#8217;t obvious how to link the static attached behavior to the instance properly.</p>
<p>A guy on <a href="http://stackoverflow.com/questions/870137/wpf-how-to-attach-mouse-events-to-a-viewmodel" >StackOverflow</a> recommended getting the DataContext from the sender in the event:</p>
<div style="font-family:courier new;background:white;color:black;font-size:10pt;">
<p style="margin:0;"><span style="color:blue;">private</span> <span style="color:blue;">static</span> <span style="color:blue;">void</span> ButtonOnClick(<span style="color:blue;">object</span> sender, <span style="color:#2b91af;">RoutedEventArgs</span> args)<br />
{</p>
</div>
<blockquote>
<div style="font-family:courier new;background:white;color:black;font-size:10pt;">
<p style="margin:0;"><span style="color:blue;">var</span> fxElem = sender <span style="color:blue;">as</span> <span style="color:#2b91af;">FrameworkElement</span>;</p>
<p style="margin:0;"><span style="color:blue;">var</span> vm = (<span style="color:#2b91af;">VM</span>) ((<span style="color:#2b91af;">FrameworkElement</span>)args.OriginalSource).DataContext;</p>
</div>
</blockquote>
<p>Most other explanations of attached behaviors are limited to working with the control itself and not the ViewModel:</p>
<p><a title="http://eladm.wordpress.com/2009/04/02/attached-behavior/" href="http://eladm.wordpress.com/2009/04/02/attached-behavior/">http://eladm.wordpress.com/2009/04/02/attached-behavior/</a><br />
<a title="http://www.codeproject.com/KB/WPF/AttachedBehaviors.aspx" href="http://www.codeproject.com/KB/WPF/AttachedBehaviors.aspx">http://www.codeproject.com/KB/WPF/AttachedBehaviors.aspx</a></p>
<p>You can <a href="http://cid-ad623ebb35a7dabd.skydrive.live.com/self.aspx/.Public/BlogCode/FunctionalProgrammingHW1.zip" >download the code here</a>.</p>
<p><a href="http://goldmanalpha.files.wordpress.com/2009/12/image9.png"><img style="display:inline;border:0;" title="image" src="http://goldmanalpha.files.wordpress.com/2009/12/image_thumb4.png?w=244&#038;h=107" border="0" alt="image" width="244" height="107" /></a></p>
<h3>Here’s the homework code:</h3>
<div style="font-family:courier new;background:white;color:black;font-size:10pt;">
<pre style="margin:0;"><span style="color:blue;">public</span>  <span style="color:#2b91af;">IEnumerable</span>&lt;<span style="color:#2b91af;">IComparable</span>&gt;
</pre>
<pre style="margin:0;">    Sort(<span style="color:#2b91af;">IEnumerable</span>&lt;<span style="color:#2b91af;">IComparable</span>&gt; listToSort)</pre>
<pre style="margin:0;">{</pre>
<pre style="margin:0;">    <span style="color:blue;">if</span> (listToSort == <span style="color:blue;">null</span>)</pre>
<pre style="margin:0;">        <span style="color:blue;">throw</span> <span style="color:blue;">new</span> <span style="color:#2b91af;">InvalidOperationException</span></pre>
<pre style="margin:0;">            (<span style="color:#a31515;">"Cannot sort a null list."</span>);</pre>
<pre style="margin:0;">    <span style="color:blue;">if</span> (listToSort.Count() == 0)</pre>
<pre style="margin:0;">        <span style="color:blue;">return</span> listToSort;</pre>
<pre style="margin:0;">    <span style="color:blue;">var</span> result = <span style="color:blue;">new</span> <span style="color:#2b91af;">List</span>&lt;<span style="color:#2b91af;">IComparable</span>&gt;();</pre>
<pre style="margin:0;">    <span style="color:blue;">var</span> start = listToSort.First();</pre>
<pre style="margin:0;">    <span style="color:green;">//smaller on left</span></pre>
<pre style="margin:0;">    result.AddRange(Sort(listToSort.Skip(1)</pre>
<pre style="margin:0;">        .Where(e =&gt; e.CompareTo(start) &lt;= 0)));</pre>
<pre style="margin:0;">    <span style="color:green;">//val in middle</span></pre>
<pre style="margin:0;">    result.Add(start);</pre>
<pre style="margin:0;">    <span style="color:green;">//larger on right</span></pre>
<pre style="margin:0;">    result.AddRange(Sort(listToSort.Skip(1)</pre>
<pre style="margin:0;">        .Where(e =&gt; e.CompareTo(start) &gt; 0)));</pre>
<pre style="margin:0;">    <span style="color:blue;">return</span> result;</pre>
<pre style="margin:0;">}</pre>
</div>
<h3>Here’s some highlights of the attached behavior class:</h3>
<div style="font-family:courier new;background:white;color:black;font-size:10pt;"><span style="color:blue;">public</span> <span style="color:blue;">static</span> <span style="color:blue;">class</span> <span style="color:#2b91af;">SortStarter</span></div>
<div style="font-family:courier new;background:white;color:black;font-size:10pt;">
<p style="margin:0;">{</p>
<p style="margin:0;"><span style="color:green;">// // RegisterAttached for attached behaviors</span></p>
<p style="margin:0;"><span style="color:blue;">public</span> <span style="color:blue;">static</span> <span style="color:blue;">readonly</span> <span style="color:#2b91af;">DependencyProperty</span> SortBehaviorProperty =</p>
<p style="margin:0;"><span style="color:#2b91af;">DependencyProperty</span>.RegisterAttached(<span style="color:#a31515;">&#8220;SortBehavior&#8221;</span>, <span style="color:blue;">typeof</span>(<span style="color:blue;">bool</span>), <span style="color:blue;">typeof</span>(<span style="color:#2b91af;">SortStarter</span>), <span style="color:blue;">new</span> <span style="color:#2b91af;">UIPropertyMetadata</span>(<span style="color:blue;">false</span>, SortBehaviorChanged));</p>
<p style="margin:0;">
<p style="margin:0;"><span style="color:green;">// Get/Set Methods for the attached behaviors:</span></p>
<p style="margin:0;"><span style="color:blue;">public</span> <span style="color:blue;">static</span> <span style="color:blue;">bool</span> GetSortBehavior(<span style="color:#2b91af;">DependencyObject</span> obj){</p>
<blockquote>
<p style="margin:0;"><span style="color:blue;">return</span> (<span style="color:blue;">bool</span>)obj.GetValue(SortBehaviorProperty);}</p>
</blockquote>
<p style="margin:0;"><span style="color:blue;">public</span> <span style="color:blue;">static</span> <span style="color:blue;">void</span> SetSortBehavior(<span style="color:#2b91af;">DependencyObject</span> obj, <span style="color:blue;">bool</span> value){</p>
<blockquote>
<p style="margin:0;">obj.SetValue(SortBehaviorProperty, value);}</p>
</blockquote>
<p style="margin:0;">
<p style="margin:0;"><span style="color:green;">// Method to hook the event</span></p>
<p style="margin:0;"><span style="color:blue;">private</span> <span style="color:blue;">static</span> <span style="color:blue;">void</span> SortBehaviorChanged(<span style="color:#2b91af;">DependencyObject</span> dpo, <span style="color:#2b91af;">DependencyPropertyChangedEventArgs</span> args){</p>
<p style="margin:0;"><span style="color:blue;">var</span> button = dpo <span style="color:blue;">as</span> <span style="color:#2b91af;">ButtonBase</span>;</p>
<p style="margin:0;"><span style="color:blue;">if</span> (button != <span style="color:blue;">null</span>){</p>
<p style="margin:0;"><span style="color:blue;">if</span> ((<span style="color:blue;">bool</span>) args.NewValue)</p>
<blockquote>
<p style="margin:0;">button.Click += ButtonOnClick;</p>
</blockquote>
<p style="margin:0;"><span style="color:blue;">else</span></p>
<blockquote>
<p style="margin:0;">button.Click -= ButtonOnClick;</p>
</blockquote>
<p style="margin:0;">}</p>
<p style="margin:0;"><span style="color:green;">// Button Click Handler:</span></p>
<p style="margin:0;"><span style="color:blue;">private</span> <span style="color:blue;">static</span> <span style="color:blue;">void</span> ButtonOnClick(<span style="color:blue;">object</span> sender, <span style="color:#2b91af;">RoutedEventArgs</span> args){</p>
<p style="margin:0;"><span style="color:green;">// Don’t process calls from up the visual tree</span></p>
<p style="margin:0;"><span style="color:blue;">if</span> (!<span style="color:#2b91af;">Object</span>.ReferenceEquals(sender, args.OriginalSource))  <span style="color:blue;">return</span>;</p>
<p style="margin:0;">
<p style="margin:0;"><span style="color:green;">//get VM from DC</span></p>
<p style="margin:0;"><span style="color:blue;">var</span> fxElem = sender <span style="color:blue;">as</span> <span style="color:#2b91af;">FrameworkElement</span>;</p>
<p style="margin:0;"><span style="color:blue;">var</span> vm = ((<span style="color:#2b91af;">FrameworkElement</span>) args.OriginalSource).DataContext as <span style="color:#2b91af;">VM</span>;</p>
<p style="margin:0;"><span style="color:green;">// process with VM and new Sorter class</span></p>
<p style="margin:0;">}</p>
</div>
<h3>Hooking up the button in XAML is simple:</h3>
<p>&lt;Window x:Class=&#8221;WpfApplication1.Window1&#8243;</p>
<p>xmlns=&#8221;<a href="http://schemas.microsoft.com/winfx/2006/xaml/presentation&quot;">http://schemas.microsoft.com/winfx/2006/xaml/presentation&#8221;</a></p>
<p>xmlns:x=&#8221;<a href="http://schemas.microsoft.com/winfx/2006/xaml&quot;">http://schemas.microsoft.com/winfx/2006/xaml&#8221;</a></p>
<p>xmlns:local=&#8221;clr-namespace:WpfApplication1&#8243;</p>
<p>Title=&#8221;Window1&#8243; Height=&#8221;129&#8243; Width=&#8221;300&#8243;&gt;</p>
<p>&lt;Button local:SortStarter.SortBehavior=&#8221;True&#8221; &gt;Sort&lt;/Button&gt;</p>
<p>  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/goldmanalpha.wordpress.com/347/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/goldmanalpha.wordpress.com/347/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/goldmanalpha.wordpress.com/347/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/goldmanalpha.wordpress.com/347/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/goldmanalpha.wordpress.com/347/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/goldmanalpha.wordpress.com/347/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/goldmanalpha.wordpress.com/347/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/goldmanalpha.wordpress.com/347/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/goldmanalpha.wordpress.com/347/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/goldmanalpha.wordpress.com/347/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=goldmanalpha.wordpress.com&#038;blog=9682964&#038;post=347&#038;subd=goldmanalpha&#038;ref=&#038;feed=1" /></div>
]]></content:encoded>
			<wfw:commentRss>http://goldmanalpha.wordpress.com/2009/12/26/functional-homework/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Considering Adding a Functional Language to My Bag of Tricks</title>
		<link>http://goldmanalpha.wordpress.com/2009/11/13/functionallanguage/</link>
		<comments>http://goldmanalpha.wordpress.com/2009/11/13/functionallanguage/#comments</comments>
		<pubDate>Fri, 13 Nov 2009 16:51:42 +0000</pubDate>
		<dc:creator>Aaron Goldman</dc:creator>
				<category><![CDATA[Functional Programming]]></category>
		<category><![CDATA[Lab49]]></category>
		<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false">http://goldmanalpha.wordpress.com/?p=136</guid>
		<description><![CDATA[There are a lot of people @Lab who know things like Erlang, Haskell, Python, R, etc., etc., etc.  I&#8217;m actually considering learning Lisp, but I need a project.  I &#8220;learned&#8221; php for a project over the summer, but I didn&#8217;t really like it since its so much like classic ASP (really messy).  Maybe I&#8217;ll learn [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=goldmanalpha.wordpress.com&#38;blog=9682964&#38;post=136&#38;subd=goldmanalpha&#38;ref=&#38;feed=1" />]]></description>
			<content:encoded><![CDATA[<div class='snap_preview'>
<p>There are a lot of people <a href="http://www.lab49.com/" >@Lab</a> who know things like <a href="http://www.erlang.org/index.html" >Erlang</a>, <a href="http://www.haskell.org/" >Haskell</a>, <a href="http://www.python.org/" >Python</a>, <a href="http://www.r-project.org/" >R</a>, etc., etc., etc.  I&#8217;m actually considering learning <a href="http://en.wikiquote.org/wiki/Lisp_programming_language">Lisp</a>, but I need a project.  I &#8220;learned&#8221; <a href="http://www.sitepoint.com/forums/showthread.php?t=155043" >php</a> for a project over the summer, but I didn&#8217;t really like it since its so much like classic ASP (really messy).  Maybe I&#8217;ll learn <a href="http://research.microsoft.com/en-us/um/cambridge/projects/fsharp/" >F#</a> instead&#8230;  That shouldn&#8217;t be such a strech since I built an <a href="http://www.csis.pace.edu/%7Ebergin/compiler/CompilerAward.html">ML compiler</a> in grad school (F# is based on ML).  I wonder what kind of project I’d be interested in would benefit from a functional language&#8230;  I suppose I’ll have to read up on the language and maybe that will give me some ideas.</p>
<p>Its funny, doing WPF, my umpteenth technology, is just not enough.</p>
<p>  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/goldmanalpha.wordpress.com/136/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/goldmanalpha.wordpress.com/136/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/goldmanalpha.wordpress.com/136/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/goldmanalpha.wordpress.com/136/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/goldmanalpha.wordpress.com/136/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/goldmanalpha.wordpress.com/136/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/goldmanalpha.wordpress.com/136/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/goldmanalpha.wordpress.com/136/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/goldmanalpha.wordpress.com/136/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/goldmanalpha.wordpress.com/136/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=goldmanalpha.wordpress.com&#038;blog=9682964&#038;post=136&#038;subd=goldmanalpha&#038;ref=&#038;feed=1" /></div>
]]></content:encoded>
			<wfw:commentRss>http://goldmanalpha.wordpress.com/2009/11/13/functionallanguage/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>How to use MongoDB from PowerShell and F#</title>
		<link>http://feedproxy.google.com/~r/DevelopmentInABlink/~3/mRs4u15KFU4/</link>
		<comments>http://feedproxy.google.com/~r/DevelopmentInABlink/~3/mRs4u15KFU4/#comments</comments>
		<pubDate>Mon, 26 Oct 2009 02:36:16 +0000</pubDate>
		<dc:creator>Doug Finke</dc:creator>
				<category><![CDATA[Functional Programming]]></category>
		<category><![CDATA[PowerShell]]></category>

		<guid isPermaLink="false">http://dougfinke.com/blog/index.php/2009/10/25/how-to-use-mongodb-from-powershell-and-f/</guid>
		<description><![CDATA[Dwight Merriman, founder of 10gen,&#160; presented today, at Lab49 where I work, about his new database platform:
Mongo (from &#34;humongous&#34;) is a high-performance, open source, schema-free document-oriented database. MongoDB is written in C++ and offers the following features:

Collection oriented storage: easy storage of object/JSON -style data 
Dynamic queries 
Full index support, including on inner objects and [...]]]></description>
			<content:encoded><![CDATA[<p>Dwight Merriman, founder of 10gen,&#160; presented today, at <a href="http://www.lab49.com/">Lab49</a> where I work, about his new database platform:</p>
<p>Mongo (from &quot;humongous&quot;) is a high-performance, open source, schema-free document-oriented database. <a href="http://www.mongodb.org/display/DOCS/Home">MongoDB</a> is written in C++ and offers the following features:</p>
<ul>
<li>Collection oriented storage: easy storage of object/<a href="http://www.mongodb.org/display/DOCS/BSON">JSON</a> -style data </li>
<li>Dynamic <a href="http://www.mongodb.org/display/DOCS/Querying">queries</a> </li>
<li>Full <a href="http://www.mongodb.org/display/DOCS/Indexes">index</a> support, including on inner objects and embedded arrays </li>
<li>Query <a href="http://www.mongodb.org/display/DOCS/Database+Profiler">profiling</a> </li>
<li><a href="http://www.mongodb.org/display/DOCS/Replication">Replication</a> and fail-over support </li>
<li>Efficient storage of binary data including <a href="http://www.mongodb.org/display/DOCS/GridFS">large objects</a> (e.g. photos and videos) </li>
<li><a href="http://www.mongodb.org/display/DOCS/Sharding">Auto-sharding</a> for cloud-level scalability </li>
</ul>
<h3>PowerShell</h3>
<p>Dwight pointed out the way different languages could to talk to MongoDB and C# was one of them using a <a href="http://github.com/samus/mongodb-csharp">community developed driver</a>.</p>
<p>Following the post <a href="http://odetocode.com/blogs/scott/archive/2009/10/13/experimenting-with-mongodb-from-c.aspx">Experimenting with MongoDB from C#</a>, MongoDB was up and running and I was storing and retrieving data in no time.</p>
<p><a href="http://dougfinke.com/uploadPictures/HowtouseMongoDBfromPowerShell_1123E/image.png"><img style="border-bottom: 0px; border-left: 0px; display: inline; margin-left: 0px; border-top: 0px; margin-right: 0px; border-right: 0px" title="image" border="0" alt="image" src="http://dougfinke.com/uploadPictures/HowtouseMongoDBfromPowerShell_1123E/image_thumb.png" width="366" height="261" /></a> </p>
<h3>F#</h3>
<p>Looks like Matthew Podwysocki used the same reference and has <a href="http://gist.github.com/218388">MongoDB working with F#</a>.</p>
<p><img src="http://feeds.feedburner.com/~r/DevelopmentInABlink/~4/mRs4u15KFU4" height="1" width="1"/></p>
]]></content:encoded>
			<wfw:commentRss>http://feedproxy.google.com/~r/DevelopmentInABlink/~3/mRs4u15KFU4/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Don Syme’s F# deck from JAOO</title>
		<link>http://feedproxy.google.com/~r/DevelopmentInABlink/~3/hbBonTPMBzE/</link>
		<comments>http://feedproxy.google.com/~r/DevelopmentInABlink/~3/hbBonTPMBzE/#comments</comments>
		<pubDate>Mon, 12 Oct 2009 13:04:55 +0000</pubDate>
		<dc:creator>Doug Finke</dc:creator>
				<category><![CDATA[.Net]]></category>
		<category><![CDATA[Functional Programming]]></category>

		<guid isPermaLink="false">http://dougfinke.com/blog/?p=820</guid>
		<description><![CDATA[Don Syme, creator of F#, posts his F# tutorial he presented at JAOO 2009. Over 100 crunchy slides.
Some highlights of the code are:

Foundational material on F# async programming, and samples including:

Fetching web pages in parallel
The Bing translator sample using async programming
A Graphical, asynchronous twitter client in 50 lines
A Twitter feed example that uses F# first [...]]]></description>
			<content:encoded><![CDATA[<p>Don Syme, creator of F#, posts his <a href="http://blogs.msdn.com/dsyme/archive/2009/10/10/f-tutorial-code-and-slides-jaoo-2009-edition.aspx">F# tutorial</a> he presented at <a href="http://jaoo.dk/aarhus-2009/">JAOO 2009</a>. Over 100 crunchy slides.</p>
<p>Some highlights of the code are:</p>
<ul>
<li>Foundational material on F# async programming, and samples including:
<ul>
<li>Fetching web pages in parallel</li>
<li>The Bing translator sample using async programming</li>
<li>A Graphical, asynchronous twitter client in 50 lines</li>
<li>A Twitter feed example that uses F# first class reactive event processing to process the stream of feeds</li>
<li>An asynchronous web crawler</li>
<li>Processing images in parallel, using a mixture of I/O and CPU parallelism</li>
</ul>
</li>
<li>An updated version of the famous Interactive DirectX demo</li>
<li>Lots of great micro samples on foundational topics such as
<ul>
<li>object oriented programming</li>
<li>language oriented programming</li>
<li>function composition</li>
<li>design patterns</li>
<li>discriminated unions</li>
<li>records</li>
<li>units of measure</li>
</ul>
</li>
</ul>
<p><img src="http://feeds.feedburner.com/~r/DevelopmentInABlink/~4/hbBonTPMBzE" height="1" width="1"/></p>
]]></content:encoded>
			<wfw:commentRss>http://feedproxy.google.com/~r/DevelopmentInABlink/~3/hbBonTPMBzE/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>F# Integrated with Visual Studio 2010 and .NET 4</title>
		<link>http://feedproxy.google.com/~r/DevelopmentInABlink/~3/7QjI21eYX-0/</link>
		<comments>http://feedproxy.google.com/~r/DevelopmentInABlink/~3/7QjI21eYX-0/#comments</comments>
		<pubDate>Sat, 10 Oct 2009 13:35:45 +0000</pubDate>
		<dc:creator>Doug Finke</dc:creator>
				<category><![CDATA[Functional Programming]]></category>

		<guid isPermaLink="false">http://dougfinke.com/blog/index.php/2009/10/10/f-integrated-with-visual-studio-2010-and-net-4/</guid>
		<description><![CDATA[
 .NET 4 core types that F# uses, such as Tuple, Lazy, and BigInteger, are now part of the .NET Framework and can be used across all .NET languages
One ground-breaking feature of F# is Units of Measure, which allows you to annotate your floating point code with units, such as meters and seconds providing compile-time [...]]]></description>
			<content:encoded><![CDATA[<ul>
<li> .NET 4 core types that F# uses, such as <em>Tuple</em>, <em>Lazy</em>, and <em>BigInteger</em>, are now part of the .NET Framework and can be used across all .NET languages</li>
<li>One ground-breaking feature of F# is Units of Measure, which allows you to annotate your floating point code with units, such as meters and seconds providing compile-time checking</li>
<li>F# language features are designed to make parallel and asynchronous programming more intuitive</li>
<li>F# is a strongly-typed language like C#, but with a lightweight syntax often seen in a dynamic language like Python</li>
</ul>
<p>via <a href="http://blogs.msdn.com/somasegar/archive/2009/10/09/f-in-vs2010.aspx">F# in VS2010</a></p>
<p><img src="http://feeds.feedburner.com/~r/DevelopmentInABlink/~4/7QjI21eYX-0" height="1" width="1"/></p>
]]></content:encoded>
			<wfw:commentRss>http://feedproxy.google.com/~r/DevelopmentInABlink/~3/7QjI21eYX-0/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>IFL 2009: First Impressions</title>
		<link>http://blog.lab49.com/archives/3510</link>
		<comments>http://blog.lab49.com/archives/3510#comments</comments>
		<pubDate>Sun, 04 Oct 2009 19:37:55 +0000</pubDate>
		<dc:creator>Kalani Thielen</dc:creator>
				<category><![CDATA[Architecture]]></category>
		<category><![CDATA[C++]]></category>
		<category><![CDATA[CEP/ESP]]></category>
		<category><![CDATA[Computer Science]]></category>
		<category><![CDATA[Functional Programming]]></category>
		<category><![CDATA[General Development]]></category>
		<category><![CDATA[Grid]]></category>
		<category><![CDATA[HPC]]></category>
		<category><![CDATA[Haskell]]></category>
		<category><![CDATA[Languages]]></category>
		<category><![CDATA[Learning]]></category>
		<category><![CDATA[Lisp]]></category>
		<category><![CDATA[Logic]]></category>
		<category><![CDATA[Performance]]></category>
		<category><![CDATA[Security]]></category>
		<category><![CDATA[Seminars]]></category>
		<category><![CDATA[Technology]]></category>
		<category><![CDATA[Testing]]></category>

		<guid isPermaLink="false">http://blog.lab49.com/archives/3510</guid>
		<description><![CDATA[Last week, my colleague Ken Overton and I attended the IFL 2009 conference in South Orange, New Jersey.&#160; The event was partially funded by Jane St Capital, and consisted of research on the implementation and application of “functional languages.”&#160; The invited talk was by Benjamin Pierce (of TaPL fame), on his joint work (with Nate [...]]]></description>
			<content:encoded><![CDATA[<p>Last week, my colleague <a href="http://blog.lab49.com/archives/3471">Ken Overton</a> and I attended the <a href="http://blogs.shu.edu/projects/IFL2009/">IFL 2009</a> conference in South Orange, New Jersey.&#160; The event was partially funded by <a href="http://ocaml.janestreet.com/">Jane St Capital</a>, and consisted of research on the implementation and application of “functional languages.”&#160; The invited talk was by Benjamin Pierce (of <a href="http://www.cis.upenn.edu/~bcpierce/tapl/">TaPL</a> fame), on his joint work (with <a href="http://www.cis.upenn.edu/~jnfoster/">Nate Foster</a> and others) on the bidirectional programming language <a href="http://www.seas.upenn.edu/~harmony/">Boomerang</a>.&#160; The conference’s full <a href="http://blogs.shu.edu/projects/IFL2009/schedule.html">range of subjects</a> was diverse, and in this article I will summarize what I saw.</p>
<p> <span id="more-3510"></span>
<p>The conference took place over a three-day period.&#160; The first and third days were broken down into four sessions.&#160; The second day ended early, after Dr. Pierce’s presentation, and only had two sessions.&#160; Each session consisted of two to four presentations around a common theme.&#160; This structure worked well enough, and I’ll provide summaries in the same order.</p>
<p><strong>Domain-Specific Functional Languages</strong></p>
<p>First was a presentation on PICOBIT, a compact compiler and virtual machine for a Scheme language suitable for use with microcontrollers.&#160; The Scheme compiler was a fairly straightforward mapping to C.&#160; However, the authors also wrote another compiler for the subset of C that their first compiler produced.&#160; In this C-language, recursion is disallowed, and function-callers pass parameters by modifying their callee’s variables directly.&#160; There was some skepticism about this approach (versus the use of a standard C compiler), although the published performance numbers were reasonable.</p>
<p>Next was a presentation on “Kansas Lava,” a project from the University of Kansas which aims to embed a low-level “circuit” language in Haskell, so that either correct VHDL code can be generated, or the circuit can be tested by the Haskell evaluator.&#160; Here, most of the interesting work in the presentation involved the type-system machinery needed to track the size (in bits) of values as they’re produced by non-trivial compositions of other sized values.&#160; There were no interesting circuit optimizations present, and in fact the speaker demonstrated that even trivial optimizations (e.g.: “1 and X” =&gt; X) weren’t done.&#160; Beyond the basic use-case for dependent types, the speaker also sang the praises of applicative functors in his application (twice over a win for <a href="http://strictlypositive.org/">Conor McBride</a>).</p>
<p>On a similar note, the next speaker presented his work on <a href="http://www.bluespec.com/products/bsc.htm">Bluespec SystemVerilog</a>, a commercial compiler with a Haskell-like system of Hindley-Milner type inference plus multiple-parameter type classes with functional dependencies.&#160; Also like Kansas Lava, much of the difficult work (and the speaker’s most emotional subject) involved inching toward dependent types with type-level arithmetic and the inevitable difficulties of reasoning about arithmetic expressions.&#160; The speaker was presented with an appeal to resort to standard “computer algebra” systems, but in fairness it’s pretty awkward to prove involved propositions about arithmetic in his type system.&#160; There was also some interest in moving to a legitimate dependent-type system.</p>
<p>Finally, the last presentation in this session was called “iTasks for End-users,” which covered a web-based “task-management” application similar to <a href="http://www.fogcreek.com/FogBUGZ/">FogBugz</a>, <a href="http://trac.edgewall.org/">Trac</a>, or <a href="http://studios.thoughtworks.com/mingle-agile-project-management">Mingle</a>.&#160; The novel aspect of this system is that the heavily Javascript-based web forms were derived automatically from the structure of the types of records representing those forms, and that the complex client/server interaction and state management involved in processing forms could be written in a straightforward monadic style.&#160; The speaker conceded that most people found the subject of task-management unrewarding, and there was widespread agreement that he was right.</p>
<p><strong>Multi-core Functional Languages</strong></p>
<p>The first presentation in this session was one of Jane St. Capital’s “Summer of Code” winners – a concurrent garbage collector for O’Caml.&#160; The O’Caml runtime system by default has a garbage collector that is particularly hostile to concurrency.&#160; This project used the sensible approach of allocating level-one heaps distinctly to each thread in a process, and compacting to a shared heap when necessary.&#160; Global synchronization happened only in the case where collection/compaction against the shared heap was invoked.&#160; Overall the reported performance numbers looked promising, and the project seemed worthwhile (if you have to use O’Caml).&#160; Unfortunately, the speaker’s accent was too difficult to understand (and ours for him, as he wasn’t able to parse audience questions) so a few good questions about performance edge-cases went unanswered.</p>
<p>Next was a presentation on a coordination language called “<a href="http://www.snet-home.org/">S-Nets</a>.”&#160; The language had explicit forms for the parallel and sequential composition of programs, as well as some type-directed dispatching logic that would decide when and how inputs would be presented to programs in these networks.&#160; Because it was an explicit coordination language, complex concurrency scenarios translated to fairly complex expressions, but it may make a reasonable shell language, or a target for Hume (the next presentation).</p>
<p>Finally, the session ended with a presentation of “<a href="http://cs.shu.edu/tfp2007/drafts/58.pdf">Hume</a>,” a system for automatically partitioning a program across multiple cores by a “cost-directed” application of meaning-preserving program transformations, the whole body of which the authors have named the “box calculus” (“box” in this case refers to an individual process or thread of execution).&#160; The presenter’s animation of these program transformations was compelling, although slightly dampened by the fact that Hume’s language was limited to non-recursive programs.</p>
<p><strong>Functional Programming and Education</strong></p>
<p>First up in this session was Andy Gill (also the presenter for the Kansas Lava project) discussing his “<a href="http://www.ittc.ku.edu/~andygill/chalkboard.php">Chalkboard</a>” library for writing efficient 2D image-rendering programs.&#160; His system was inspired by Conal Elliott’s <a href="http://conal.net/papers/Vertigo/">Vertigo library</a>, a very influential and straightforward (if not inefficient) system for representing images as their sampling functions.&#160; It qualifies as “education-related” in that it has been used to introduce problems of basic graphics programming to undergraduate students.</p>
<p>Next up was a presentation on “Holmes,” a system for detecting fraudulent homework submissions by a search against historical submissions.&#160; The system worked by applying a series of heuristics, ranging from simple token list edit-distance comparison to similar functions on the control-flow-graph representation of two programs.&#160; A project like this might generally be considered depressing, but it energized the audience like few others.</p>
<p>Finally, the session ended with a presentation appealing to attendees to make formal logic (as applied to proving software correctness) a required course in its own right (and not a sidebar in a general “discrete math” course).&#160; Some statistics were used to make this case, showing that the subject can reasonably be taught to undergraduate students, and briefly surveying the results from schools that do treat the subject adequately.&#160; No clear curricula were presented (in fact, the presenter demonstrated that the two most popular remotely-applicable textbooks only mentioned the subject of logical software verification briefly).&#160; Some schools have taken the <a href="http://books.google.com/books?id=m5w5PRj5Nj4C&amp;dq=coq'art&amp;printsec=frontcover&amp;source=bl&amp;ots=VGpB1NY_-m&amp;sig=Wr48wtj-VjSsDv_PVQUWxypLcNw&amp;hl=en&amp;ei=ahbESpWrEdzd8AbGvvhE&amp;sa=X&amp;oi=book_result&amp;ct=result&amp;resnum=2">Coq’Art</a> book as a starting point, although the speaker didn’t address that (it may be too early for judgment).</p>
<p><strong>Parallel Programming and Reactive Programming</strong></p>
<p>The “pHood” tool for analyzing the performance of parallel functional programs (especially Haskell programs) was presented in this final session of the first day.&#160; Based on a similar tool (named “Hood”) for sequential programs, pHood allows the transparent insertion of some monitoring-annotations (presumably driven by some very cautious use of ‘unsafePerformIO’) to determine how effectively your program is making use of parallelism.</p>
<p>Next was a presentation on “fusion-equipped parallel skeletons,” an interesting (even useful) technique for realizing implicit data-parallelism, simultaneously eliminating redundant work by fusion.&#160; Fusion is typically known as a compiler technique that saves work by “fusing” compositions of functions to eliminate the production of redundant intermediate structures (possibly the simplest example is the identity: map f (map g X) = map (f . g) X).&#160; Impressively (or horrifically, depending on your political persuasion) this was achieved in C++ by a novel application of expression templates (effectively, compile-time representations of C++ parse trees realized by clever template functions, and functions operating on those trees).&#160; For commercial users of C++, this is unquestionably a valuable technique to study.</p>
<p>”Liftless Functional Reactive Programming” was the subject of the next talk.&#160; Like the “Chalkboard” talk before it, this project also traces back to the work by Conal Elliott (and others on FRP generally).&#160; Here the speaker developed an FRP system in Scala, and sought to avoid some of the tediousness of other Haskell-based FRP systems by avoiding “lifting” – the mechanical process of mapping functions on pure values to functions on values in the context of an FRP signal.&#160; The solution involved the manipulation of a hidden stack of widget actions, maybe a deflating approach to FRP enthusiasts (especially concurrency-minded ones), but probably effective for any users of Scala.</p>
<p>Finally, the last presentation of the session (and the first day) was entitled “Eventless Reactivity From Scratch,” and featured another FRP system (this one in Haskell).&#160; The speaker briefly surveyed a few well-known FRP systems before explaining his own.&#160; Key to this system is applicative binding (e.g.: his first example defines a lifted sum on signals using the applicative ‘liftA2’ function) and time-based signal functions (hence “eventless reactivity”).&#160; A novel (to my eyes) use of the “mdo” syntax for recursive monadic binding within this system allowed a particularly elegant definition of the sine and cosine functions as integrals of each other.&#160; Overall this presentation functioned as an accessible overview of FRP methods in Haskell, and as a clear roadmap for interested developers.&#160; As with the other presentations on this subject, Conal Elliott’s FRP work was also highlighted.</p>
<p><strong>Compilation</strong></p>
<p>The second day began with a very interesting presentation on “compiling SaC for the ‘MicroGrid’ architecture.”&#160; SaC (or “single-assignment C”) is a popular language among researchers in parallel languages, and in this case it was used to realize data-parallel programs on a novel hardware platform called the “MicroGrid.”&#160; This architecture features a massive collection of processors, each capable of evaluating many threads of execution concurrently.&#160; As with several other projects of this sort, it’s <em>nested</em> data-parallelism that poses unique challenges to compiler-writers, and although this architecture went some way toward alleviating those problems, in at least one example the presenter demonstrated sub-optimal distribution at the second level of nested parallelism (e.g.: the first pass distributes across three processors, and from there to 200 threads each).&#160; This project is definitely an interesting work-in-progress.</p>
<p>”Arity raising” was the next topic; the main objective here is to optimize for large register sets by mechanically breaking one argument of a function into multiple arguments (the constituent parts of the argument that are actually used in the body of the function or, recursively, its callees) with the hope that better register usage can be achieved.&#160; As newer processors feature ever larger register sets, the argument for this particular optimization will grow more compelling.&#160; In this case the optimization was applied to a compiler for an ML-language, which made for a good testbed in any case (ML programs probably rely on language-level constructs for composing data more than most other languages).</p>
<p>A restricted form of dependent types, called “Symbiotic Expressions” by their presenters, made for the last presentation in this session.&#160; The “expressions” meant here are actually index variable and array bounds constraints, which are “symbiotic” in that they are associated with AST nodes in the intermediate form of a SaC program.&#160; A few associated optimizations were discussed, including an “algebraic with-loop folding” technique for flattening nested data-parallel loops.</p>
<p><strong>Language Features</strong></p>
<p>Here we received an interesting presentation titled “A Calculus for Coercive Subtyping.”&#160; In fact, the aim of this project is to implement a dependently typed lambda calculus with implicit coercion (as a means of achieving subtyping).&#160; The talk was very dense with typing rules, but overall the approach seemed amenable to the general system of qualified types (translated to an intermediate calculus with explicit witnesses of subtyping/overloading) developed by <a href="http://www.amazon.com/Qualified-Types-Practice-Distinguished-Dissertations/dp/0521543266">Mark Jones</a> (though he didn’t study dependent type systems in that work).&#160; Working in a dependently typed lambda calculus also adds some complication in the valid dependency-pairings admitted – i.e.: the presenters defined a lambda cube of overloading parallel to the standard one.&#160; Unfortunately, the pace of the presentation made it difficult to follow, and the audience presented no questions.</p>
<p>A powerful application of “stream fusion” in Haskell was demonstrated next.&#160; Stream fusion is a special case of the general principle of fusion (discussed earlier), which, with the GHC compiler, can be achieved with <a href="http://www.haskell.org/ghc/docs/latest/html/users_guide/rewrite-rules.html">“rewrite rules”</a> – directives that tell the compiler how certain terms can be simplified (and only valid due to the inherent referential transparency of Haskell terms).&#160; Here the objective was to provide an efficient representation for Unicode strings, allowing (as with regular strings in Haskell) the normal list-functions (e.g.: map, filter, foldl, etc).&#160; To make this work, the standard list functions must be defined in terms of streams rather than lists, and dual stream/unstream functions must be defined on data-types (in this case, on arrays of Unicode characters) in order to give them the expected interface (and to convert from that interface back to the array form).&#160; In this way, a function removing numbers and converting to uppercase on Unicode strings can be expressed as “unstream . (map toUpper) . stream . unstream . (filter isNotDigit) . stream” and the fusion step here will be the application of the rewrite rule “stream (unstream x) = x” (which has the effect of eliminating intermediate structures, as desired).&#160; In all, this was an ideal presentation.</p>
<p>“General contract boundaries” were discussed in the next presentation, in the context of PLT Scheme.&#160; As the first audience member at question-time observed, there was a significant amount of overlap between this project and the general principle of type systems.</p>
<p>Finally the session ended with another gem, an embedding of a bidirectional language in Haskell.&#160; This approach contrasted with the invited presentation by Ben Pierce (to follow) by defining a data-type for bidirectional functions, and combinators on such functions mirroring many standard functions (map, filter, etc).&#160; Perhaps the greatest benefit from this approach, aside from the usual benefits from embedding in Haskell, was that reverse functions could be generated with their forward data trivially.&#160; The bidirectional editor GUI was much less compelling, but it was good enough to demonstrate the basic principles.</p>
<p><strong>How to Build Your Own Bidirectional Programming Language</strong></p>
<p>This invited talk began with a summary of the kind of problem that bidirectional programming aims to solve: in essence, the “view-update” problem familiar to users and developers of relational databases.&#160; As a running example, the presenter used an XML representation of a simple database of composers, and a projection (or “view”) of a subset of that data as simple newline-delimited text.&#160; It should be possible then to update the newline-delimited view and have the original XML representation updated as well.&#160; In contrast to the previous presenter’s solution to the same problem, this one was built as its own self-contained language: <a href="http://www.seas.upenn.edu/~harmony/">Boomerang</a>.&#160; Its primitives are finite-state transducers, just the simplest bidirectional transformations on strings (describable by regular expressions).&#160; <a href="http://augeas.net/">A tool inspired by this language</a> is apparently used by RedHat to unify configuration of all sorts of small /etc/ configuration files.&#160; Other applications are immediately possible as well.&#160; For example, as my colleague Ken Overton pointed out, sharing structure representations between multiple languages (e.g.: Java/C++) can be made much simpler, without the intermediate canonical representations that many people resort to.</p>
<p><strong>Theorem Provers and Testing</strong></p>
<p>On this, the third and final day, the first session began with a presentation on “user-interface driven theorem prover development.”&#160; Unfortunately, the subject of the talk was not the theorem prover itself, but just its GUI.&#160; In essence, the presentation was about Intellisense for theorem provers (and thanks to the Curry-Howard isomorphism, the “for theorem provers” part can be dropped).&#160; The presenter digressed at some length on the subject of highlighting sub-expressions.&#160; I don’t remember the word “zipper” mentioned, but that was his approach, in essence.</p>
<p>Next up was a presentation on hygienic macros in the ACL2 theorem prover.&#160; Actually this talk again was only incidentally related to theorem provers.&#160; ACL2 admits a subset of Common Lisp, where higher order functions are strictly disallowed.&#160; To get around this limitation, users of ACL2 use macros heavily (to generate first order functions from macros embodying higher order functions).&#160; That would have been frustrating enough, but their macro system was unhygienic (it allowed macro substitution to capture variables from its enclosing scope) and so this presentation concerned the cleaning up of that mess.&#160; In essence, this is the resolution of the same old “dynamic scope” bug under a different guise.</p>
<p>Finally the last presentation in this session was another gem, and (although strictly speaking it was about “testing”) this presentation came the closest to actually discussing a technique for proving theorems.&#160; Its subject was “unifying QuickCheck and SmallCheck,” which requires some background explanation.&#160; QuickCheck is a novel system for testing Haskell programs (and Erlang, if you need it) by requiring only the specification of straightforward logical propositions (e.g.: “reverse (xs++ys) = (reverse ys)++(reverse xs)”), after which it will randomly search the space of the quantified variables of the proposition (that’s the “xs” and “ys” variables of the last expression) until it finds a configuration that contradicts the proposition.&#160; Having then found a contradiction, it simplifies the offending configuration until it’s as simple as possible, while still demonstrating the contradiction.&#160; SmallCheck is a similar system, except that rather than randomly searching for a contradiction it will exhaustively search for a contradiction (up to a given size).&#160; This presentation concerned the technical details of bringing both of these systems together into one.</p>
<p><strong>Incrementalization, GADTs, Generic Programming</strong></p>
<p>“Incrementalization” of datatype-centric libraries was the focus of the first presentation in this series.&#160; As the presenter defined it, datatype-centric libraries are those where a small set of datatypes are constructed and summarized or translated only within the context of that library.&#160; “Incrementalization” of such a library entails the addition of some accumulating data in the constructors of the relevant datatypes, and the rewriting of “deep” recursive functions over such structures (for example, recursively counting the nodes of a binary tree) to “shallow” functions of the accumulators added to those datatypes (for example, adding the count of children to a binary tree’s constructor, so that counting them is trivial and incrementally building the binary tree also incrementally computes this count from nested binary tree nodes).&#160; This approach of “incrementalizing” libraries amounts to an embedding of attribute grammars in Haskell, which the presenter briefly touched on.</p>
<p>The next presenter introduced the Clean language’s “Dynamic” type (for runtime type checking) and then gave a presentation on simulating Clean’s “Dynamic” with GADTs in Haskell.&#160; His analysis suggested that Clean’s dynamic type-information consumption is dual to an analogous type-information construction inherent in the use of GADTs.</p>
<p>A language (“Qube”) for efficient “rank-generic” array programs formed the basis for the next and final presentation in this session.&#160; This presentation covered the application of dependent typing (in a limited context) to type-check “shape analyses” on array operations.&#160; This is a subject covered in bits and pieces by several different approaches, but it has long seemed that dependent types provide an ideal way to synthesize these many disparate techniques, so I was especially happy to find this presentation.&#160; The generalized treatment of matrix multiplication (for matrix, vector, and scalar cases in each configuration) is particularly amenable to this treatment, as are many other important functions like the inner product and so on.&#160; The presenters covered the type-safe implementation of these functions in Qube, and demonstrated performance numbers on massively parallel hardware that were in most cases almost identical to hand-written C.&#160; All in all, this was one of the most interesting presentations of the entire conference for those of us working in the financial sector.</p>
<p><strong>Evaluation Models and Environments</strong></p>
<p>Leading this session was a presentation on “Call by Effect.”&#160; The presenter initially made the standard argument in favor of effect systems – higher order functions (like map, filter, etc) only need to be written once, and are then polymorphic in both computation types and effect types (in contrast to Haskell where there’s a pure map function and a monadic ‘mapM’).&#160; Following that, the presenter defined “call by effect” as a method of achieving lazy evaluation when pure code is evaluated, and eager evaluation in the presence of effects.&#160; As far as evaluation order goes, this approach allows a language with effect types to reduce terms in the same way as Haskell (lazily when possibly, eagerly when necessary) although, strictly speaking, Haskell offers more than two options.&#160; With its ability to describe effects without special-purpose type-system extensions, Haskell still seems closer to the ideal, but its lifting functions and monad transformers are awkward enough to make effect system research like this worthwhile.&#160; Maybe some day the two will meet somewhere in the middle.</p>
<p>The next presentation was titled “Very Lazy Evaluation: A New Execution Model for Functional Languages.”&#160; It concerned a system similar to abstract machines like the SECD or STG machines, suitable as a target for compilers of functional languages (and specifically those with lazy evaluation).&#160; The approach seemed to me to be a fairly straightforward stack machine, but further details in the post-conference paper may demonstrate more subtle features.</p>
<p>Finally, the last presentation in this session seemed like essentially a small FRP system for mobile devices in Scheme.&#160; Like the other Scheme presentations, there was a fair amount of audience skepticism about basic points of practice (ad-hoc type systems being developed, unclear/inconsistent semantics of low-level OS interaction, etc).&#160; The presenter showed a couple of amusing projects built with this system (one great video was of a group of developers shaking their phones to produce music).</p>
<p><strong>Implementation and Benchmarking</strong></p>
<p>”Record combinators” were the subject of the first presentation in this last session of the conference.&#160; This presentation was also fairly dense in implementation details, but the general approach seemed to be to embed a language of record extensions/reflection in Haskell.&#160; Here I was again reminded of Mark Jones’s work in <a href="http://books.google.com/books?id=43JKbm523AwC&amp;lpg=PA124&amp;ots=6mwVZIUZbU&amp;dq=mark%20jones%20qualified%20types&amp;pg=PP1#v=onepage&amp;q=&amp;f=false">qualified types</a> – where qualified types are shown to unify Haskell-style type classes, O’Caml-style structural subtyping, and type systems with record constraints.&#160; The full details were a little difficult to follow in the presentation setting, but (like the example of the inner-product function for rank generic dependent array programming) there were a few examples given that helped motivate the audience to want such a system.&#160; These seemed to boil down to wanting to treat records generically in one case (say, sending any serializable record as a message across a network) while simultaneously verifying code against the specific structure of the record in most other cases (as when a specific field is requested from a record).&#160; I have not personally done much work with these kinds of systems, but it seems like a interesting subject to explore.</p>
<p>The design and implementation of higher-order modules in SML/NJ was covered next.&#160; Modules are ML’s principle method of organizing programs, along with functors (ML’s name for module-dependent modules).&#160; SML/NJ also includes support for “higher-order” modules (functor-dependent modules, or modules that define functors).&#160; <a href="http://www.smlnj.org/doc/features.html">The SML/NJ documentation</a> has some useful examples (under the heading “higher-order modules”).&#160; This presentation explored where the design of higher-order modules has worked well in SML/NJ, and clarified some issues of its static semantics for those of us who don’t work often with ML modules.</p>
<p>Finally, the session (and the conference overall) ended with a presentation on a project called “Unibench,” which aims to be a universal tool for benchmarking applications.&#160; Unibench is a web application that can run several builds of arbitrary programs (where builds are organized along the usual OS/compiler groups), and automatically apply ad-hoc benchmarking scripts to keep track of each program’s performance profile over time.&#160; Several audience members pointed out that the Unibench tool had a lot in common with build-server systems, and in fact it seemed to be a primitive version of <a href="http://www.jetbrains.com/teamcity/">TeamCity</a>.</p>
<p><strong>Summary</strong></p>
<p> Overall the conference had several very interesting presentations, some of which have a direct impact on those of us working in the financial sector.&#160; I hope that I haven’t mischaracterized any of the presentations (if so, I hope that the aggrieved parties will add comments here).&#160; It was very interesting to get a chance to put faces to the names of several people whose work I’ve only encountered before in print.&#160; At the end of the last day, I was left with a lot of ideas to think about.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.lab49.com/archives/3510/feed</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>IFL 2009</title>
		<link>http://blog.lab49.com/archives/3471</link>
		<comments>http://blog.lab49.com/archives/3471#comments</comments>
		<pubDate>Sun, 27 Sep 2009 15:04:18 +0000</pubDate>
		<dc:creator>Ken Overton</dc:creator>
				<category><![CDATA[Computer Science]]></category>
		<category><![CDATA[Events]]></category>
		<category><![CDATA[Functional Programming]]></category>
		<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false">http://blog.lab49.com/?p=3471</guid>
		<description><![CDATA[I spent part of last week attending IFL 2009; as I don&#8217;t really consider myself a &#8216;real&#8217; functional programmer, what I have to say is kind of an outsiders perspective. Generally, I thought it was worth 3 days of my life and saw some things that look pretty promising. It was also nice to get [...]]]></description>
			<content:encoded><![CDATA[<p>I spent part of last week attending <a href="http://blogs.shu.edu/projects/IFL2009/">IFL 2009</a>; as I don&#8217;t really consider myself a &#8216;real&#8217; functional programmer, what I have to say is kind of an outsiders perspective.</p>
<p>Generally, I thought it was worth 3 days of my life and saw some things that look pretty promising.  It was also nice to get a window on the types of problems that the field is grappling with right now.  Not surprisingly, there were several presentations on concurrency/parallelism; some were attempts to provide more syntax for explicitly declaring concurrent programs, but what I find more promising were the presentations of data parallelism where the language or library figures out what can be processed in parallel and optimally does it for you.  Thus your programs address the problem you&#8217;re actually solving rather than concurrency arcana.</p>
<p>What did surprise me (as an outsider) was the struggles to deal with reactive programming models &#8212; eventing, callbacks, GUIs.  The sorts of things that are pretty trivial when you don&#8217;t mind keeping state (I include callback-functions here) are very complicated without.  Another surprise (in a good way) was the wealth of possibilities in the FL-universe for testing: theorem provers to provide logical underpinnings and automatic testing tools that can generate tests that unit-testing people write for ourselves.  These tools are light-years ahead of our typical unit-testing environment.  Not only can they save us the time of writing the tests, they&#8217;ll do a better job of coming up with all the corner cases.</p>
<p>One other observation: the way to find out who you should have been paying attention to is not to look at who&#8217;s presenting &#8212; look at the citations from all the presenters and which names keep popping up. For this conference the name Conal Elliott seemed to crop up in quite a range of presentations.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.lab49.com/archives/3471/feed</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
		<item>
		<title>Reactive Programming: How to Invert an Enumerator</title>
		<link>http://blog.lab49.com/archives/3252</link>
		<comments>http://blog.lab49.com/archives/3252#comments</comments>
		<pubDate>Wed, 29 Jul 2009 17:11:37 +0000</pubDate>
		<dc:creator>Jeremy Kimball</dc:creator>
				<category><![CDATA[.Net]]></category>
		<category><![CDATA[Functional Programming]]></category>
		<category><![CDATA[LINQ]]></category>
		<category><![CDATA[Learning]]></category>

		<guid isPermaLink="false">http://blog.lab49.com/archives/3252</guid>
		<description><![CDATA[“The opposite of a correct statement is a false statement. But the opposite of a profound truth may well be another profound truth.” Niels Bohr Enumerables and Enumerators, oh my! Enumerables and Enumerators are great; big sacks of data we can iterate through using a well-established method. Just in case anyone isn’t up on their [...]]]></description>
			<content:encoded><![CDATA[<p class="MsoNormal"><i style="mso-bidi-font-style: normal">“The opposite of a correct statement is a false statement. But the opposite of a profound truth may well be another profound truth.” </i></p>
<p class="MsoNormal"><i style="mso-bidi-font-style: normal">Niels Bohr </i></p>
</p>
<h2>Enumerables and Enumerators, oh my!</h2>
<p class="MsoNormal">Enumerables and Enumerators are great; big sacks of data we can iterate through using a well-established method. Just in case anyone isn’t up on their GOF, the pair looks a bit like this:</p>
<p class="MsoNormal" style="margin-bottom: 0pt; line-height: normal; mso-layout-grid-align: none"><span style="font-size: 10pt; color: blue; font-family: &quot;Courier New&quot;; mso-no-proof: yes">interface</span><span style="font-size: 10pt; font-family: &quot;Courier New&quot;; mso-no-proof: yes"> <span style="color: #2b91af">IEnumerable</span>&lt;T&gt; </span></p>
<p class="MsoNormal" style="margin-bottom: 0pt; line-height: normal; mso-layout-grid-align: none"><span style="font-size: 10pt; font-family: &quot;Courier New&quot;; mso-no-proof: yes">{ </span></p>
<p class="MsoNormal" style="margin-bottom: 0pt; line-height: normal; mso-layout-grid-align: none"><span style="font-size: 10pt; color: #2b91af; font-family: &quot;Courier New&quot;; mso-no-proof: yes"><span style="mso-spacerun: yes">&#160;&#160;&#160; </span>IEnumerator</span><span style="font-size: 10pt; font-family: &quot;Courier New&quot;; mso-no-proof: yes">&lt;T&gt; GetEnumerator(); </span></p>
<p class="MsoNormal" style="margin-bottom: 0pt; line-height: normal; mso-layout-grid-align: none"><span style="font-size: 10pt; font-family: &quot;Courier New&quot;; mso-no-proof: yes">} </span></p>
<p> <span style="font-size: 10pt; font-family: &quot;Courier New&quot;; mso-no-proof: yes"></span>
<p class="MsoNormal" style="margin-bottom: 0pt; line-height: normal; mso-layout-grid-align: none"><span style="font-size: 10pt; color: blue; font-family: &quot;Courier New&quot;; mso-no-proof: yes">interface</span><span style="font-size: 10pt; font-family: &quot;Courier New&quot;; mso-no-proof: yes"> <span style="color: #2b91af">IEnumerator</span>&lt;T&gt; : <span style="color: #2b91af">IDisposable </span></span></p>
<p class="MsoNormal" style="margin-bottom: 0pt; line-height: normal; mso-layout-grid-align: none"><span style="font-size: 10pt; font-family: &quot;Courier New&quot;; mso-no-proof: yes">{ </span></p>
<p class="MsoNormal" style="margin-bottom: 0pt; line-height: normal; mso-layout-grid-align: none"><span style="font-size: 10pt; color: blue; font-family: &quot;Courier New&quot;; mso-no-proof: yes"><span style="mso-spacerun: yes">&#160;&#160;&#160; </span>bool</span><span style="font-size: 10pt; font-family: &quot;Courier New&quot;; mso-no-proof: yes"> MoveNext(); </span></p>
<p class="MsoNormal" style="margin-bottom: 0pt; line-height: normal; mso-layout-grid-align: none"><span style="font-size: 10pt; font-family: &quot;Courier New&quot;; mso-no-proof: yes"><span style="mso-spacerun: yes">&#160;&#160;&#160; </span>T Current { <span style="color: blue">get</span>; } </span></p>
<p class="MsoNormal" style="margin-bottom: 0pt; line-height: normal; mso-layout-grid-align: none"><span style="font-size: 10pt; font-family: &quot;Courier New&quot;; mso-no-proof: yes">} </span></p>
<p> <span style="font-size: 10pt; font-family: &quot;Courier New&quot;; mso-no-proof: yes"></span>
</p>
<p class="MsoNormal">So we have our “sack”, our Enumerable of type T, where we can obtain a disposable reference to the Enumerator (also of type T), which we can use as a sort of pointer into the sack to move about and grab elements out. This is of course exactly what the compiler does when you use the foreach construct in C#:</p>
<p class="MsoNormal" style="margin-bottom: 0pt; line-height: normal; mso-layout-grid-align: none"><span style="font-size: 10pt; color: blue; font-family: &quot;Courier New&quot;; mso-no-proof: yes">foreach</span><span style="font-size: 10pt; font-family: &quot;Courier New&quot;; mso-no-proof: yes"> (<span style="color: blue">var</span> item <span style="color: blue">in</span> myEnumerable) </span></p>
<p class="MsoNormal" style="margin-bottom: 0pt; line-height: normal; mso-layout-grid-align: none"><span style="font-size: 10pt; font-family: &quot;Courier New&quot;; mso-no-proof: yes">{ </span></p>
<p class="MsoNormal" style="margin-bottom: 0pt; line-height: normal; mso-layout-grid-align: none"><span style="font-size: 10pt; color: #2b91af; font-family: &quot;Courier New&quot;; mso-no-proof: yes"><span style="mso-spacerun: yes">&#160;&#160;&#160; </span>Console</span><span style="font-size: 10pt; font-family: &quot;Courier New&quot;; mso-no-proof: yes">.WriteLine(item); </span></p>
<p class="MsoNormal" style="margin-bottom: 0pt; line-height: normal; mso-layout-grid-align: none"><span style="font-size: 10pt; font-family: &quot;Courier New&quot;; mso-no-proof: yes">} </span></p>
<p class="MsoNormal" style="margin-bottom: 0pt; line-height: normal; mso-layout-grid-align: none"><span style="font-size: 10pt; color: green; font-family: &quot;Courier New&quot;; mso-no-proof: yes">// Is equivalent to: </span></p>
<p class="MsoNormal" style="margin-bottom: 0pt; line-height: normal; mso-layout-grid-align: none"><span style="font-size: 10pt; color: blue; font-family: &quot;Courier New&quot;; mso-no-proof: yes">using</span><span style="font-size: 10pt; font-family: &quot;Courier New&quot;; mso-no-proof: yes">(<span style="color: blue">var</span> myEnumerator = myEnumerable.GetEnumerator()) </span></p>
<p class="MsoNormal" style="margin-bottom: 0pt; line-height: normal; mso-layout-grid-align: none"><span style="font-size: 10pt; font-family: &quot;Courier New&quot;; mso-no-proof: yes">{ </span></p>
<p class="MsoNormal" style="margin-bottom: 0pt; line-height: normal; mso-layout-grid-align: none"><span style="font-size: 10pt; color: blue; font-family: &quot;Courier New&quot;; mso-no-proof: yes"><span style="mso-spacerun: yes">&#160;&#160;&#160; </span>while</span><span style="font-size: 10pt; font-family: &quot;Courier New&quot;; mso-no-proof: yes">(myEnumerator.MoveNext()) </span></p>
<p class="MsoNormal" style="margin-bottom: 0pt; line-height: normal; mso-layout-grid-align: none"><span style="font-size: 10pt; font-family: &quot;Courier New&quot;; mso-no-proof: yes"><span style="mso-spacerun: yes">&#160;&#160;&#160; </span>{ </span></p>
<p class="MsoNormal" style="margin-bottom: 0pt; line-height: normal; mso-layout-grid-align: none"><span style="font-size: 10pt; font-family: &quot;Courier New&quot;; mso-no-proof: yes"><span style="mso-spacerun: yes">&#160;&#160;&#160; </span><span style="mso-spacerun: yes">&#160;&#160;&#160; </span><span style="color: blue">var</span> item = myEnumerator.Current; </span></p>
<p class="MsoNormal" style="margin-bottom: 0pt; line-height: normal; mso-layout-grid-align: none"><span style="font-size: 10pt; font-family: &quot;Courier New&quot;; mso-no-proof: yes"><span style="mso-spacerun: yes">&#160;&#160;&#160;&#160;&#160;&#160;&#160; </span><span style="color: #2b91af">Console</span>.WriteLine(item); </span></p>
<p class="MsoNormal" style="margin-bottom: 0pt; line-height: normal; mso-layout-grid-align: none"><span style="font-size: 10pt; font-family: &quot;Courier New&quot;; mso-no-proof: yes"><span style="mso-spacerun: yes">&#160;&#160;&#160; </span>} </span></p>
<p class="MsoNormal" style="margin-bottom: 0pt; line-height: normal; mso-layout-grid-align: none"><span style="font-size: 10pt; font-family: &quot;Courier New&quot;; mso-no-proof: yes">} </span></p>
<p> <span style="font-size: 10pt; font-family: &quot;Courier New&quot;; mso-no-proof: yes">
<p>&#160;</p>
<p> </span>
<p class="MsoNormal" style="margin-bottom: 0pt; line-height: normal; mso-layout-grid-align: none"><span style="mso-no-proof: yes; mso-bidi-font-family: &#39;Courier New&#39;">This bit of background is necessary in order to discuss the <i style="mso-bidi-font-style: normal">really</i> interesting bit: </span></p>
</p>
<p class="MsoNormal" style="margin-bottom: 0pt; line-height: normal; mso-layout-grid-align: none"><span style="mso-no-proof: yes; mso-bidi-font-family: &#39;Courier New&#39;"><span style="mso-spacerun: yes">&#160; </span><b style="mso-bidi-font-weight: normal"><i style="mso-bidi-font-style: normal">What is the opposite of an Enumerable?</i></b> </span></p>
<p> <span style="mso-no-proof: yes; mso-bidi-font-family: &#39;Courier New&#39;">
<p>&#160;</p>
<p> </span><br />
<h2><span style="mso-no-proof: yes">Part the second, where we talk about funky math
</p>
<p>   </span></h2>
<p class="MsoNormal">Long ago in days of yore, when computer scientists, philosophers and mathematicians all hung out at the same bars discussing grand ideas, people with names like Russell, Church, and Turing spoke of a new way of describing “stuff” that was governed entirely by the unyielding rules of math and logic. Finally, people the world over could talk about apples and oranges, and even state in precise terms how apples and oranges were both indeed fruit, even though an apple was not an orange, nor an orange an apple!</p>
<p class="MsoNormal">Ok, that may have been a bit much – rather than go into a deep discussion about type theory and lambda calculus, I shall refer you, humble reader, to the magic of the internets, where you shall find descriptions so as to make your brain melt into a goo. Alternatively, you could talk to <b style="mso-bidi-font-weight: normal"><a href="http://blog.lab49.com/archives/3011">this guy</a>.</b></p>
<p class="MsoNormal">Instead, in the hopes of keeping at least some of your attention, we shall jump right in with trying to express the above Enumerable/Enumerator pair using a very simple “type language.” Looking first at the IEnumerable&lt;T&gt;, we see that it has one method (we’ll call it a “function”):</p>
<p class="MsoNormal" style="margin-bottom: 0pt; line-height: normal; mso-layout-grid-align: none"><span style="font-size: 10pt; color: #2b91af; font-family: &quot;Courier New&quot;; mso-no-proof: yes">IEnumerator</span><span style="font-size: 10pt; font-family: &quot;Courier New&quot;; mso-no-proof: yes">&lt;T&gt; GetEnumerator(); </span></p>
</p>
<p class="MsoNormal">In our simple type language, we shall describe it thusly:</p>
<p class="MsoNormal"><span style="font-family: &quot;Courier New&quot;"><span style="mso-tab-count: 1">&#160;&#160;&#160;&#160; </span>() -&gt; ( () -&gt; T ) </span></p>
</p>
<p class="MsoNormal">The above can be read as: “A function that returns a thing that contains a function that returns something of type T”. It can also be read as “A function that returns an enumerator that contains a function pair that can return something of type T”.</p>
<p class="MsoNormal">Of course, it’s quite a bit more complicated than this – since we are implicitly changing the state of the enumerator whenever we call MoveNext, we get into some funky stuff relating to that cringe-worthy word “Monad”, but we’re going to glaze over all that for now. Just think of it as described above.</p>
<p class="MsoNormal">Ok, now that is settled, we’re going to do something really funky; we’ll take this:</p>
<p class="MsoNormal"><span style="font-family: &quot;Courier New&quot;"><span style="mso-tab-count: 1">&#160;&#160;&#160;&#160; </span>() -&gt; ( () -&gt; T ) </span></p>
<p class="MsoNormal">And turn around all the arrows, producing this (why this is a valid thing to do is related to mystical terms like covariance and contra-variance, which I won’t begin to try to describe here):</p>
<p class="MsoNormal"><span style="font-family: &quot;Courier New&quot;"><span style="mso-tab-count: 1">&#160;&#160;&#160;&#160; </span>() &lt;- ( () &lt;- T ) </span></p>
<p class="MsoNormal">It’s a little easier to read left to right, so reordering:</p>
<p class="MsoNormal"><span style="font-family: &quot;Courier New&quot;"><span style="mso-tab-count: 1">&#160;&#160;&#160;&#160; </span>(T -&gt; ()) -&gt; () </span></p>
<p class="MsoNormal">We can read this as: “A function ‘A’ that takes another function ‘B’ that takes a thing of type ‘T’ and returns nothing, with function ‘A’ also returning nothing”. Interesting…that looks a lot like the definition of a callback:</p>
<p class="MsoNormal" style="margin-bottom: 0pt; line-height: normal; mso-layout-grid-align: none"><span style="font-size: 10pt; color: blue; font-family: &quot;Courier New&quot;; mso-no-proof: yes">void</span><span style="font-size: 10pt; font-family: &quot;Courier New&quot;; mso-no-proof: yes"> Foo(<span style="color: #2b91af">Action</span>&lt;T&gt; callback); </span></p>
</p>
<p class="MsoNormal">If we perform that same type of “type reversal” to all the members of IEnumerable and IEnumerator, we get definitions a bit like these:</p>
<p class="MsoNormal" style="margin-bottom: 0pt; line-height: normal; mso-layout-grid-align: none"><span style="font-size: 10pt; color: blue; font-family: &quot;Courier New&quot;; mso-no-proof: yes">interface</span><span style="font-size: 10pt; font-family: &quot;Courier New&quot;; mso-no-proof: yes"> <span style="color: #2b91af">IBackwardsEnumerable</span>&lt;T&gt; </span></p>
<p class="MsoNormal" style="margin-bottom: 0pt; line-height: normal; mso-layout-grid-align: none"><span style="font-size: 10pt; font-family: &quot;Courier New&quot;; mso-no-proof: yes">{ </span></p>
<p class="MsoNormal" style="margin-bottom: 0pt; line-height: normal; mso-layout-grid-align: none"><span style="font-size: 10pt; color: blue; font-family: &quot;Courier New&quot;; mso-no-proof: yes"><span style="mso-spacerun: yes">&#160;&#160;&#160; </span>void</span><span style="font-size: 10pt; font-family: &quot;Courier New&quot;; mso-no-proof: yes"> Subscribe( </span></p>
<p class="MsoNormal" style="margin-bottom: 0pt; line-height: normal; mso-layout-grid-align: none"><span style="font-size: 10pt; font-family: &quot;Courier New&quot;; mso-no-proof: yes"><span style="mso-spacerun: yes">&#160;&#160;&#160;&#160;&#160;&#160;&#160; </span><span style="color: #2b91af">IBackwardsEnumerator</span>&lt;T&gt; callbackLikeThing </span></p>
<p class="MsoNormal" style="margin-bottom: 0pt; line-height: normal; mso-layout-grid-align: none"><span style="font-size: 10pt; font-family: &quot;Courier New&quot;; mso-no-proof: yes"><span style="mso-spacerun: yes">&#160;&#160;&#160; </span>); </span></p>
<p class="MsoNormal" style="margin-bottom: 0pt; line-height: normal; mso-layout-grid-align: none"><span style="font-size: 10pt; font-family: &quot;Courier New&quot;; mso-no-proof: yes">} </span></p>
<p class="MsoNormal" style="margin-bottom: 0pt; line-height: normal; mso-layout-grid-align: none"><span style="font-size: 10pt; color: blue; font-family: &quot;Courier New&quot;; mso-no-proof: yes">interface</span><span style="font-size: 10pt; font-family: &quot;Courier New&quot;; mso-no-proof: yes"> <span style="color: #2b91af">IBackwardsEnumerator</span>&lt;T&gt; </span></p>
<p class="MsoNormal" style="margin-bottom: 0pt; line-height: normal; mso-layout-grid-align: none"><span style="font-size: 10pt; font-family: &quot;Courier New&quot;; mso-no-proof: yes">{ </span></p>
<p class="MsoNormal" style="margin-bottom: 0pt; line-height: normal; mso-layout-grid-align: none"><span style="font-size: 10pt; color: blue; font-family: &quot;Courier New&quot;; mso-no-proof: yes"><span style="mso-spacerun: yes">&#160;&#160;&#160; </span>void</span><span style="font-size: 10pt; font-family: &quot;Courier New&quot;; mso-no-proof: yes"> OnDone(<span style="color: blue">bool</span> done); </span></p>
<p class="MsoNormal" style="margin-bottom: 0pt; line-height: normal; mso-layout-grid-align: none"><span style="font-size: 10pt; color: blue; font-family: &quot;Courier New&quot;; mso-no-proof: yes"><span style="mso-spacerun: yes">&#160;&#160;&#160; </span>void</span><span style="font-size: 10pt; font-family: &quot;Courier New&quot;; mso-no-proof: yes"> OnValue(T value); </span></p>
<p class="MsoNormal" style="margin-bottom: 0pt; line-height: normal; mso-layout-grid-align: none"><span style="font-size: 10pt; font-family: &quot;Courier New&quot;; mso-no-proof: yes">} </span></p>
<p class="MsoNormal">But wait, that’s not quite right…the earlier definition for the enumerator had IDisposable in there somewhere, plus there was the implicit possibility of an exception being thrown by Current.Get (in the case where we’ve MoveNext’ed past the end of the enumerable). We still need to account for all the inputs and outputs when we do our reversal (henceforth called the <b style="mso-bidi-font-weight: normal">dual</b>), so how do we account for these? Well, it doesn’t make a lot of sense to have our callback thingy be disposable; but we can make the registration of that callback disposable…</p>
<p class="MsoNormal" style="margin-bottom: 0pt; line-height: normal; mso-layout-grid-align: none"><span style="font-size: 10pt; color: blue; font-family: &quot;Courier New&quot;; mso-no-proof: yes">interface</span><span style="font-size: 10pt; font-family: &quot;Courier New&quot;; mso-no-proof: yes"> <span style="color: #2b91af">IBackwardsEnumerable</span>&lt;T&gt; </span></p>
<p class="MsoNormal" style="margin-bottom: 0pt; line-height: normal; mso-layout-grid-align: none"><span style="font-size: 10pt; font-family: &quot;Courier New&quot;; mso-no-proof: yes">{ </span></p>
<p class="MsoNormal" style="margin-bottom: 0pt; line-height: normal; mso-layout-grid-align: none"><span style="font-size: 10pt; color: #2b91af; font-family: &quot;Courier New&quot;; mso-no-proof: yes"><span style="mso-spacerun: yes">&#160;&#160; </span>IDisposable</span><span style="font-size: 10pt; font-family: &quot;Courier New&quot;; mso-no-proof: yes"> Subscribe(<span style="color: #2b91af">IBackwardsEnumerator</span>&lt;T&gt; callbackLikeThing); </span></p>
<p class="MsoNormal" style="margin-bottom: 0pt; line-height: normal; mso-layout-grid-align: none"><span style="font-size: 10pt; font-family: &quot;Courier New&quot;; mso-no-proof: yes">} </span></p>
<p class="MsoNormal" style="margin-bottom: 0pt; line-height: normal; mso-layout-grid-align: none"><span style="font-size: 10pt; color: blue; font-family: &quot;Courier New&quot;; mso-no-proof: yes">interface</span><span style="font-size: 10pt; font-family: &quot;Courier New&quot;; mso-no-proof: yes"> <span style="color: #2b91af">IBackwardsEnumerator</span>&lt;T&gt; </span></p>
<p class="MsoNormal" style="margin-bottom: 0pt; line-height: normal; mso-layout-grid-align: none"><span style="font-size: 10pt; font-family: &quot;Courier New&quot;; mso-no-proof: yes">{ </span></p>
<p class="MsoNormal" style="margin-bottom: 0pt; line-height: normal; mso-layout-grid-align: none"><span style="font-size: 10pt; color: blue; font-family: &quot;Courier New&quot;; mso-no-proof: yes"><span style="mso-spacerun: yes">&#160;&#160; </span>void</span><span style="font-size: 10pt; font-family: &quot;Courier New&quot;; mso-no-proof: yes"> OnDone(<span style="color: blue">bool</span> done); </span></p>
<p class="MsoNormal" style="margin-bottom: 0pt; line-height: normal; mso-layout-grid-align: none"><span style="font-size: 10pt; color: blue; font-family: &quot;Courier New&quot;; mso-no-proof: yes"><span style="mso-spacerun: yes">&#160;&#160; </span>void</span><span style="font-size: 10pt; font-family: &quot;Courier New&quot;; mso-no-proof: yes"> OnError(<span style="color: #2b91af">Exception</span> error); </span></p>
<p class="MsoNormal" style="margin-bottom: 0pt; line-height: normal; mso-layout-grid-align: none"><span style="font-size: 10pt; color: blue; font-family: &quot;Courier New&quot;; mso-no-proof: yes"><span style="mso-spacerun: yes">&#160;&#160; </span>void</span><span style="font-size: 10pt; font-family: &quot;Courier New&quot;; mso-no-proof: yes"> OnValue(T value); </span></p>
<p class="MsoNormal" style="margin-bottom: 0pt; line-height: normal; mso-layout-grid-align: none"><span style="font-size: 10pt; font-family: &quot;Courier New&quot;; mso-no-proof: yes">} </span></p>
<p class="MsoNormal">Wait a second…this is starting to look a lot like an Asynchronous method call:</p>
<p class="MsoNormal" style="margin-bottom: 0pt; line-height: normal; mso-layout-grid-align: none"><span style="font-size: 10pt; color: blue; font-family: &quot;Courier New&quot;; mso-no-proof: yes">void</span><span style="font-size: 10pt; font-family: &quot;Courier New&quot;; mso-no-proof: yes"> AsyncMethod(T initialParameter, </span></p>
<p class="MsoNormal" style="margin-bottom: 0pt; line-height: normal; mso-layout-grid-align: none"><span style="font-size: 10pt; color: #2b91af; font-family: &quot;Courier New&quot;; mso-no-proof: yes"><span style="mso-spacerun: yes">&#160;&#160; </span>Action</span><span style="font-size: 10pt; font-family: &quot;Courier New&quot;; mso-no-proof: yes">&lt;T&gt; callback, </span></p>
<p class="MsoNormal" style="margin-bottom: 0pt; line-height: normal; mso-layout-grid-align: none"><span style="font-size: 10pt; font-family: &quot;Courier New&quot;; mso-no-proof: yes"><span style="mso-spacerun: yes">&#160;&#160; </span><span style="color: #2b91af">Action</span>&lt;<span style="color: #2b91af">Exception</span>&gt; fault, </span></p>
<p class="MsoNormal" style="margin-bottom: 0pt; line-height: normal; mso-layout-grid-align: none"><span style="font-size: 10pt; font-family: &quot;Courier New&quot;; mso-no-proof: yes"><span style="mso-spacerun: yes">&#160;&#160; </span><span style="color: #2b91af">Action</span> cancel); </span></p>
</p>
<p class="MsoNormal">The “callback” is what gets invoked when we have done some work (OnValue(T) above), the fault handler is invoked if we have a problem (OnError(Exception) above), and we have a way of stopping or cancelling the call in mid-process (OnDone(bool=true) above).</p>
<p class="MsoNormal">The similarities are not unusual – we’ve gone from a blocking-read type of operation (pulling values from an Enumerable collection) to a non-blocking write type of operation (asynchronously pushing values into a sort of stream).</p>
<p class="MsoNormal">Cool. So what the heck does all of that mean?</p>
<h2>Observations on Observation</h2>
<p class="MsoNormal">The Observer pattern (read your GOF!) is defined as: </p>
<p class="MsoNormal"><i style="mso-bidi-font-style: normal">“A software pattern in which an object, called the subject, maintains a list of its dependents, called observers, and notifies them automatically of any state changes, usually by calling one of their methods” </i></p>
<p class="MsoNormal">Looking back at the dual of the Enumerable pattern above, we can see that what we have derived is nothing more than the Observer pattern, in a slightly altered form. And so, we’ll call it as such:</p>
<p class="MsoNormal" style="margin-bottom: 0pt; line-height: normal; mso-layout-grid-align: none"><span style="font-size: 10pt; color: blue; font-family: &quot;Courier New&quot;; mso-no-proof: yes">interface</span><span style="font-size: 10pt; font-family: &quot;Courier New&quot;; mso-no-proof: yes"> <span style="color: #2b91af">IObservable</span>&lt;T&gt; </span></p>
<p class="MsoNormal" style="margin-bottom: 0pt; line-height: normal; mso-layout-grid-align: none"><span style="font-size: 10pt; font-family: &quot;Courier New&quot;; mso-no-proof: yes">{ </span></p>
<p class="MsoNormal" style="margin-bottom: 0pt; line-height: normal; mso-layout-grid-align: none"><span style="font-size: 10pt; color: #2b91af; font-family: &quot;Courier New&quot;; mso-no-proof: yes"><span style="mso-spacerun: yes">&#160;&#160;&#160; </span>IDisposable</span><span style="font-size: 10pt; font-family: &quot;Courier New&quot;; mso-no-proof: yes"> Subscribe(<span style="color: #2b91af">IObserver</span>&lt;T&gt; observer); </span></p>
<p class="MsoNormal" style="margin-bottom: 0pt; line-height: normal; mso-layout-grid-align: none"><span style="font-size: 10pt; font-family: &quot;Courier New&quot;; mso-no-proof: yes">} </span></p>
<p class="MsoNormal" style="margin-bottom: 0pt; line-height: normal; mso-layout-grid-align: none"><span style="font-size: 10pt; color: blue; font-family: &quot;Courier New&quot;; mso-no-proof: yes">interface</span><span style="font-size: 10pt; font-family: &quot;Courier New&quot;; mso-no-proof: yes"> <span style="color: #2b91af">IObserver</span>&lt;T&gt; </span></p>
<p class="MsoNormal" style="margin-bottom: 0pt; line-height: normal; mso-layout-grid-align: none"><span style="font-size: 10pt; font-family: &quot;Courier New&quot;; mso-no-proof: yes">{ </span></p>
<p class="MsoNormal" style="margin-bottom: 0pt; line-height: normal; mso-layout-grid-align: none"><span style="font-size: 10pt; color: blue; font-family: &quot;Courier New&quot;; mso-no-proof: yes"><span style="mso-spacerun: yes">&#160;&#160;&#160; </span>void</span><span style="font-size: 10pt; font-family: &quot;Courier New&quot;; mso-no-proof: yes"> OnDone(); </span></p>
<p class="MsoNormal" style="margin-bottom: 0pt; line-height: normal; mso-layout-grid-align: none"><span style="font-size: 10pt; font-family: &quot;Courier New&quot;; mso-no-proof: yes"><span style="mso-spacerun: yes">&#160;&#160;&#160; </span><span style="color: blue">void</span> OnError(<span style="color: #2b91af">Exception</span> error); </span></p>
<p class="MsoNormal" style="margin-bottom: 0pt; line-height: normal; mso-layout-grid-align: none"><span style="font-size: 10pt; color: blue; font-family: &quot;Courier New&quot;; mso-no-proof: yes"><span style="mso-spacerun: yes">&#160;&#160;&#160; </span>void</span><span style="font-size: 10pt; font-family: &quot;Courier New&quot;; mso-no-proof: yes"> OnNext(T value); </span></p>
<p class="MsoNormal" style="margin-bottom: 0pt; line-height: normal; mso-layout-grid-align: none"><span style="font-size: 10pt; font-family: &quot;Courier New&quot;; mso-no-proof: yes">} </span></p>
<p class="MsoNormal">The only change (other than renaming some things) is to remove the redundant Boolean value passed into OnDone – this is because the only time “OnDone” really matters is when that Boolean value is true. It doesn’t make a whole lot of sense to keep telling someone watching you work “I’m not done yet, I’m not done yet” when you can simply say “I’m done now”. </p>
<p class="MsoNormal">If this looks strangely like the way one would attach an event handler to a control &#8211; say, a button click &#8211; that’s because it’s basically the same thing, since a multi-cast delegate is pretty much an observer pattern condensed into a neat little package.</p>
<p class="MsoNormal">So we’ve proved, albeit in a rushed fashion, that the Observer pattern is the dual of the Enumerator pattern. We’ve also shown that it’s virtually identical to an asynchronous method call. We can also infer that it’s very similar to the way we would normally attach event handlers. </p>
<p class="MsoNormal">Whoop-de-do… What is the point? </p>
<p class="MsoNormal">Ever hear of LINQ?</p>
<h3>Coda: QNIL</h3>
<p class="MsoNormal">So LINQ does all its work with Enumerables. Using that same reasoning we went through above, a couple of very clever folks over at Microsoft created what is essentially “a dual of LINQ” – I rather like the idea of calling it QNIL (pronounced “Kyu-nil”), but as they are much smarter than I, I’ll use their terms and call it Rx – short for “Reactive framework”, but don’t ask me where they got the “x” from.</p>
<p class="MsoNormal"><a href="http://themechanicalbride.blogspot.com/2009/07/introducing-rx-linq-to-events.html">Introducing Rx LINQ to Events</a></p>
<p class="MsoNormal">Why is this cool? Observe, and I shall dazzle you:</p>
<p class="MsoNormal">Doing drag-and-drop is a pain. Every single time you implement it, you need to catch the initial mouse down event, set some internal flag to know it’s in a “dragging state”, attach some MouseMove handler to be able to determine where it’s being drug to, and then waiting for the next MouseUp event to come along so you can unhook your move handler, reset your internal state, and finally you’re done. </p>
<p class="MsoNormal">And you have to re-implement the same damned logic each time.</p>
<p class="MsoNormal">Let’s think about what we’re really trying to do. If Visual Studio understood English (Visual Studio 2014, perhaps?), I would say to it:</p>
<p class="MsoNormal">“If a user clicks on my control, listen for any mouse move events until the next mouse up event, and give those events to me so I can move my control where the user has moved the mouse.”</p>
<p class="MsoNormal">With Rx, it might be something like:</p>
<p class="MsoNormal" style="margin-bottom: 0pt; line-height: normal; mso-layout-grid-align: none"><span style="font-size: 10pt; color: #2b91af; font-family: &quot;Courier New&quot;; mso-no-proof: yes">IObservable</span><span style="font-size: 10pt; font-family: &quot;Courier New&quot;; mso-no-proof: yes">&lt;<span style="color: #2b91af">Event</span>&lt;<span style="color: #2b91af">MouseEventArgs</span>&gt;&gt; draggingEvent = </span></p>
<p class="MsoNormal" style="margin-bottom: 0pt; line-height: normal; mso-layout-grid-align: none"><span style="font-size: 10pt; color: blue; font-family: &quot;Courier New&quot;; mso-no-proof: yes"><span style="mso-spacerun: yes">&#160;&#160;&#160; </span>from</span><span style="font-size: 10pt; font-family: &quot;Courier New&quot;; mso-no-proof: yes"> mouseLeftDownEvent <span style="color: blue">in</span> </span></p>
<p class="MsoNormal" style="margin-bottom: 0pt; line-height: normal; mso-layout-grid-align: none"><span style="font-size: 10pt; font-family: &quot;Courier New&quot;; mso-no-proof: yes"><span style="mso-spacerun: yes">&#160;&#160;&#160;&#160;&#160;&#160;&#160; </span>ctl.GetMouseLeftDown() </span></p>
<p class="MsoNormal" style="margin-bottom: 0pt; line-height: normal; mso-layout-grid-align: none"><span style="font-size: 10pt; font-family: &quot;Courier New&quot;; mso-no-proof: yes"><span style="mso-spacerun: yes">&#160;&#160;&#160; </span><span style="color: blue">from</span> mouseMoveEvent <span style="color: blue">in</span> </span></p>
<p class="MsoNormal" style="margin-bottom: 0pt; line-height: normal; mso-layout-grid-align: none"><span style="font-size: 10pt; font-family: &quot;Courier New&quot;; mso-no-proof: yes"><span style="mso-spacerun: yes">&#160;&#160;&#160;&#160; </span><span style="mso-spacerun: yes">&#160;&#160; </span>ctl.GetMouseMove() </span></p>
<p class="MsoNormal" style="margin-bottom: 0pt; line-height: normal; mso-layout-grid-align: none"><span style="font-size: 10pt; font-family: &quot;Courier New&quot;; mso-no-proof: yes"><span style="mso-spacerun: yes">&#160;&#160;&#160;&#160;&#160;&#160;&#160; </span>.Until(ctl.GetMouseLeftUp()) </span></p>
<p class="MsoNormal" style="margin-bottom: 0pt; line-height: normal; mso-layout-grid-align: none"><span style="font-size: 10pt; color: blue; font-family: &quot;Courier New&quot;; mso-no-proof: yes"><span style="mso-spacerun: yes">&#160;&#160;&#160; </span>select</span><span style="font-size: 10pt; font-family: &quot;Courier New&quot;; mso-no-proof: yes"> mouseMoveEvent; </span></p>
<p class="MsoNormal" style="margin-bottom: 0pt; line-height: normal; mso-layout-grid-align: none"><span style="font-size: 10pt; font-family: &quot;Courier New&quot;; mso-no-proof: yes">draggingEvent.Subscribe( </span></p>
<p class="MsoNormal" style="margin-bottom: 0pt; text-indent: 0.5in; line-height: normal; mso-layout-grid-align: none"><span style="font-size: 10pt; font-family: &quot;Courier New&quot;; mso-no-proof: yes">(moveEvent) =&gt; </span></p>
<p class="MsoNormal" style="margin-bottom: 0pt; text-indent: 0.5in; line-height: normal; mso-layout-grid-align: none"><span style="font-size: 10pt; font-family: &quot;Courier New&quot;; mso-no-proof: yes">{ ctl.MoveTo(moveEvent.X, moveEvent.Y);}) </span></p>
<p class="MsoNormal" style="margin-bottom: 0pt; line-height: normal; mso-layout-grid-align: none"><span style="font-size: 10pt; font-family: &quot;Courier New&quot;; mso-no-proof: yes"></span></p>
<p class="MsoNormal" style="margin-bottom: 0pt; line-height: normal; mso-layout-grid-align: none">
<p><span style="font-size: 10pt; font-family: &quot;Courier New&quot;; mso-no-proof: yes"></span></p>
<p><span style="font-size: 10pt; font-family: &quot;Courier New&quot;; mso-no-proof: yes"></span></p>
</p>
<p class="MsoNormal"><span style="mso-no-proof: yes">And that, dear reader, is just plain cool. </span></p>
]]></content:encoded>
			<wfw:commentRss>http://blog.lab49.com/archives/3252/feed</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Differentiating Types in Haskell</title>
		<link>http://blog.lab49.com/archives/3027</link>
		<comments>http://blog.lab49.com/archives/3027#comments</comments>
		<pubDate>Sun, 26 Apr 2009 13:54:42 +0000</pubDate>
		<dc:creator>Kalani Thielen</dc:creator>
				<category><![CDATA[Computer Science]]></category>
		<category><![CDATA[Conversations in the Lab]]></category>
		<category><![CDATA[F#]]></category>
		<category><![CDATA[Functional Programming]]></category>
		<category><![CDATA[Haskell]]></category>
		<category><![CDATA[Logic]]></category>

		<guid isPermaLink="false">http://blog.lab49.com/archives/3027</guid>
		<description><![CDATA[In the last article, we explored the concept of data-types as algebraic expressions, and the idea that the derivative of these expressions produces their type of one-hole contexts.&#160; This &#8220;leap of logic&#8221; gives us a firm foundation for purely-functional incremental mutation, and (more generally) proof that there are interesting things happening at the level of [...]]]></description>
			<content:encoded><![CDATA[<p>In <a href="http://blog.lab49.com/archives/3011">the last article</a>, we explored the concept of data-types as algebraic expressions, and the idea that the derivative of these expressions produces their type of one-hole contexts.&nbsp; This &#8220;leap of logic&#8221; gives us a firm foundation for <a href="http://blog.lab49.com/archives/2984">purely-functional incremental mutation</a>, and (more generally) proof that there are interesting things happening at the level of types!</p>
<p>Still, many good ideas are destroyed (or exalted) when the time comes to make a real program out of them.&nbsp; So in this article, we will write that program, and in the process shore up this notion of a derivative by defining it over any recursive type.</p>
<p><span id="more-3027"></span></p>
<p><strong>Defining the Derivative</strong></p>
<p>In <a href="http://www.cs.nott.ac.uk/~ctm/diff.pdf">his paper first exploring this topic</a>, Conor McBride determines the six laws for differentiating data types, roughly as follows:</p>
<table cellspacing="2" cellpadding="2" width="444" border="0">
<tbody>
<tr>
<td valign="top" width="164"><font face="Courier New">1. ∂x(x)</font></td>
<td valign="top" width="272"><font face="Courier New">1</font></td>
</tr>
<tr>
<td valign="top" width="164"><font face="Courier New">2. ∂x(T) where <font face="Courier New">x <font face="Symbol">Ï</font> T</font></font></td>
<td valign="top" width="272"><font face="Courier New">0</font></td>
</tr>
<tr>
<td valign="top" width="164"><font face="Courier New">3. ∂x(S + T)</font></td>
<td valign="top" width="272"><font face="Courier New">∂x(S) + ∂x(T)</font></td>
</tr>
<tr>
<td valign="top" width="164"><font face="Courier New">4. ∂x(S * T)</font></td>
<td valign="top" width="272"><font face="Courier New">∂x(S) * T + S * ∂x(T)</font></td>
</tr>
<tr>
<td valign="top" width="164"><font face="Courier New">5. ∂x(μy.F)</font></td>
<td valign="top" width="272"><font face="Courier New">μz.((∂x(F)|y=μ y.F)+(∂y(F)|y=μy.F)*z)</font></td>
</tr>
<tr>
<td valign="top" width="164"><font face="Courier New">6. ∂x(F|y=S)</font></td>
<td valign="top" width="272"><font face="Courier New">(∂x(F)|y=S) + (∂y(F)|y=S) * ∂x(S)</font></td>
</tr>
</tbody>
</table>
<p>This table is slightly more complicated than the rosy picture painted by the last article.&nbsp; Before getting into the details of this definition, it&#8217;s worth pointing out one of the important things done here with recursive types.&nbsp; We&#8217;ll need to distinguish between a recursive type, <font face="Courier New">μ y.F</font> , and its one-step unrolling, <font face="Courier New">F|y=S</font> (see the left column of rules 5 and 6).&nbsp; Our previous definition of recursive types still applies, but instead of informally saying that a recursive type defines an infinite expansion by repeated substitution, we capture a single-step of substitution in this new form.</p>
<p>Also, this point was slightly glossed over in the last article, it should be pointed out that for typical data-types, we&#8217;re actually interested in the <strong><em>partial</em></strong> derivative.&nbsp; In the definition above, <font face="Courier New">∂x(T)</font> means the partial derivative of T with respect to x, and <font face="Courier New">∂y(T)</font> means the partial derivative with respect to y.&nbsp; Likewise, when we use <font face="Courier New">∂x(T)</font> we are <em>poking an x-hole</em> in T (i.e.: we&#8217;re finding one x in T to single out).</p>
<p>The first four rules are just the same rules as in Calculus, but it&#8217;s instructive to informally consider what they mean in the context of types.&nbsp; The first rule says that poking an x-hole in just the single variable x produces the unit type (this also tells us that holes have the unit type, perhaps a subtle point that was not made in the last article).&nbsp; The second rule says that poking an x-hole in any type where x is not mentioned produces the void type (i.e.: you can&#8217;t poke a hole in an x that isn&#8217;t there).&nbsp; The third rule says that if you have a type that could either be an S or a T, then poking an x-hole in this type produces a type that&#8217;s either an S with an x-hole or a T with an x-hole.&nbsp; And the fourth rule says that poking an x-hole in a pair of an S and a T is either an S with an x-hole and a T (left intact), or it&#8217;s an S (left intact) and a T with an x-hole &#8212; in other words, in a pair, the hole is either in the first or the second value.</p>
<p>In other words, rules 3 and 4 are just the normal sum and product rules of Differential Calculus (respectively) and rules 1 and 2 are the regular base cases of differentiation (for the differentiated variable, or a constant &#8212; respectively).</p>
<p>So what explains rules 5 and 6?&nbsp; These are two sides of the <a href="http://en.wikipedia.org/wiki/Chain_rule">plain old chain rule</a>.&nbsp; It&#8217;s (arguably) easiest to make this case for rule 6, so let&#8217;s repeat it for reference:</p>
<table cellspacing="2" cellpadding="2" width="354" border="0">
<tbody>
<tr>
<td valign="top" width="85"><font face="Courier New">∂x(F|y=S) :</font></td>
<td valign="top" width="261"><font face="Courier New">(∂x(F)|y=S) + (∂y(F)|y=S) * ∂x(S)</font></td>
</tr>
</tbody>
</table>
<p>Now consider the definition of the chain rule for partial derivatives:</p>
<p><font face="Courier New">For z = f(u, v)</font><br /><font face="Courier New">∂z/<font face="Courier New">∂</font>x = (<font face="Courier New">∂</font>f/<font face="Courier New">∂</font>u)*(<font face="Courier New">∂</font>u/<font face="Courier New">∂</font>x) + (<font face="Courier New">∂</font>f/<font face="Courier New">∂</font>v)*(<font face="Courier New">∂</font>v/<font face="Courier New">∂</font>x)</font></p>
<p>This definition looks almost identical to rule 6, except that in this case the left side of the sum (<font face="Courier New">∂x(F)|y=S</font>) is just <font face="Courier New">∂f/∂x</font>.</p>
<p>The connection is a little more obscure in rule 5:</p>
<table cellspacing="2" cellpadding="2" width="416" border="0">
<tbody>
<tr>
<td valign="top" width="90"><font face="Courier New">∂x(μ y.F) :</font></td>
<td valign="top" width="318"><font face="Courier New">μ z.((∂x(F)|y=μ y.F) + (∂y(F)|y=μ y.F) * z)</font></td>
</tr>
</tbody>
</table>
<p>Here we actually have the same structure as in rule 6, except that we see &#8220;z&#8221; where the chain rule tells us to expect <font face="Courier New">∂v/∂x</font>.&nbsp; Informally, this anomaly is resolved by recognizing that &#8220;z&#8221; (representing the infinite expansion of the entire recursive type) is in fact <font face="Courier New">∂v/∂x</font>.</p>
<p>Let&#8217;s try a non-trivial example to develop some intuition for this method before we set out to write the differentiation program.&nbsp; Consider the recursive type of lists of integers:</p>
<p><font face="Courier New">μ X.(1+int*X)</font></p>
<p>And we will want to poke an int-hole, so we&#8217;re going to find:</p>
<p><font face="Courier New">∂int(</font><font face="Courier New">μ X.(1+int*X))</font></p>
<p>By rule #5 (and given that &#8220;y&#8221; from rule #5 matches &#8220;X&#8221; in our expression, and &#8220;F&#8221; from rule #5 matches &#8220;1+int*X&#8221; in our expression), this becomes:</p>
<p><font face="Courier New">μz.((∂int(1+int*X)|X=μX.1+int*X)+(∂X(1+int*X)|X=μX.1+int*X)*z)</font></p>
<p>Yikes!&nbsp; There&#8217;s a lot going on there, but perhaps we can break this problem into easier pieces by a couple of choice substitutions.&nbsp; Since this is just a recursive type with a sum in it, let&#8217;s choose a couple of variables to represent both sides of the sum:</p>
<p><font face="Courier New">μz.(U+V*z)<br />where<br />&nbsp;&nbsp; U = ∂int(1+int*X)|X=(μX.1+int*X)<br />&nbsp;&nbsp; V = ∂X(1+int*X)|X=(μX.1+int*X)</font></p>
<p>Now we can evaluate U and V independently.&nbsp; First let&#8217;s consider U:</p>
<p><font face="Courier New">∂int(1+int*X)|X=(μX.1+int*X)</font></p>
<p>By rule #3 (the sum rule) this becomes:</p>
<p><font face="Courier New">(∂int(1)+<font face="Courier New">∂int(</font>int*X))|X=(μX.1+int*X)</font></p>
<p>Now we have two derivatives to evaluate.&nbsp; First the one on the left becomes 0 (by rule #2) and we can eliminate it:</p>
<p><font face="Courier New"><font face="Courier New">∂int(</font>int*X)|X=(μX.1+int*X)</font></p>
<p>Then by rule #4 (the product rule) this last derivative becomes:</p>
<p><font face="Courier New">(∂int(int) * X + int * ∂int(X))|X=(μX.1+int*X)</font></p>
<p>Now we&#8217;re almost done.&nbsp; Here we have one more sum, and the derivative on the left becomes 1 (by rule #1), leaving a lone X:</p>
<p><font face="Courier New">(X + int * ∂int(X))|X=(μX.1+int*X)</font></p>
<p>And the derivative on the right becomes 0 (by rule #2), which means that the right side of the sum can be eliminated.&nbsp; Therefore we have solved &#8220;U&#8221;:</p>
<p><font face="Courier New">U = X|X=(μX.1+int*X)</font></p>
<p>Now, since we&#8217;re done, we could substitute for X here to eliminate the redundant context:</p>
<p><font face="Courier New">U = μX.(1+int*X)</font></p>
<p>In other words, U is a list of ints.&nbsp; Now we must solve V (the trickier side of the chain rule, where we switch to poking an int-list hole rather than an int-hole):</p>
<p><font face="Courier New">∂X(1+int*X)|X=(μX.1+int*X)</font></p>
<p>By rule #3, this becomes:</p>
<p><font face="Courier New">∂X(1)+<font face="Courier New">∂X(</font>int*X)|X=(μX.1+int*X)</font></p>
<p>Here the left side of the sum is eliminated (by rule #2) and the right side is elaborated (by rule #4) becoming:</p>
<p><font face="Courier New"><font face="Courier New">(∂X(int) * X + int * ∂X(X))|X=(μX.1+int*X)</font></font></p>
<p>Now the left side of the sum is eliminated (by rule #2), and the right side just simplifies to int (by rule #1), so that we&#8217;ve also now solved for V:</p>
<p><font face="Courier New"><font face="Courier New">V = int|X=(μX.1+int*X)</font></font></p>
<p>In fact, we don&#8217;t need this trailing context information anymore (since &#8220;X&#8221; doesn&#8217;t appear in the simple type variable &#8220;int&#8221;, we don&#8217;t need to remember how to substitute &#8220;X&#8221;), so we can simply say:</p>
<p><font face="Courier New"><font face="Courier New">V = int</font></font></p>
<p>Now, substituting U and V back into our original solution for the derivative of a list of ints, this becomes:</p>
<p><font face="Courier New">μz.((μX.(1+int*X))+int*z)</font></p>
<p>To help us make some sense of this answer, it&#8217;s useful to observe that the following identity holds:</p>
<p><font face="Courier New">μ a.(T+S*a) = list&lt;S&gt; * T</font></p>
<p>We know this to be true in the normal case of lists &#8212; because in that case T = 1 (and list&lt;S&gt;*1 = list&lt;S&gt;).&nbsp; But if we apply this identity to the answer we&#8217;ve derived, we can conclude that the derivative of a list of ints is a pair of lists of ints (which makes sense &#8212; the first list is the prefix up to the hole, and the second list is the suffix following the hole).&nbsp; In fact, it&#8217;s a good thing that we derived this answer, because we&#8217;ve <a href="http://blog.lab49.com/archives/2984">already made use of</a> it!</p>
<p>Now, assuming that we&#8217;re satisfied with this differentiation procedure, all that&#8217;s left is to actually implement it in a real program.</p>
<p><strong>A Brief Haskell Program</strong></p>
<p>The first thing that we need to do is set down a data structure that represents types.&nbsp; The circularity of this definition may seem odd (we&#8217;re defining a data type for structures that represent data types), but because we&#8217;ve already covered in detail the forms that types can take, it shouldn&#8217;t be very surprising:</p>
<p><font face="Courier New">data Type =<br />&nbsp;&nbsp; Ty String<br />| Sum (Type, Type)<br />| Prod (Type, Type)<br />| Fix (String, Type)<br />| FApp (Type, String, Type) deriving Eq</font>
<p>Stated plainly, a type is a type variable (e.g.: int, string, date, unit, void, etc), or the sum of two types, or the product of two types, or a recursive type, or the one-step unrolling of a recursive type.</p>
<p>For convenience, we can define a function to display these type structures conveniently (and consistent with the notation we&#8217;ve developed so far):</p>
<p><font face="Courier New">instance Show Type where<br />show (Ty &#8220;unit&#8221;)&nbsp;&nbsp;&nbsp;&nbsp; =&#8221;1&#8243;<br />show (Ty &#8220;void&#8221;)&nbsp;&nbsp;&nbsp;&nbsp; =&#8221;0&#8243;<br />show (Ty v)&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; =v<br />show (Sum&nbsp; (t1, t2)) =(show t1)++&#8221;+&#8221;++(show t2)<br />show (Prod (t1, t2)) =(show t1)++&#8221;*&#8221;++(show t2)<br />show (Fix&nbsp; (v,&nbsp; ty)) =&#8221;mu &#8220;++v++&#8221;.&#8221;++(show ty)<br />show (FApp (t, x, s))=&#8221;["++(show t)++"|"++x++"="++(show s)++"]&#8220;</font>
<p>This way, if we enter an interesting type at the Haskell prompt (like the recursive type of lists of integers), we should see it in the shorthand we&#8217;ve developed:</p>
<p><font face="Courier New">Prelude&gt; Fix (&#8220;X&#8221;, Sum (Ty &#8220;unit&#8221;, Prod (Ty &#8220;int&#8221;, Ty &#8220;X&#8221;)))<br />mu X.1+int*X</font></p>
<p>Finally, we can define a &#8220;derivative&#8221; function on types with respect to a particular type-variable by explicitly translating each of the 6 rules we&#8217;ve considered above.&nbsp; First rule #1:</p>
<p><font face="Courier New">derivative (Ty v) x | x == v = Ty &#8220;unit&#8221;</font>
<p>Then rule #2 (a type other than x):
<p><font face="Courier New">derivative (Ty v) x = Ty &#8220;void&#8221;</font>
<p>Then rule #3 (the rule for sums):
<p><font face="Courier New">derivative (Sum&nbsp; (t1, t2)) x = Sum (derivative t1 x, derivative t2 x)</font>
<p>And rule #4, for products:
<p><font face="Courier New">derivative (Prod (t1, t2))&nbsp;&nbsp; x = Sum (Prod (derivative t1 x, t2), Prod (t1, derivative t2 x))</font>
<p>Rule #5 (assuming for the moment that we have a function <font face="Courier New">unique_name</font> to choose a unique type-variable name that does not appear in a particular type expression):
<p><font face="Courier New">derivative rty@(Fix (v, ty)) x =<br />&nbsp;&nbsp; let z = unique_name rty in<br />&nbsp;&nbsp; let dt_dx = derivative ty x in<br />&nbsp;&nbsp; let dt_dv = derivative ty v in<br />&nbsp;&nbsp;&nbsp;&nbsp; Fix (z,<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; Sum (<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; FApp (dt_dx, v, rty),<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; Prod (FApp (dt_dv, v, rty), Ty z)))</font>
<p>And finally rule #6:
<p><font face="Courier New">derivative (FApp (t, y, s))&nbsp; x =<br />&nbsp;&nbsp;&nbsp; let dt_dx = derivative t x in<br />&nbsp;&nbsp;&nbsp; let dt_dy = derivative t y in<br />&nbsp;&nbsp;&nbsp; let ds_dx = derivative s x in<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; Sum (FApp(dt_dx, y, s), Prod (FApp (dt_dy, y, s), ds_dx))</font>
<p>Now, as a question of correctness, we have finished this problem &#8212; we have a Haskell program that can compute derivatives of types (modulo the definition of this <font face="Courier New">unique_name</font> function).&nbsp; However, as in the normal differential calculus, the terms we produce can be a little messy &#8212; with lots of 1*X and X+0 hanging around.&nbsp; There can also be unnecessary recursive types (where the recursion variable is not mentioned in the body of the recursive type), and those should be eliminated as well.
<p>The simplest approach is probably to define the single-step simplification of a type expression:
<p><font face="Courier New">simplify (Sum&nbsp; (Ty &#8220;void&#8221;, x))= simplify x<br />simplify (Sum&nbsp; (x, Ty &#8220;void&#8221;))= simplify x<br />simplify (Sum&nbsp; (x, y))&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; = Sum (simplify x, simplify y)<br />simplify (Prod (Ty &#8220;void&#8221;, x))= Ty &#8220;void&#8221;<br />simplify (Prod (x, Ty &#8220;void&#8221;))= Ty &#8220;void&#8221;<br />simplify (Prod (Ty &#8220;unit&#8221;, x))= simplify x<br />simplify (Prod (x, Ty &#8220;unit&#8221;))= simplify x<br />simplify (Prod (x, y))&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; = Prod (simplify x, simplify y)<br />simplify (Fix&nbsp; (v, ty))&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; | not (v `member` names ty) = ty<br />simplify (Fix&nbsp; (v, ty))&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; = Fix (v, simplify ty)<br />simplify (FApp (t, y, s))&nbsp;&nbsp;&nbsp;&nbsp; | not (y `member` names t) = t<br />simplify (FApp (t, y, s))&nbsp;&nbsp;&nbsp;&nbsp; = FApp (simplify t, y, simplify s)<br />simplify x&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; = x</font>
<p>Then, given that we can perform a single step of simplification to a term (keep in mind, one 0*X becoming 0 could propagate into a new 0*Y, as in the expression Y*(0*X)), we can <strong><em>completely</em></strong> simplify a term by the fixed-point of this process:
<p><font face="Courier New">fixed_point f x | x == (f x) = x<br />fixed_point f x&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; = fixed_point f (f x) </font>
<p><font face="Courier New">csimplify x = fixed_point simplify x</font>
<p>Also, because the way we display these types loses some grouping information (the type &#8220;int*(string+date)&#8221; is actually printed &#8220;int*string+date&#8221;, which is actually a different type!) we should probably flatten types (e.g.: converting &#8220;int*(string+date)&#8221; to &#8220;int*string + int*date&#8221;):
<p><font face="Courier New">flatten ty = distribute Nothing ty<br />where<br />&nbsp; distribute Nothing t@(Ty _) = t<br />&nbsp; distribute (Just lty) t@(Ty _) = Prod (lty, t)<br />&nbsp; distribute mlty (Sum (t1, t2)) = Sum (distribute mlty t1, distribute mlty t2)<br />&nbsp; distribute mlty (Prod (t1, t2)) = distribute (Just (distribute mlty t1)) t2<br />&nbsp; distribute Nothing (Fix (v, ty)) = Fix (v, distribute Nothing ty)<br />&nbsp; distribute (Just lty) <a href="mailto:t@(Fix">t@(Fix</a> (v, ty)) = Prod (lty, distribute Nothing t)<br />&nbsp; distribute Nothing (FApp (t, x, s)) = FApp (distribute Nothing t, x, distribute Nothing s)<br />&nbsp; distribute (Just lty) t@(FApp (f, x, s)) = Prod (lty, distribute Nothing t)</font>
<p>Finally we can package all of these niceties on top of the &#8220;derivative&#8221; function into a single definition:
<p><font face="Courier New">d ty x = flatten (csimplify (derivative ty x))</font>
<p>For convenience, <a href="http://blog.lab49.com/wp-content/uploads/2009/04/dtype.txt">I&#8217;ve prepared a script</a> &#8212; please rename it to dtype.hs, somehow our weblog software thinks that *.hs files are insecure &#8212; which contains all of these definitions (along with several utility functions, like <font face="Courier New">unique_name</font>, which are necessary but not vital to the understanding of this differentiation procedure).&nbsp; Provided that you have GHC installed, you can load the script like this:
<p><font face="Courier New">&gt; ghci dtype.hs</font>
<p>We can then test it out on two types whose one-hole contexts we&#8217;ve <a href="http://blog.lab49.com/archives/2984">already made use of</a>.&nbsp; First the derivative of a list:
<p><font face="Courier New">Prelude&gt; d (Fix (&#8220;X&#8221;, Sum (Ty &#8220;unit&#8221;, Prod (Ty &#8220;int&#8221;, Ty &#8220;X&#8221;)))) &#8220;int&#8221;<br />mu a.[X|X=mu X.1+int*X]+int*a</font>
<p>Also we can take the derivative of a binary tree:
<p><font face="Courier New">Prelude&gt; d (Fix (&#8220;X&#8221;, Sum (Ty &#8220;int&#8221;, Prod (Ty &#8220;X&#8221;, Ty &#8220;X&#8221;)))) &#8220;int&#8221;<br />mu a.1+[X+X|X=mu X.int+X*X]*a</font>
<p>Again, using the list identity and the observation that X is the type of binary trees of ints, this tells us that the derivative of a binary tree is a list of a binary tree or a binary tree (either the left or right branch passed on the path from the hole in the tree to the root of the tree).</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.lab49.com/archives/3027/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>The Algebra of Data, and the Calculus of Mutation</title>
		<link>http://blog.lab49.com/archives/3011</link>
		<comments>http://blog.lab49.com/archives/3011#comments</comments>
		<pubDate>Sun, 19 Apr 2009 04:02:56 +0000</pubDate>
		<dc:creator>Kalani Thielen</dc:creator>
				<category><![CDATA[Computer Science]]></category>
		<category><![CDATA[Conversations in the Lab]]></category>
		<category><![CDATA[F#]]></category>
		<category><![CDATA[Featured Posts]]></category>
		<category><![CDATA[Functional Programming]]></category>
		<category><![CDATA[General Development]]></category>
		<category><![CDATA[Haskell]]></category>
		<category><![CDATA[Logic]]></category>

		<guid isPermaLink="false">http://blog.lab49.com/archives/3011</guid>
		<description><![CDATA[With the spreading popularity of languages like F# and Haskell, many people are encountering the concept of an algebraic data type for the first time.&#160; When that term is produced without explanation, it almost invariably becomes a source of confusion.&#160; In what sense are data types algebraic?&#160; Is there a one-to-one correspondence between the structures [...]]]></description>
			<content:encoded><![CDATA[<p>With the spreading popularity of languages like F# and Haskell, many people are encountering the concept of an <a href="http://en.wikipedia.org/wiki/Algebraic_data_type">algebraic data type</a> for the first time.&nbsp; When that term is produced without explanation, it almost invariably becomes a source of confusion.&nbsp; In what sense are data types algebraic?&nbsp; Is there a one-to-one correspondence between the structures of high-school algebra and the data types of Haskell?&nbsp; Could I create a polynomial data type?&nbsp; Do I have to remember the quadratic formula?&nbsp; Are the term-transformations of (say) differential calculus meaningful in the context of algebraic data types?&nbsp; Isn&#8217;t this all just a bunch of general abstract nonsense?</p>
<p>We&#8217;ll investigate these questions, and perhaps demystify this important concept of functional languages.</p>
<p><span id="more-3011"></span></p>
<p><strong>Algebraic Expressions at the Level of Types</strong></p>
<p>To understand the concept of algebraic data types, simply stated, we need to unify the set of concepts that we associate with algebra, and the set of concepts that we associate with data types.</p>
<p>In an algebraic expression, we might encounter a humble lone variable:</p>
<p><font face="Courier New">x</font></p>
<p>In a <em>data type expression</em>, we might encounter a humble lone type:</p>
<p><font face="Courier New">int</font></p>
<p>Algebraic expressions can also be compositions of other expressions, so for example we might see:</p>
<p><font face="Courier New">x*x</font></p>
<p>And similarly for data types:</p>
<p><font face="Courier New">int*int</font></p>
<p>To explain: the <em>product </em>of two types denotes the type of pairs of those types.&nbsp; In some languages, this might instead be written as <font face="Courier New">pair&lt;int,int&gt;</font> but as we&#8217;ll soon see, it&#8217;s useful to think of this as a product.</p>
<p>Of course, the algebraic expression above could be simplified to <font face="Courier New">x**2</font> (&#8220;x squared&#8221;) and so you could also write <font face="Courier New">int**2</font>.</p>
<p>Now, in an algebraic expression you might also see:</p>
<p><font face="Courier New">x+x</font></p>
<p>And the same concept exists for data types:</p>
<p><font face="Courier New">int+int</font></p>
<p>The <em>sum</em> of two types denotes the type of <strong>variants</strong> which can have values either of the left type or the right (but not both).&nbsp; The sum in the above type might seem superfluous, because whether a value of the above sum type has the left or the right type, it&#8217;ll be an <font face="Courier New">int</font>.&nbsp; However, there&#8217;s some additional useful information in knowing whether the left or right was chosen.</p>
<p>Consider, for example, a data type representing the balance of a bank account:</p>
<p><font face="Courier New">type balance = int + int</font></p>
<p>We might interpret values on the left as <em>positive</em> balances, and values on the right as <em>negative<strong> </strong></em>balances.&nbsp; So if we wrote a function to describe a balance for screen-reading, it might look like:</p>
<p><font face="Courier New">string describe(balance b) {<br />&nbsp;&nbsp; if (b.is_left()) {<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; return &#8220;The bank owes you $&#8221; + b.left();<br />&nbsp;&nbsp; } else {<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; return &#8220;You owe the bank $&#8221; + b.right();<br />&nbsp;&nbsp; }<br />}</font></p>
<p>For many people, sum types are less obvious than product types.&nbsp; It may help to consider that, just as <font face="Courier New">pair&lt;int,int&gt;</font> corresponds to product types, <font face="Courier New"><a href="http://www.boost.org/doc/libs/1_38_0/doc/html/variant.html">boost::variant&lt;int,int&gt;</a></font> corresponds to sum types.&nbsp; C-style unions also serve a similar function.</p>
<p>Now, we can use these type-composition functions to make arbitrarily complex expressions:</p>
<p><font face="Courier New">(int*int*string)+(date*(string+int))</font></p>
<p>Just as we could use them to make arbitrarily complex algebraic expressions:</p>
<p><font face="Courier New">(x*x*y)+(z*(y+x))</font></p>
<p>But there is perhaps a simpler algebraic concept to consider:</p>
<p><font face="Courier New">1</font></p>
<p>What does the natural number &#8220;one&#8221; mean at the level of types?&nbsp; This is called the &#8220;unit type&#8221; and it has only one value, written <font face="Courier New">()</font>.&nbsp; It doesn&#8217;t do much good to have a value of the unit type &#8212; you already know what it must be.&nbsp; However, it can become useful in composition, for example if you consider the simple identity:</p>
<p><font face="Courier New">1+1=2</font></p>
<p>Now &#8220;two&#8221; becomes the type of <strong>bits</strong> (or <em>boolean</em> values) &#8212; because a value of this type could either be the (trivial) unit value on the left, or the one on the right.&nbsp; This view may help to understand variant types better, consider:</p>
<p><font face="Courier New">int+int = 2*int</font></p>
<p>In other words, the <em>sum type</em> of two <font face="Courier New">int</font>s is the same thing as the <em>product type</em> of a boolean value and a single <font face="Courier New">int</font> (the boolean value tells you whether the <font face="Courier New">int</font> is the one on the left or the right of the sum).</p>
<p>Furthermore, as you might expect:</p>
<p><font face="Courier New">1*int = int</font></p>
<p>In other words, having a pair of a unit value and an <font face="Courier New">int</font> is the same as having an <font face="Courier New">int</font> (the unit value adds no information here &#8212; you already know what it must be).</p>
<p>Now there&#8217;s one other natural number that deserves special consideration:</p>
<p><font face="Courier New">0</font></p>
<p>This is a special kind of type &#8212; it&#8217;s known as the &#8220;void&#8221; type (slightly different than the void type in programming languages like C, you&#8217;ll have to forgive this overloading of terms).&nbsp; Unlike the unit type, which has a single value, the void type <em>has no values</em>.&nbsp; It&#8217;s impossible to construct a value of this type.</p>
<p>That means, for example, that:</p>
<p><font face="Courier New">1+0=1</font></p>
<p>Because if you have a sum type with unit on the left and void on the right, no values of this type can possibly be on the right (again, it&#8217;s impossible to construct a value of the void type) &#8212; so it&#8217;s safe to assume that you can simplify this sum type to just be the unit type.</p>
<p>By a similar argument:</p>
<p><font face="Courier New">1*0=0</font></p>
<p>Because to construct a pair, you have to construct both of its members &#8212; if you can&#8217;t construct one member of the pair (again, it&#8217;s impossible to construct a value of the void type) then you can&#8217;t construct the whole pair.</p>
<p>Now, these types that we&#8217;ve covered so far are quite useful, and it&#8217;s hopefully pretty clear how they map to simple algebraic expressions.&nbsp; However, it might be pointed out that there are more complex types, and more complex algebraic expressions to consider (even though the expressions above can get quite complex).</p>
<p>For example, how might the type of a list of integers be described (a <font face="Courier New">list&lt;int&gt;</font>) as an algebraic expression?&nbsp; To help motivate this answer, consider the possible lists of integers we might produce.&nbsp; For example, a list of integers could be an empty list, or it might be just one integer, or it might be two, or three, etc.&nbsp; Each &#8220;or&#8221; here should be thought of as a sum, so that (with the unit type representing the trivial empty list) we come to a type represented by an infinite sum:</p>
<p><font face="Courier New">1+int+int**2+int**3+&#8230;+int**n</font></p>
<p>Now, as an algebraic expression we might be happy with this, or we might convert it to the &#8220;big-sigma&#8221; notation.&nbsp; However, in the world of types, this kind of infinite expansion is described with a <em>recursive type</em>.&nbsp; A recursive type associates the expansion with a symbol and consolidates the type to an expression where that symbol may be used.&nbsp; For the case of our list of <font face="Courier New">int</font>s, this is written:</p>
<p><font face="Courier New">μX.(1+int*X)</font></p>
<p>This can be pronounced &#8220;mu X, one plus int times X.&#8221;&nbsp; Forget the &#8220;mu&#8221; if Greek symbols bother you; all it really means is &#8220;look out, here comes a recursive type.&#8221;&nbsp; The most important idea is that the type should be thought of as the infinite expansion you get when you repeatedly substitute the entire recursive type for X (the recursion variable).&nbsp; For example, performing that substitution once in the above type will produce:</p>
<p><font face="Courier New">1+int*(μX.(1+int*X))</font></p>
<p>and again:</p>
<p><font face="Courier New">1+int*(1+int*(μX.(1+int*X)))</font></p>
<p>Using the normal distributive properties of * and +, this can be reduced to:</p>
<p><font face="Courier New">1+int+int**2*(μX.(1+int*X))</font></p>
<p>And in the limit that we perform this substitution continually, we will produce the same infinite sum that we expected for this list of <font face="Courier New">int</font>s.</p>
<p>Although this formalism may seem somewhat removed from the language of types in F#, you can quickly recover it if you replace the keyword &#8220;type&#8221; for &#8220;mu,&#8221; &#8220;=&#8221; for &#8220;.&#8221;, &#8220;|&#8221; for &#8220;+&#8221;, recognize that empty constructors are constructors on the unit type, and ignore constructor names.&nbsp; For example:</p>
<p><font face="Courier New">type IntList = Nil | Cons of int*IntList</font></p>
<p>becomes:</p>
<p><font face="Courier New">μIntList.(1+int*IntList)</font></p>
<p>Again, the type of lists of integers that we have already identified (modulo the choice of &#8220;X&#8221; or &#8220;IntList&#8221; for the recursion symbol).</p>
<p>This machinery of recursive types takes some getting used to, but it can produce the same infinite series that we expect in algebra, and it&#8217;s very convenient for recursive types with multiple branches of recursion, for example the type of binary trees of integers:</p>
<p><font face="Courier New">μX.(int+X*X)</font></p>
<p>In other words, a binary tree is either a leaf (storing an <font face="Courier New">int</font>) or it&#8217;s a branch (storing a pair of binary trees).</p>
<p>It seems like we can describe a very rich category of types with these tools (for more detail, see <a href="http://www.cis.upenn.edu/~bcpierce/tapl/">&#8220;the bible of type theory&#8221;</a>).&nbsp; What&#8217;s more, our existing knowledge of algebra can be ported to this world of types, where we find many familiar structures.&nbsp; But this formalization of types goes even deeper, and there are more concepts left to unify.</p>
<p>∂<strong> for Data</strong></p>
<p>In the world of functional programming, destructive mutation is discouraged or even banned outright.&nbsp; From a formal perspective, an update should produce a new copy of the original value, with both versions available for some later use.&nbsp; This view has simplified many otherwise thorny problems, and it makes programs much simpler to reason about.</p>
<p>We have <a href="http://blog.lab49.com/archives/2984">previously discussed</a> ways to recover mutation-like functions, inspired by the most famous data structure of its kind: <a href="http://www.st.cs.uni-saarland.de/edu/seminare/2005/advanced-fp/docs/huet-zipper.pdf">the Zipper</a>.</p>
<p>In 2001, Conor McBride made <a href="http://www.cs.nott.ac.uk/~ctm/diff.pdf">a remarkable discovery</a> about algebraic data types, and the concept of a zipper, which he <a href="http://www.cs.nott.ac.uk/~txa/publ/jpartial.pdf">elaborated</a> four years later (along with coauthors Abbot, Ghani, and Altenkirch).</p>
<p>Central to this discovery is the concept of a <em>one-hole context</em>.&nbsp; A one-hole context can be thought of as a data type &#8220;with a hole in it.&#8221;&nbsp; This is a concept closely linked to the concept of mutation, as a value can be &#8220;updated&#8221; by &#8220;plugging in&#8221; that hole.</p>
<p>Consider as a very simple example, a 3-tuple of integers.&nbsp; Its type is <font face="Courier New">int*int*int</font>, or <font face="Courier New">int**3</font>.&nbsp; Now, we might have a value of this type:</p>
<p><font face="Courier New">(98, 76, 54)</font></p>
<p>We might want to &#8220;update&#8221; one of these values, or at least single one out for updating.&nbsp; We can do this by &#8220;poking a hole&#8221; in the data structure where a particular value goes.&nbsp; In other words, we might choose to update the first, second, or third components of this 3-tuple (using &#8220;_&#8221; to represent a hole):</p>
<p><font face="Courier New">(_,&nbsp; 76, 54)<br />(98, _,&nbsp; 54)<br />(98, 76, _)</font></p>
<p>These three cases represent the only ways that we could &#8220;poke a hole&#8221; in this 3-tuple data, and we can capture that idea in a corresponding data type.&nbsp; Because there are three ways to poke a hole, the type should be a three-way sum.&nbsp; Each possibility leaves two integers (in different configurations), and so we can pretty straightforwardly deduce this type of <em>one-hole contexts</em>:</p>
<p><font face="Courier New">(int*int)+(int*int)+(int*int)</font></p>
<p>In other words, the first <font face="Courier New">int*int</font> corresponds to the type of &#8220;<font face="Courier New">(_, 76, 54)</font>&#8220;, the second <font face="Courier New">int*int</font> corresponds to the type of &#8220;<font face="Courier New">(98, _, 54)</font>&#8220;, and the third <font face="Courier New">int*int</font> corresponds to the type of &#8220;<font face="Courier New">(98, 76, _)</font>&#8220;.</p>
<p>It&#8217;s useful to simplify the type of this expression, and so we might shrink it to (explicitly naming squares):</p>
<p><font face="Courier New">int**2+int**2+int**2</font></p>
<p>and then combining like terms:</p>
<p><font face="Courier New">3*int**2</font></p>
<p>In other words, the type of one-hole contexts of 3-tuples of ints is one of three int-pairs.</p>
<p>Now here&#8217;s an odd thing, we started out with the type:</p>
<p><font face="Courier New">int**3</font></p>
<p>and taking its one-hole context we derived the type:</p>
<p><font face="Courier New">3*int**2</font></p>
<p>That looks an awful lot like the derivative of differential calculus!</p>
<p>In fact that&#8217;s exactly what McBride discovered, that the derivative of an algebraic data type is its type of one-hole contexts!&nbsp; Extended to recursive types (see McBride&#8217;s paper for more details) we can use the derivative to mechanically produce functions for updating and iterating over arbitrary data structures.</p>
<p><strong>Further Reading</strong></p>
<p>Predating McBride&#8217;s work, Andre Joyal explored the concept of <a href="http://en.wikipedia.org/wiki/Combinatorial_species">combinatorial species</a> (built on the concept of <a href="http://en.wikipedia.org/wiki/Generating_function">generating functions</a> &#8212; a formalism similar in purpose to algebraic data types), where the use of the derivative was also discovered.</p>
<p>McBride is also the co-creator of the programming language <a href="http://www.e-pig.org/">Epigram</a>, a programming language with a powerful theory of types.</p>
<p>In the next article, we&#8217;ll look at implementing this notion of differentiation of data types with a brief Haskell program.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.lab49.com/archives/3011/feed</wfw:commentRss>
		<slash:comments>16</slash:comments>
		</item>
		<item>
		<title>Purely-Functional Incremental Mutation</title>
		<link>http://blog.lab49.com/archives/2984</link>
		<comments>http://blog.lab49.com/archives/2984#comments</comments>
		<pubDate>Mon, 06 Apr 2009 02:14:47 +0000</pubDate>
		<dc:creator>Kalani Thielen</dc:creator>
				<category><![CDATA[Computer Science]]></category>
		<category><![CDATA[Conversations in the Lab]]></category>
		<category><![CDATA[F#]]></category>
		<category><![CDATA[Functional Programming]]></category>
		<category><![CDATA[Haskell]]></category>

		<guid isPermaLink="false">http://blog.lab49.com/archives/2984</guid>
		<description><![CDATA[In writing functional programs, we&#8217;ve learned to put aside many problematic techniques for writing programs, especially iteration and mutation over data structures.&#160; On the other hand, some folks aren&#8217;t buying in to this functional nonsense, and they continue to build elaborate (and working, they will remind you) software based fundamentally on algorithms incrementally mutating data [...]]]></description>
			<content:encoded><![CDATA[<p>In writing functional programs, we&#8217;ve learned to put aside many problematic techniques for writing programs, especially iteration and mutation over data structures.&nbsp; On the other hand, some folks aren&#8217;t buying in to this functional nonsense, and they continue to build elaborate (and <em>working</em>, they will remind you) software based fundamentally on algorithms incrementally mutating data structures.</p>
<p>Can&#8217;t we all just get along?</p>
<p>(An answer inside, plus the continuation of <a href="http://blog.lab49.com/archives/2954">our exploration of type-classes</a>.)</p>
<p><span id="more-2984"></span></p>
<p><strong>Yes We Can</strong></p>
<p>We just need to be liberal with how we define &#8220;mutation.&#8221;&nbsp; In the practice of most programming languages, &#8220;mutation&#8221; means destructive updates &#8212; so that when we perform an update on a data structure, the previous state of that structure is lost.&nbsp; However, when most people think of mutation (and when they consider why it&#8217;s useful to them) they typically think of an update that takes a (short) constant amount of time &#8212; and this becomes most useful in the aggregate of a lot of little mutations applied incrementally.&nbsp; When you tell them that a functional update preserves previous states by creating an updated copy, a little cash-register in their brain goes nuts calculating the expense of (say) making three consecutive updates.</p>
<p>But we <em>can</em> perform a purely functional update in constant time.&nbsp; As a trivial example, consider a pair of values.&nbsp; We can update a pair either by updating its first element or its second; in Haskell:</p>
<p><font face="Courier New">update_left&nbsp; (_, y) x = (x, y)<br />update_right (x, _) y = (x, y)</font></p>
<p>Although these functions don&#8217;t destructively update the structures they work on, they do produce updated structures in a constant amount of time.&nbsp; So where does the expense of this functional method get out of hand?</p>
<p>Consider a function to update the <em>nth</em> element of a list.&nbsp; This kind of function is easy enough to write:</p>
<p><font face="Courier New">update_nth []&nbsp;&nbsp;&nbsp;&nbsp; _ _ = []<br />update_nth (_:xs) 0 v = v:xs<br />update_nth (x:xs) n v = x:(update_nth xs (n &#8211; 1) v)</font></p>
<p>This does work correctly, but it&#8217;s a good example of the kind of argument that a mutation-loving programmer could justifiably make against Haskell.&nbsp; Because, if you need to update just the 70th, 90th, and 120th elements of the list, you wind up stepping through the first 69, 89, and 119 elements at each stage (for a total of 69+89+119=227 visits).&nbsp; However, in an incremental C/C++/Java program we can just increment an iterator and update it, meaning that for the equivalent program we&#8217;d only need to visit 119 elements (of course, the distance between these two expenses gets even greater with longer lists, and with more updates).</p>
<p>Where did we go wrong?</p>
<p>If purely functional updates to tuples are efficient, perhaps we can make our list look like a tuple.&nbsp; This basic insight led to the introduction of <a href="http://www.st.cs.uni-saarland.de/edu/seminare/2005/advanced-fp/docs/huet-zipper.pdf">the Zipper</a>, an important kind of data-type.</p>
<p>To see how this solves our problems for lists, we need to consider the concept of a <em>one-hole context</em>.&nbsp; A one-hole context represents a &#8220;point of interest&#8221; in a data structure.&nbsp; So for instance, with a list, a one-hole context should represent the list elements we&#8217;ve visited up to our point of interest, and what remains after our point of interest.</p>
<p>For example, to focus on the 3rd element of this list:</p>
<p><font face="Courier New">[1,2,3,4,5]</font></p>
<p>Our one-hole context should look like this:</p>
<p><font face="Courier New">([2,1], [4,5])</font></p>
<p>Notice that the first list is in reverse order, because it represents the elements in the order that we visited them.</p>
<p>Now with this data type we&#8217;ve almost settled on the perfect representation.&nbsp; All that we need to do is add the value of interest, and we&#8217;ll have a complete representation of the list with an element in focus and in just the right form for purely functional updates.&nbsp; Again, with the 3rd element of the list [1,2,3,4,5] selected:</p>
<p><font face="Courier New">([2,1], 3, [4,5])</font></p>
<p>Now we can write a general function to update this iterator value:</p>
<p><font face="Courier New">update (prefix, _, suffix) x = (prefix, x, suffix)</font></p>
<p>We can also write functions to increment this iterator (again, a constant-time operation):</p>
<p><font face="Courier New">forward (_,&nbsp; _, [])&nbsp;&nbsp; = error &#8220;Iterator at end.&#8221;<br />forward (px, x, s:sx) = (x:px, s, sx)</font></p>
<p>And also to decrement the iterator:</p>
<p><font face="Courier New">backward ([], _, _)&nbsp;&nbsp;&nbsp; = error &#8220;Iterator at beginning.&#8221;<br />backward (p:px, x, sx) = (px, p, x:sx)</font></p>
<p>Finally, we have a method to efficiently and incrementally walk a list, updating arbitrary parts of it in constant time in a purely functional way.&nbsp; Of course, there is an added expense (hopefully one that we can amortize away) if we need to reconstruct the &#8220;real&#8221; updated list from our iterator:</p>
<p><font face="Courier New">close (px, x, sx) = (reverse px) ++ (x:sx)</font></p>
<p><strong>Beyond Lists</strong></p>
<p>At this point, we may be able to win over some mutation-loving programmers.&nbsp; However, the point will quickly be made that <em>in the real world</em> we use data structures other than lists.&nbsp; Binary trees, n-ary trees, directed graphs, and many other kinds of structures crop up in all sorts of problems.</p>
<p>Once again, type-classes are here to save us.&nbsp; We just need to take a step back, and recognize that to apply this principle of purely-functional-incremental-update-able iterators to arbitrary &#8220;container types&#8221; we need a couple of suitable type-classes.&nbsp; We&#8217;ll need to begin our script with the following line:</p>
<p><font face="Courier New">{-# LANGUAGE MultiParamTypeClasses, FunctionalDependencies, FlexibleInstances, UndecidableInstances, TypeSynonymInstances #-}</font>
<p>First, our representation of iterators should encapsulate everything that we&#8217;ve learned here.&nbsp; We should be able to increment and decrement them.&nbsp; We should be able to check their current value, and update them.&nbsp; For convenience, we should also be able to determine when we&#8217;re at the end (or beginning) of the iterator&#8217;s extent:</p>
<p><font face="Courier New">class Iterator b a | b -&gt; a where<br />&nbsp;&nbsp; bos&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; :: b -&gt; Bool<br />&nbsp;&nbsp; eos&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; :: b -&gt; Bool<br />&nbsp;&nbsp; forward&nbsp; :: b -&gt; b<br />&nbsp;&nbsp; backward :: b -&gt; b<br />&nbsp;&nbsp; value&nbsp;&nbsp;&nbsp; :: b -&gt; a<br />&nbsp;&nbsp; update&nbsp;&nbsp; :: b -&gt; a -&gt; b</font>
<p>Here, the type &#8220;b&#8221; represents an iterator and &#8220;a&#8221; its &#8220;element type&#8221; (hence the functional dependency &#8220;b -&gt; a&#8221; saying that b derives a).</p>
<p>Finally, we&#8217;ll need to convert back and forth between a container and its iterator:</p>
<p><font face="Courier New">class Iterator b a =&gt; Iterable f b a | f -&gt; b, b -&gt; f where<br />&nbsp;&nbsp; open&nbsp; :: f a -&gt; b<br />&nbsp;&nbsp; close :: b -&gt; f a</font>
<p>This type-class captures the critical observation that every container-type has a unique iterator type (&#8220;f -&gt; b&#8221;) and that every iterator type derives a unique container type (&#8220;b -&gt; f&#8221;).</p>
<p>Now, as we&#8217;ve already spent the first half of this article addressing it, we can put lists and their iterators into this type-class:</p>
<p><font face="Courier New">instance Iterable [] ([a], a, [a]) a where<br />&nbsp;&nbsp; open (x:xs)&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; = ([], x, xs)<br />&nbsp;&nbsp; close (px, x, sx) = (reverse px) ++ (x:sx)</font>
<p><font face="Courier New">instance Iterator ([a], a, [a]) a where<br />&nbsp;&nbsp; bos ([], _, _)&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; = True<br />&nbsp;&nbsp; bos _&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; = False<br />&nbsp;&nbsp; eos (_, _, [])&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; = True<br />&nbsp;&nbsp; eos _&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; = False<br />&nbsp;&nbsp; forward&nbsp; (px,&nbsp;&nbsp; x, s:sx) = (x:px, s, sx)<br />&nbsp;&nbsp; backward (p:px, x, sx)&nbsp;&nbsp; = (px, p, x:sx)<br />&nbsp;&nbsp; value&nbsp; (_, x, _)&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; = x<br />&nbsp;&nbsp; update (px, _, sx) x&nbsp;&nbsp;&nbsp;&nbsp; = (px, x, sx)</font>
<p>With this structure in place, it is now possible to write functions that perform incremental updates to <em>arbitrary data structures</em>.&nbsp; So far we&#8217;ve only shown that this can be done for lists.&nbsp; However, if we follow the lesson of the Zipper we can also put (say) binary trees into the <font face="Courier New">Iterable</font> type-class as well.</p>
<p>Recall our definition of binary trees:</p>
<p><font face="Courier New">data Tree a = Leaf a | Branch (Tree a) (Tree a)<br />&nbsp;&nbsp; deriving (Show, Eq)</font>
<p>Now, to represent a point in a binary tree (its <em>one-hole context</em>) we need to record the <em>converse branches</em> at each step of the path we followed from the root of the tree (similar to the <a href="http://www.itl.nist.gov/div897/sqg/dads/HTML/SchorrWaiteGraphMarking.html">Deutsch-Schorr-Waite</a> algorithm for constant-space garbage collection).&nbsp; Along with that one-hole context representation, we&#8217;ll store another binary tree (the focused tree) to complete our iterator type.</p>
<p><font face="Courier New">type TreeIter a = (Tree a, [Either (Tree a) (Tree a)])</font>
<p>To aid us in this representation of a binary tree&#8217;s iterator, we will need a few utility functions.&nbsp; First, to move up one level in the tree:
<p><font face="Courier New">up (r, (Left&nbsp; l):p) = (Branch l r, p)<br />up (l, (Right r):p) = (Branch l r, p)</font>
<p>Also, to descend to the first leaf (either by following all left or right branches):
<p><font face="Courier New">descendl c@(Leaf _, p)&nbsp;&nbsp; = c<br />descendl (Branch l r, p) = descendl (l, (Right r):p)<br />descendr c@(Leaf _, p)&nbsp;&nbsp; = c<br />descendr (Branch l r, p) = descendr (r, (Left&nbsp; l):p)</font>
<p>Notice here that the &#8220;up&#8221; and &#8220;descend&#8221; functions cancel each other out (&#8220;up&#8221; removes a node from the list of converse branches, and &#8220;descend[l|r]&#8221; adds one at each step).
<p>Also, to make it slightly easier to check the converse branches in our paths, we can define a couple of simple utilities:
<p><font face="Courier New">is_right (Left _)&nbsp; = False<br />is_right (Right _) = True<br />is_left&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; = not . is_right</font>
<p>Now we have enough to easily put <font face="Courier New">Tree</font>, our type of binary trees, into the <font face="Courier New">Iterable</font> type-class:
<p><font face="Courier New">instance Iterable Tree (TreeIter a) a where<br />&nbsp;&nbsp; open t&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; = descendl (t, [])<br />&nbsp;&nbsp; close (t, [])&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; = t<br />&nbsp;&nbsp; close (r, (Left&nbsp; l):p) = close (Branch l r, p)<br />&nbsp;&nbsp; close (l, (Right r):p) = close (Branch l r, p)</font>
<p><font face="Courier New">instance Iterator (Tree a, [Either (Tree a) (Tree a)]) a where<br />&nbsp;&nbsp; bos (_, p)&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; = all is_right p<br />&nbsp;&nbsp; eos (_, p)&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; = all is_left p<br />&nbsp;&nbsp; forward&nbsp;&nbsp;&nbsp; (t, (Right t&#8217;):p) = descendl (t&#8217;, (Left t):p)<br />&nbsp;&nbsp; forward&nbsp; c@(t, (Left&nbsp; t&#8217;):p) = forward (up c)<br />&nbsp;&nbsp; backward&nbsp;&nbsp; (t, (Left&nbsp; t&#8217;):p) = descendr (t&#8217;, (Right t):p)<br />&nbsp;&nbsp; backward c@(t, (Right t&#8217;):p) = backward (up c)<br />&nbsp;&nbsp; value&nbsp; (Leaf x, _)&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; = x<br />&nbsp;&nbsp; update (_, p) x&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; = (Leaf x, p)</font>
<p>Phew!&nbsp; That&#8217;s it; we can now incrementally iterate over lists and trees, updating arbitrary elements in a purely functional way, in a constant amount of time.
<p><font face="Courier New">Iterable</font> implementations for other container types can be derived in a straightforward way.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.lab49.com/archives/2984/feed</wfw:commentRss>
		<slash:comments>12</slash:comments>
		</item>
		<item>
		<title>Does Haskell Support Subtyping? It Depends.</title>
		<link>http://blog.lab49.com/archives/2954</link>
		<comments>http://blog.lab49.com/archives/2954#comments</comments>
		<pubDate>Sat, 28 Mar 2009 19:16:52 +0000</pubDate>
		<dc:creator>Kalani Thielen</dc:creator>
				<category><![CDATA[Conversations in the Lab]]></category>
		<category><![CDATA[F#]]></category>
		<category><![CDATA[Functional Programming]]></category>
		<category><![CDATA[Haskell]]></category>

		<guid isPermaLink="false">http://blog.lab49.com/archives/2954</guid>
		<description><![CDATA[We&#8217;ve already seen that type-classes enable a very rich form of ad-hoc overloading (especially for basic arithmetic, where other languages require awkward workarounds).&#160; If that were all that we could do with type-classes, it would more than justify their existence in a language.&#160; However, that&#8217;s not all that we can do with type-classes &#8212; they&#8217;re [...]]]></description>
			<content:encoded><![CDATA[<p>We&#8217;ve <a href="http://blog.lab49.com/archives/2930">already seen</a> that type-classes enable a very rich form of ad-hoc overloading (especially for basic arithmetic, where other languages require awkward workarounds).&nbsp; If that were all that we could do with type-classes, it would more than justify their existence in a language.&nbsp; However, that&#8217;s not all that we can do with type-classes &#8212; they&#8217;re good for much more.</p>
<p><span id="more-2954"></span></p>
<p><strong>A Few Extensions</strong></p>
<p>I should start off by mentioning that the features of type-classes we&#8217;ll cover here are not part of the <a href="http://www.haskell.org/onlinereport/">Haskell98 standard</a>, but they&#8217;re regularly used and supported by <a href="http://www.haskell.org/ghc/">GHC</a>.&nbsp; Provided that you&#8217;re using GHC, the code that follows in this article will work if you place the following line at the head of its file:</p>
<p><font face="Courier New">{-# LANGUAGE MultiParamTypeClasses, FunctionalDependencies, FlexibleInstances #-}</font>
<p><strong>Subtyping</strong></p>
<p>In F# as well as Haskell, <a href="http://en.wikipedia.org/wiki/Tuple">tuples</a> are an important and commonly-used tool.&nbsp; They are used to define composite types, joining an arbitrary (but finite, statically known) number of types together.&nbsp; As we saw in the last article, they&#8217;re a convenient form for representing vectors.&nbsp; However, in Haskell (and in F# for that matter) you may notice an odd thing about the standard functions provided for tuples: fst and snd.</p>
<p><font face="Courier New">Prelude&gt; :t fst<br />fst :: (a,b) -&gt; a<br />Prelude&gt; :t snd<br />snd :: (a,b) -&gt; b</font></p>
<p>These functions, fst and snd, are used to extract the first and second components of a 2-tuple (respectively).&nbsp; Unfortunately, if we happen to be using 3-tuples, or 4-tuples (or n-tuples, for n &gt; 2) we&#8217;re out of luck.&nbsp; In those cases, we can&#8217;t even extract the first and second members without having to create something like:</p>
<p><font face="Courier New">fst3 (x,_,_) = x<br />fst4 (x,_,_,_) = x<br />&#8230; etc &#8230;</font></p>
<p>This is pretty silly.&nbsp; This is clearly a case where some overloading would benefit us, so that we wouldn&#8217;t need to define the &#8220;fst&#8221; function with a different name for each possible size of tuple.&nbsp; What we really want is something with a type signature like:</p>
<p><font face="Courier New">first :: Pair p a b =&gt; p -&gt; a</font></p>
<p>Here we&#8217;re seeing a type-class constraint unlike the comparatively simple ones in the last article.&nbsp; In essence, what &#8220;<font face="Courier New">Pair p a b</font>&#8221; must mean here, is that for some pair type &#8220;<font face="Courier New">p</font>&#8221; a type &#8220;<font face="Courier New">a</font>&#8221; and a type &#8220;<font face="Courier New">b</font>&#8221; can be extracted.&nbsp; In the case of the &#8220;<font face="Courier New">first</font>&#8221; function we&#8217;ll just extract the &#8220;<font face="Courier New">a</font>&#8221; type, so the type of the &#8220;<font face="Courier New">second</font>&#8221; function must be:</p>
<p><font face="Courier New">second :: Pair p a b =&gt; p -&gt; b</font></p>
<p>This scheme might sound reasonable, but how is the Haskell compiler supposed to know that the &#8220;p&#8221; type really does derive the &#8220;a&#8221; and &#8220;b&#8221; types?&nbsp; For that, we need <a href="http://hackage.haskell.org/trac/haskell-prime/wiki/FunctionalDependencies">functional dependencies</a>.&nbsp; We can simply declare this dependency when we make the &#8220;<font face="Courier New">Pair</font>&#8221; type-class and Haskell&#8217;s type-checker will respect the restriction across all members of the type-class:</p>
<p><font face="Courier New">class Pair p a b | p -&gt; a, p -&gt; b where<br />&nbsp;&nbsp; first&nbsp; :: p -&gt; a<br />&nbsp;&nbsp; second :: p -&gt; b</font>
<p>When filling out instances, we won&#8217;t have to mention these dependencies again.&nbsp; So for example, if we wanted to define &#8220;<font face="Courier New">first</font>&#8221; and &#8220;<font face="Courier New">second</font>&#8221; over 2, 3, and 4-tuples:</p>
<p><font face="Courier New">instance Pair (a, b) a b where<br />&nbsp;&nbsp; first&nbsp; (x, y) = x<br />&nbsp;&nbsp; second (x, y) = y </font>
<p><font face="Courier New">instance Pair (a, b, c) a b where<br />&nbsp;&nbsp; first&nbsp; (x, y, z) = x<br />&nbsp;&nbsp; second (x, y, z) = y </font>
<p><font face="Courier New">instance Pair (a, b, c, d) a b where<br />&nbsp;&nbsp; first&nbsp; (x, y, z, w) = x<br />&nbsp;&nbsp; second (x, y, z, w) = y</font>
<p>Now it&#8217;s true that we&#8217;re still filling out each and every definition, like we had done with fst3, fst4, etc.&nbsp; However, we have at least gotten far enough to avoid having to know the size of the tuple when we&#8217;re using it!&nbsp; It would be a <a href="http://www.e-pig.org/">strong language indeed</a> that didn&#8217;t require this boilerplate, but it&#8217;s easy enough to generate it and forget it.</p>
<p>Of course we don&#8217;t have to stop at &#8220;<font face="Courier New">first</font>&#8221; and &#8220;<font face="Courier New">second</font>&#8221; (but we do have to stop somewhere).&nbsp; We might also want to define &#8220;<font face="Courier New">third</font>&#8221; on any tuple as big or bigger than a triple.&nbsp; Of course, a triple should already be a pair (i.e.: if <font face="Courier New">third </font>is defined on a tuple, <font face="Courier New">first</font> and <font face="Courier New">second</font> had better also be).&nbsp; We can express this requirement with a type-class constraint, as well as the functional dependency required to claim that the triple&#8217;s type can produce yet another type (but we don&#8217;t need to re-declare the functional dependencies inherited from the <font face="Courier New">Pair</font> type):</p>
<p><font face="Courier New">class Pair p a b =&gt; Triple p a b c | p -&gt; c where<br />&nbsp;&nbsp; third :: p -&gt; c</font>
<p>After that, it&#8217;s just as easy (if not a little tedious) to put more tuples into this type-class as well:</p>
<p><font face="Courier New">instance Triple (a, b, c) a b c where<br />&nbsp;&nbsp; third (x, y, z) = z </font>
<p><font face="Courier New">instance Triple (a, b, c, d) a b c where<br />&nbsp;&nbsp; third (x, y, z, w) = z</font>
<p><strong>Points and Colored Points</strong>
<p>It requires a bit of initial work (whether manual or automatic) to set this up, but once our generic tuple functions are in place we can then use them to achieve <a href="http://en.wikipedia.org/wiki/Structural_type_system">structural subtyping</a> without any other work from the language.
<p>For example, we may make a distinction between points and colored points:
<p><font face="Courier New">data Color = Red | Green | White | Yellow | Blue</p>
<p>makePoint x y = (x, y)<br />makeCPoint x y c = (x, y, c)</font>
<p>However, either kind of point can have a distance (from the origin) defined:
<p><font face="Courier New">distance :: (Pair p Float Float) =&gt; p -&gt; Float<br />distance p = sqrt ((first p)**2 + (second p)**2)</font>
<p><strong>To Be Continued</strong>
<p>It&#8217;s fairly remarkable that type-classes (with these extensions) allow the recovery of subtyping in a language that otherwise wasn&#8217;t designed to support it.
<p>In the next article we&#8217;ll continue investigating applications of multi-parameter type-classes with functional dependencies, to address a generic approach to incremental iteration and constant-time updates for arbitrary Haskell containers.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.lab49.com/archives/2954/feed</wfw:commentRss>
		<slash:comments>14</slash:comments>
		</item>
		<item>
		<title>Functional Arithmetic Redux</title>
		<link>http://blog.lab49.com/archives/2930</link>
		<comments>http://blog.lab49.com/archives/2930#comments</comments>
		<pubDate>Tue, 24 Mar 2009 19:43:53 +0000</pubDate>
		<dc:creator>Kalani Thielen</dc:creator>
				<category><![CDATA[Conversations in the Lab]]></category>
		<category><![CDATA[F#]]></category>
		<category><![CDATA[Functional Programming]]></category>
		<category><![CDATA[Haskell]]></category>

		<guid isPermaLink="false">http://blog.lab49.com/archives/2930</guid>
		<description><![CDATA[Last time we compared arithmetic overloading and type-inference in F# and Haskell.&#160; We even created our own numeric type in Haskell, as represented by Peano numbers, by implementing a type-class instance.&#160; This stood in contrast to F#&#8217;s fixed set of numeric types (whose overloading of arithmetic functions was treated as a special case by F#&#8217;s [...]]]></description>
			<content:encoded><![CDATA[<p><a href="http://blog.lab49.com/archives/2895">Last time</a> we compared arithmetic overloading and type-inference in F# and Haskell.&nbsp; We even created our own numeric type in Haskell, as represented by Peano numbers, by implementing a type-class instance.&nbsp; This stood in contrast to F#&#8217;s fixed set of numeric types (whose overloading of arithmetic functions was treated as a special case by F#&#8217;s type-checker).</p>
<p>APL/KDB programmers don&#8217;t have the benefit of a type-checker, but they do have some sophisticated overloading of arithmetic types.&nbsp; Here we&#8217;ll see how we can recover APL-style arithmetic in Haskell, properly typed, and discover an important generalization that should further the argument that type-classes would be a valuable addition to F#.</p>
<p><span id="more-2930"></span></p>
<p><strong>A Simple Point</strong></p>
<p>Type-classes in Haskell are used to represent <em>bounded polymorphism</em>.&nbsp; This is in contrast to &#8220;parametric polymorphism,&#8221; the idea that a function can be defined over all types.&nbsp; In fact, we don&#8217;t need type-classes to define &#8220;bounds&#8221; on parametric polymorphism &#8212; we <em>could</em> just supply proof of the type being within bounds every time that proof is required (this was the moviephone-F# program of the last article &#8212; always passing the right &#8220;add&#8221; function when it was needed).&nbsp; Type-classes simply save us from that burden.</p>
<p>Just as type-class bounds apply to the types of functions, they can also apply to the types of type-class instances.&nbsp; For example, consider the definition of a simple 2D point:</p>
<p><font face="Courier New">instance (Num a, Num b) =&gt; Num (a, b) where<br />&nbsp;&nbsp; (a1, a2) + (b1, b2) = (a1+b1, a2+b2)<br />&nbsp;&nbsp; (a1, a2) &#8211; (b1, b2) = (a1-b1, a2-b2)<br />&nbsp;&nbsp; (a1, a2) * (b1, b2) = (a1*b1, a2*b2)<br />&nbsp;&nbsp; abs (av, bv)&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; = (abs av, abs bv)<br />&nbsp;&nbsp; signum (av, bv)&nbsp;&nbsp;&nbsp;&nbsp; = (signum av, signum bv)<br />&nbsp;&nbsp; fromInteger x&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; = (fromInteger x, fromInteger x)</font>
<p>This restriction (following the keyword &#8220;instance&#8221; introducing a type-class instance) says that a pair of values <font face="Courier New">(a, b)</font> can be treated like a number, provided that <font face="Courier New">a</font> can be treated like a number and <font face="Courier New">b</font> can be treated like a number.&nbsp; The rest of the definition defines arithmetic over these pairs in a fairly straightforward way.
<p><font face="Courier New">Prelude&gt; (2, 3.5) + (1, 0.2)<br />(3, 3.7)</font>
<p>An important point here is that the &#8216;fromInteger&#8217; function &#8220;lifts&#8221; integers into any numeric type.&nbsp; So we can demonstrate expressions similar to what we might see at the start of a linear algebra course (multiplying vectors by scalars):
<p><font face="Courier New">Prelude&gt; 2 * (3, 3.5)<br />(6, 7.0)</font>
<p>Extending this definition to 3D points is just as simple:
<p><font face="Courier New">instance (Num a, Num b, Num c) =&gt; Num (a, b, c) where<br />&nbsp;&nbsp; (a1, a2, a3) + (b1, b2, b3) = (a1+b1, a2+b2, a3+b3)<br />&nbsp;&nbsp; (a1, a2, a3) &#8211; (b1, b2, b3) = (a1-b1, a2-b2, a3-b3)<br />&nbsp;&nbsp; (a1, a2, a3) * (b1, b2, b3) = (a1*b1, a2*b2, a3*b3)<br />&nbsp;&nbsp; abs (av, bv, cv) = (abs av, abs bv, abs cv)<br />&nbsp;&nbsp; signum (av, bv, cv) = (signum av, signum bv, signum cv)<br />&nbsp;&nbsp; fromInteger x = (fromInteger x, fromInteger x, fromInteger x)</font>
<p><strong>A Less Simple Point</strong>
<p>KDB also defines arithmetic over arbitrary-length lists, and we will do that here as well.&nbsp; However, it&#8217;s worth first covering &#8220;higher-kinded type-classes&#8221; or type-classes defined over type constructors.
<p>What is a type constructor?&nbsp; Speaking roughly, a type constructor is something which, when applied to a type, produces a new type.&nbsp; For example, in F# &#8220;list&#8221; is a type constructor because it isn&#8217;t until you supply it a type, &#8220;int list&#8221;, that you have a real type.&nbsp; In Haskell, this distinction is made by the &#8220;<a href="http://en.wikipedia.org/wiki/Kind_(type_theory)">kind system</a>&#8221; &#8212; allowing a more concise definition of a type constructor.&nbsp; A &#8220;basic type&#8221; (e.g.: Int, Float, Int -&gt; Float, [Char], etc) has kind *, so a &#8220;type constructor&#8221; (e.g.: [], ((,) Int), Maybe, (Either Int), etc) has kind *-&gt;*.&nbsp; At the GHCI prompt, you can check a type&#8217;s kind with the &#8220;:k&#8221; command:
<p><font face="Courier New">Prelude&gt; :k Int<br />Int :: *<br />Prelude&gt; :k []<br />[] :: * -&gt; *<br />Prelude&gt; :k (,)<br />(,) :: * -&gt; * -&gt; *<br />Prelude&gt; :k ((,) Int)<br />((,) Int) :: * -&gt; *</font>
<p>Probably the most natural example of a higher-kinded type-class is Haskell&#8217;s <font face="Courier New">Functor</font> class.&nbsp; It contains just the <font face="Courier New">fmap</font> function, and looks something like this:
<p><font face="Courier New">class Functor f where<br />&nbsp;&nbsp; fmap :: (a -&gt; b) -&gt; (f a -&gt; f b)</font>
<p>Here it&#8217;s clear that &#8220;f&#8221; must have kind *-&gt;*, because it is used in the definition of the <font face="Courier New">fmap</font> function to construct two types.&nbsp; What&#8217;s more, this Functor instance &#8220;lifts&#8221; a function (from some a to b) to a new function over a and b in the f container (analogously to the definition of a functor in <a href="http://en.wikipedia.org/wiki/Category_theory">category theory</a>).
<p>For lists, this definition is exactly the same as the &#8220;map&#8221; function that everyone is familiar with:
<p><font face="Courier New">instance Functor [] where<br />&nbsp;&nbsp; fmap f [] = []<br />&nbsp;&nbsp; fmap f (x:xs) = (f x):(fmap f xs)</font>
<p>However, lists are not the only kind of data structure that we use in functional programs, so that if we have a simple binary tree:
<p><font face="Courier New">data Tree a = Leaf a | Branch (Tree a) (Tree a)</font>
<p>We can define a similar <font face="Courier New">Functor</font> instance:
<p><font face="Courier New">instance Functor Tree where<br />&nbsp;&nbsp; fmap f (Leaf x) = Leaf (f x)<br />&nbsp;&nbsp; fmap f (Branch l r) = Branch (fmap f l) (fmap f r)</font>
<p>And, importantly, in both cases <font face="Courier New">fmap</font> will preserve the <em>structure</em> of the container it operates on, only transforming <em>elements</em>.
<p><font face="Courier New">Prelude&gt; fmap (1+) [1,2,3,4]<br />[2,3,4,5]<br />Prelude&gt; fmap (1+) (Branch (Branch (Leaf 1) (Leaf 2)) (Branch (Leaf 3) (Leaf 4)))<br />Branch (Branch (Leaf 2) (Leaf 3)) (Branch (Leaf 4) (Leaf 5))</font>
<p>With this knowledge, we can define arithmetic over type-constructors very easily, as long as the type-constructor is &#8220;stretch-zippable&#8221; and its elements are numbers:
<p><font face="Courier New">instance (SZip f, Num a, Show (f a), Eq (f a)) =&gt; Num (f a) where<br />&nbsp;&nbsp; xs + ys&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; = fszip (+) xs ys<br />&nbsp;&nbsp; xs &#8211; ys&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; = fszip (-) xs ys<br />&nbsp;&nbsp; xs * ys&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; = fszip (*) xs ys<br />&nbsp;&nbsp; abs xs&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; = fmap abs xs<br />&nbsp;&nbsp; signum xs&nbsp;&nbsp;&nbsp;&nbsp; = fmap signum xs<br />&nbsp;&nbsp; fromInteger i = fszunit (fromInteger i)</font>
<p>This definition isn&#8217;t complete without an explanation of <font face="Courier New">SZip</font> (&#8220;stretch-zippable&#8221; &#8212; which assumes that a <font face="Courier New">Functor</font> is also defined &#8212; as evidenced by the use of <font face="Courier New">fmap</font> in <font face="Courier New">abs</font> and <font face="Courier New">signum</font>).&nbsp; The <font face="Courier New">SZip</font> type-class is similar to <font face="Courier New">Functor</font>&#8216;s <font face="Courier New">fmap</font>, except that it maps a binary function pair-wise over two sequences.&nbsp; Unlike Haskell&#8217;s standard zip function, it then extends the final element of the shorter sequence over the remainder of the longer sequence (hence the &#8220;stretch&#8221; in &#8220;stretch-zippable&#8221;).&nbsp; It also defines a function, <font face="Courier New">fszunit</font>, to put a single element in a stretch-zippable container (although this function is common enough to probably warrant its own type-class):
<p><font face="Courier New">class Functor f =&gt; SZip f where<br />&nbsp;&nbsp; fszip :: (a -&gt; b -&gt; c) -&gt; f a -&gt; f b -&gt; f c<br />&nbsp;&nbsp; fszunit :: a -&gt; f a</font>
<p>The definition for lists is fairly straightforward:
<p><font face="Courier New">instance SZip [] where<br />&nbsp;&nbsp; fszip f [] _&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; = []<br />&nbsp;&nbsp; fszip f _ []&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; = []<br />&nbsp;&nbsp; fszip f (x:xs) [y]&nbsp;&nbsp;&nbsp; = (f x y):(map (\ x -&gt; f x y) xs)<br />&nbsp;&nbsp; fszip f [x] (y:ys)&nbsp;&nbsp;&nbsp; = (f x y):(map (f x) ys)<br />&nbsp;&nbsp; fszip f (x:xs) (y:ys) = (f x y):(fszip f xs ys)<br />&nbsp;&nbsp; fszunit x&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; = [x]</font>
<p>Here we get the expected pair-wise addition of lists, for example:
<p><font face="Courier New">Prelude&gt; [1,2,3] + [4,5,6]<br />[5,7,9]</font>
<p>As well as scalar arithmetic distributing over a list:
<p><font face="Courier New">Prelude&gt; 2 + [1,2,3]<br />[3,4,5]</font>
<p>This latter fact comes from the application of <font face="Courier New">fszunit</font> via <font face="Courier New">fromInteger</font>, which converts 2 into [2]:
<p>[2] + [1,2,3]
<p>By the definition of <font face="Courier New">fszip</font>, this maps (2+) over [1,2,3], which explains why we produce [3,4,5].
<p>Now, we can also define an <font face="Courier New">SZip</font> instance for our binary trees (for which we&#8217;ve already provided the necessary <font face="Courier New">Functor</font> instance):
<p><font face="Courier New">instance SZip Tree where<br />&nbsp;&nbsp; fszip f (Leaf x) (Leaf y) = Leaf (f x y)<br />&nbsp;&nbsp; fszip f (Branch l1 r1) (Branch l2 r2) = Branch (fszip f l1 l2) (fszip f r1 r2)<br />&nbsp;&nbsp; fszip f x (Branch l r) = Branch (fszip f x l) (fszip f x r)<br />&nbsp;&nbsp; fszip f (Branch l r) x = Branch (fszip f l x) (fszip f r x)<br />&nbsp;&nbsp; fszunit x = Leaf x</font>
<p>At this point, we&#8217;ve out-KDBed KDB, because all of our numeric overloads combine to produce a beautiful result:</p>
<p><font face="Courier New">Prelude&gt; 2 * (Branch (Leaf [(1,2,3), (4,5,6)]) (Leaf [(7,8,9), (10,11,12)]))<br />Branch (Leaf [(2,4,6),(8,10,12)]) (Leaf [(14,16,18),(20,22,24)])</font>
<p>Hopefully the value of this kind of overloading, over types and type-constructors, is clear.&nbsp; In the next article, I&#8217;ll show how type-classes can also be used to define relations between types (and/or type-constructors).</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.lab49.com/archives/2930/feed</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>The F# overload-o-phone</title>
		<link>http://blog.lab49.com/archives/2895</link>
		<comments>http://blog.lab49.com/archives/2895#comments</comments>
		<pubDate>Fri, 20 Mar 2009 12:20:03 +0000</pubDate>
		<dc:creator>Kalani Thielen</dc:creator>
				<category><![CDATA[F#]]></category>
		<category><![CDATA[Functional Programming]]></category>
		<category><![CDATA[General Development]]></category>
		<category><![CDATA[Haskell]]></category>

		<guid isPermaLink="false">http://blog.lab49.com/archives/2895</guid>
		<description><![CDATA[By now, you&#8217;ve probably heard the standard line.&#160; Functional programming is all sweetness and light; if we merely cast off the detritus of bad habits we&#8217;ve learned from C, C++ and Java we&#8217;ll find ourselves in a different world, a better world.&#160; Without state, and by dint of a civilized logical system of analysis, all [...]]]></description>
			<content:encoded><![CDATA[<p>By now, you&#8217;ve probably heard the standard line.&nbsp; Functional programming is all sweetness and light; if we merely cast off the detritus of bad habits we&#8217;ve learned from C, C++ and Java we&#8217;ll find ourselves in a different world, a better world.&nbsp; Without state, and by dint of a <a href="http://en.wikipedia.org/wiki/First-order_logic">civilized logical system</a> of analysis, all wishes will come true.</p>
<p>Yet, in the world of <a href="http://research.microsoft.com/en-us/um/cambridge/projects/fsharp/">F#</a> (and <a href="http://caml.inria.fr/ocaml/">OCaml</a> in a slightly different case), we encounter some logical anomalies:</p>
<p><font face="Courier New">&gt; (+);;<br />val it : (int -&gt; int -&gt; int)<br />&gt; 3.2 + 5.4;;<br />val it : float = 8.6</font>
<p>Which is the truth here?&nbsp; Initially we&#8217;re told that the &#8220;+&#8221; operator expects two <font face="Courier New">int</font> values, but it seems to happily accept two <font face="Courier New">float</font>s.&nbsp; Worse yet, if we expect to rely on this magical addition, our hopes are soon dashed:
<p><font face="Courier New">&gt; let twice x = x + x;;<br />&gt; twice 9.4;;<br />&nbsp; &#8212;&#8212;^^^<br />stdin(2,5): error FS0001: This expression has type<br />&nbsp;&nbsp;&nbsp; float<br />but is here used with type<br />&nbsp;&nbsp;&nbsp; int.</font>
<p>Our only chance for generic arithmetic (over ints, floats, vectors, etc) is to explicitly pass the necessary arithmetic functions around:
<p><font face="Courier New">&gt; let twice fn x = fn x x;;<br />val twice : (&#8216;a -&gt; &#8216;a -&gt; &#8216;b) -&gt; &#8216;a -&gt; &#8216;b</font><font face="Courier New"><br />&gt; twice (+) 1;;<br />val it : int = 2<br />&gt; twice (+) 1.2;;<br />val it : float = 2.4<br />&gt; twice (fun (a,b) (c,d) -&gt; (a+c,b+d)) (1,2.3);;<br />val it : int * float = (2, 4.6)</font></p>
<p>And although this works, it has a kind of Jerry Seinfeld <a href="http://www.youtube.com/watch?v=uAb3TcSWu7Q&amp;feature=related">&#8220;why don&#8217;t you just tell me the function you want to call?&#8221;</a> feel to it.&nbsp; There must be a better way.</p>
<p><span id="more-2895"></span></p>
<p><strong>Implicit, Ad-Hoc Polymorphism</strong>
<p>This problem is all the more frustrating, because we can resolve it so easily in C++:
<p><font face="Courier New"><font color="#0000ff">int</font>&nbsp;&nbsp;&nbsp; twice(<font color="#0000ff">int</font>&nbsp;&nbsp;&nbsp; x) { <font color="#0000ff">return</font> x+x; }<br /><font color="#0000ff">double</font> twice(<font color="#0000ff">double</font> x) { <font color="#0000ff">return</font> x+x; }</font>
<p>20 years ago, Phil Wadler and Stephen Blott developed an effective solution to this problem, in <a href="https://eprints.kfupm.edu.sa/44280/1/44280.pdf">How to make ad-hoc polymorphism less ad hoc</a>.&nbsp; The result has been arguably one of the most significant advances made by the programming language <a href="http://www.haskell.org/">Haskell</a>.&nbsp; It&#8217;s a tool that could be put to good use if it was included in F#.
<p>In investigating this aspect of Haskell, it&#8217;s instructive to open a <a href="http://haskell.org/ghc/">GHC</a> prompt and ask for the &#8220;+&#8221; operator&#8217;s type:
<p><font face="Courier New">Prelude&gt; :t (+)<br />(+) :: (Num a) =&gt; a -&gt; a -&gt; a</font>
<p>This type signature tells us that the &#8220;+&#8221; operator will, for any type &#8216;a&#8217;, take two &#8216;a&#8217; values as input and produce an &#8216;a&#8217; value as output, provided that &#8216;a&#8217; represents a &#8220;number.&#8221;&nbsp; Likewise, if we use it in our own functions:
<p><font face="Courier New">Prelude&gt; let twice x = x + x<br />Prelude&gt; :t twice<br />twice :: (Num a) =&gt; a -&gt; a</font>
<p>We find that the same kind of type signature persists, and that we can safely use it on any number:
<p><font face="Courier New">Prelude&gt; twice 1<br />2<br />Prelude&gt; twice 3.4<br />6.8</font>
<p>What&#8217;s going on here?&nbsp; Essentially, our code is still translated to something like the moviephone-esque F# example above, except that the compiler decides which actual arithmetic functions to use at the last possible moment (when the type &#8216;a&#8217; above is decided, however distant that is from the innermost function&#8217;s use of the &#8220;+&#8221; operator) by a kind of &#8220;moviephone-transform&#8221; of your program (more detail on this transform in a future post).&nbsp; This added constraint &#8220;Num a =&gt;&#8221; says that &#8216;a&#8217; belongs to the &#8220;Num&#8221; type-class, and this type-class membership is defined by the programmer on an ad-hoc basis.
<p>For example, suppose that we&#8217;ve defined a new type of number &#8212; like the <a href="http://en.wikipedia.org/wiki/Peano_numbers">Peano numbers</a>:
<p><font face="Courier New">data Peano = Zero | Succ Peano deriving Eq</font>
<p>Note that this type definition is almost identical to the kind we would write in F#, except that the &#8220;deriving&#8221; piece at the end specifies that the compiler should automatically put this type into the &#8220;Eq&#8221; type-class (allowing <font face="Courier New">Peano</font> values to be compared for equality).
<p>In order to treat these structures as numbers (to put the &#8220;Peano&#8221; type into the &#8220;Num&#8221; type-class), we need to define each function required by the Num type-class:
<p><font face="Courier New">instance Num Peano where<br />&nbsp;&nbsp; p + Zero&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; = p<br />&nbsp;&nbsp; p + (Succ x)&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; = (Succ p) + x<br />&nbsp;&nbsp; p &#8211; Zero&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; = p<br />&nbsp;&nbsp; Zero &#8211; x&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; = Zero<br />&nbsp;&nbsp; (Succ p) &#8211; (Succ x)&nbsp;&nbsp; = p &#8211; x<br />&nbsp;&nbsp; p * Zero&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; = Zero<br />&nbsp;&nbsp; p * (Succ x)&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; = (p * x) + p<br /></font><font face="Courier New">&nbsp;&nbsp; abs p&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; = p<br />&nbsp;&nbsp; signum Zero&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; = 0<br />&nbsp;&nbsp; signum p&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; = 1<br />&nbsp;&nbsp; fromInteger 0&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; = Zero<br />&nbsp;&nbsp; fromInteger n | n &gt; 0 = Succ (fromInteger (n &#8211; 1))</font>
<p>Here, we&#8217;ve implemented the &#8220;+&#8221;, &#8220;-&#8221;, and &#8220;*&#8221; operators by the standard definitions of Peano numbers.&nbsp; The rest of the functions aren&#8217;t very interesting, but are required to make this <font face="Courier New">Num Peano</font> instance consistent with all uses of numbers in Haskell.
<p>We can then test this definition in a fairly straightforward way, opening a GHC prompt with the above type/instance initialized (to do this, put the above definitions in a file, peano.hs, and then run: <font face="Courier New">ghci peano.hs</font>):
<p><font face="Courier New">Prelude&gt; let one = Succ Zero<br />Prelude&gt; let two = Succ one<br />Prelude&gt; let three = Succ two<br />Prelude&gt; (one + two) == three<br />True</font>
<p>Our existing functions, defined only over instances of the Num type-class, will also work with this new form of number:
<p><font face="Courier New">Prelude&gt; (twice one) == two<br />True</font>
<p>If this kind of first-order ad-hoc polymorphism were added to F#, it would go a long way toward restoring some of the honest (logically consistent) conveniences of languages like C++ (or Haskell, for that matter).&nbsp; But that&#8217;s not all that type-classes can do.&nbsp; In the next article, I&#8217;ll show how they also subsume more language features, like inheritance and sub-typing, in an equally rigorous and logically consistent way.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.lab49.com/archives/2895/feed</wfw:commentRss>
		<slash:comments>7</slash:comments>
		</item>
		<item>
		<title>Speeling problems? Trie F#.</title>
		<link>http://blog.lab49.com/archives/2841</link>
		<comments>http://blog.lab49.com/archives/2841#comments</comments>
		<pubDate>Mon, 09 Mar 2009 13:17:56 +0000</pubDate>
		<dc:creator>Kalani Thielen</dc:creator>
				<category><![CDATA[Computer Science]]></category>
		<category><![CDATA[Conversations in the Lab]]></category>
		<category><![CDATA[F#]]></category>
		<category><![CDATA[Functional Programming]]></category>

		<guid isPermaLink="false">http://blog.lab49.com/archives/2841</guid>
		<description><![CDATA[Maybe you just have large fingers.  Maybe you serve some traders, through a trade-entry language, and they have large fingers.  Whatever the reason, humans misspell words. If you write software for humans, or if you yourself are a human, read on for a simple, classical solution to this ancient problem, expressed concisely in F#. The [...]]]></description>
			<content:encoded><![CDATA[<p>Maybe you just have large fingers.  Maybe you serve some traders, through a <a href="http://mdavey.wordpress.com/2008/11/02/mgrammer-quick-trade-entry/">trade-entry language</a>, and <em>they</em> have large fingers.  Whatever the reason, humans misspell words.</p>
<p>If you write software for humans, or if you yourself are a human, read on for a simple, classical solution to this ancient problem, expressed concisely in F#.</p>
<p><span id="more-2841"></span></p>
<p><strong>The first problem is recognizing that there is a problem</strong></p>
<p>Yes, your parents were right.  You can&#8217;t be helped if you don&#8217;t know that you need help.  That&#8217;s why it&#8217;s important, right off the bat, to be able to determine that a word is actually misspelled before you try to correct it.  We&#8217;ll see, shortly, that correcting a misspelled word is only a slightly different problem than recognizing that it is misspelled.</p>
<p>To determine whether or not a word is spelled correctly, we need to consult a dictionary.  Paper dictionaries typically sort all known words in alphabetical order, forcing humans to validate spelling by a form of binary search (better at least than a linear search!), which incurs a log(N) cost for each lookup (with N being the number of words in the dictionary).  That might be acceptable just for validation, but when we search for spelling correction options that will translate to a series of lookups &#8212; enough to make it worthwhile to choose a different structure to represent our dictionary.</p>
<p>Enter the <a href="http://en.wikipedia.org/wiki/Prefix_tree">prefix-tree</a>, or trie.  Tries store dictionaries efficiently by grouping all strings with a common prefix.  This defines a recursive structure, so that  to verify that a word is in the dictionary represented by a trie, we find the sub-trie associated with the first character of the word and then we verify that the remaining suffix of the word is in the sub-trie (recursively).</p>
<p>So, for example, the dictionary consisting of the following words:</p>
<p><span style="font-family: Courier New;">Hello<br />
Help<br />
world<br />
work<br />
Jimmy<br />
Jim</span></p>
<p>Would produce the following trie structure:</p>
<p><a href="http://blog.lab49.com/wp-content/uploads/2009/03/dg.gif"><img src="http://blog.lab49.com/wp-content/uploads/2009/03/dg.gif" alt="" width="116" height="230" /></a> </p>
<p>Here, edges N steps from the root represent the Nth character of some test string, and large circles represent valid words in the dictionary (of course, not all prefixes of valid words should be valid words themselves!).  And determining whether or not a word is in the dictionary just takes an amount of time proportional to the length of the word itself, rather than the size of the dictionary.</p>
<p><strong>Just a short distance to the solution</strong></p>
<p>Now we have an efficient method to determine whether or not a particular string is in our dictionary, but how can we use this structure to search for &#8220;similar&#8221; words once we determine that a word isn&#8217;t valid?  As my friend Doug Finke <a href="http://dougfinke.com/blog/index.php/2009/02/17/powershell-an-exercise-in-species-barcoding/">has pointed out</a>, the critical definition of &#8220;similarity&#8221; is the edit-distance (or <a href="http://en.wikipedia.org/wiki/Levenshtein_distance">Levenshtein distance</a>).</p>
<p>The edit-distance between two strings is defined as the minimum number of edits necessary to translate one into the other.  Within this definition, an &#8220;edit&#8221; means inserting a character somewhere within the string, modifying a character, or deleting a character.  For our purposes (though this is easily generalized) when we determine that a word is misspelled, we&#8217;ll search for all words in the dictionary that are at most an edit-distance of 1 from the erroneous word.</p>
<p>So, suppose that we had the same dictionary as above, and we were presented with the word &#8220;Jimky.&#8221;  Put aside for the moment that we know the obvious correction.  If we want to find all strings in the dictionary that are an edit-distance of 1 from &#8220;Jimky,&#8221; we can derive those from the definition of edit-distance itself:</p>
<p><strong>Inserts</strong><br />
<span style="font-family: Courier New;">?Jimky<br />
J?imky<br />
Ji?mky<br />
Jim?ky<br />
Jimk?y<br />
Jimky?<br />
</span><br />
<strong>Updates</strong><br />
<span style="font-family: Courier New;">?imky<br />
J?mky<br />
Ji?ky<br />
Jim?y<br />
Jimk?<br />
</span><br />
<strong>Deletes</strong><br />
<span style="font-family: Courier New;">imky<br />
Jmky<br />
Jiky<br />
Jimy<br />
Jimk</span></p>
<p>Here, &#8220;?&#8221; means &#8220;any <em>valid</em> character&#8221; (in other words, each string with a &#8220;?&#8221; above actually represents a <em>set</em> of strings &#8212; one string for each valid replacement of &#8220;?&#8221;).</p>
<p>This might seem to present an expensive proposition, possibly testing (and constructing!) a large number of strings for even moderately-sized words.  However, we can rest a bit easier in recognizing that several of these generated strings share a common prefix (e.g.: consider &#8220;Jim?ky&#8221; and &#8220;Jim?y&#8221; sharing the prefix &#8220;Jim&#8221;).  Luckily for us, we already have a data structure ideally suited for finding multiple words with a common prefix &#8212; the trie &#8212; which we can use to group all of these alternatives together and accept or reject them in bulk.</p>
<p>There is very little left now to bringing our solution together.  We can simply walk the dictionary-trie with our erroneous word.  Prior to taking each step, we consider what words we could find if we were to insert a character at the current level, replace the first character and search for the remaining suffix at the current level, or delete the first character and search for the remaining suffix from the current level &#8212; then we follow the current character in this word to the next level of the trie, and continue this process for the remainder of the string.</p>
<p>This method saves us some potential pain.  We don&#8217;t need to explicitly construct all strings that could possibly be an edit-distance of 1 from our test string.  Also, we have the exact information we need at each point that we decide to substitute valid characters for &#8220;?&#8221; (i.e.: at a given level in a trie, we always know what outgoing edges there are and what their labels are).</p>
<p>All that&#8217;s left now is to implement it.</p>
<p><strong>A little F#</strong></p>
<p>The first place to start is in representing a trie as a data-type.  A reasonable definition could be:</p>
<p><span style="font-family: Courier New;"><span style="color: #0000ff;">type</span> (&#8216;k,&#8217;a) trie = TNode <span style="color: #0000ff;">of</span> (&#8216;a option * Map&lt;&#8217;k,(&#8216;k,&#8217;a) trie&gt;)</span></p>
<p>Here, the type-variables <span style="font-family: Courier New;">&#8216;k</span> and <span style="font-family: Courier New;">&#8216;a</span> represent the base key type and element type (respectively).  A trie is just an associative map, and as with other associative maps we&#8217;re just defining the same kind of key and element types (except here, our actual key will be a sequence of the base key type).</p>
<p>We won&#8217;t really care much about <span style="font-family: Courier New;">&#8216;a</span> (the element type) for this problem, and we&#8217;ll set <span style="font-family: Courier New;">&#8216;k</span> to <span style="color: #0000ff; font-family: Courier New;">char</span>.  It&#8217;s worth noting, though, that the value stored in a trie node is actually an <span style="font-family: Courier New;">&#8216;a option</span> because we won&#8217;t store values in proper prefixes of valid strings (those will have just the <span style="font-family: Courier New;">option</span> value <span style="font-family: Courier New;">None</span>).</p>
<p>The edge/sub-trie relation is saved in a <span style="font-family: Courier New;">Map</span> &#8212; and any type of associative map would do here.  In fact, in principle this edge/sub-trie map could itself be another trie (useful if our key sequence type is a list of strings, or a list of lists of strings, etc&#8230;).  This method of defining a type in terms of a (usually weaker) form of itself is termed &#8220;data-structural bootstrapping&#8221; (by at least one influential book on the subject of <a href="http://www.amazon.com/Purely-Functional-Structures-Chris-Okasaki/dp/0521663504">purely functional data structures</a>).</p>
<p>Next, to be sufficiently general in defining a trie, we will want to abstract away the actual method of iterating over the key sequence and extracting keys.  An easy method of packaging that abstraction in F# is a record of functions, like:</p>
<p><span style="font-family: Courier New;"><span style="color: #0000ff;">type</span> (&#8216;ks, &#8216;k) iter_module =<br />
   {<br />
      eos  : (&#8216;ks -&gt; <span style="color: #0000ff;">bool</span>);<br />
      head : (&#8216;ks -&gt; &#8216;k);<br />
      tail : (&#8216;ks -&gt; &#8216;ks)<br />
   };;</span></p>
<p>Here <span style="font-family: Courier New;">&#8216;ks</span> represents a type that stores a sequence of our key elements, and <span style="font-family: Courier New;">&#8216;k</span> represents the type of our key elements.  The functions in this iterator module should be familiar &#8212; <span style="font-family: Courier New;">eos</span> determines whether or not a key-sequence is at its end, <span style="font-family: Courier New;">head</span> gets the current key-value in a key-sequence, and <span style="font-family: Courier New;">tail</span> increments the key-sequence iterator.</p>
<p>But for this spelling-correction problem we don&#8217;t need to be so general.  We already know that our base key type is <span style="color: #0000ff; font-family: Courier New;">char</span>, and so we can define an iterator over a sequence of <span style="color: #0000ff; font-family: Courier New;">char</span>s straightforwardly as a pair of a string (the sequence of <span style="color: #0000ff; font-family: Courier New;">char</span>s) and an <span style="color: #0000ff; font-family: Courier New;">int</span> (the current position in that sequence).  All that&#8217;s left then is to fill out a module definition that assumes this representation:</p>
<p><span style="font-family: Courier New;"><span style="color: #0000ff;">let </span>siterm : (string * <span style="color: #0000ff;">int</span>, <span style="color: #0000ff;">char</span>) Trie.iter_module =<br />
{<br />
  eos  = <span style="color: #0000ff;">fun</span> (s, i) -&gt; i &gt;= String.length s;<br />
  head = <span style="color: #0000ff;">fun</span> (s, i) -&gt; s.[i];<br />
  tail = <span style="color: #0000ff;">fun</span> (s, i) -&gt; (s, i+1)<br />
}<br />
;;</span></p>
<p>We&#8217;ll assume the generic iterator module when implementing tries, and we&#8217;ll come back to this instance when we get to implementing spelling correction.  For now it&#8217;s useful to keep in mind as a justification for the key sequence iterator abstraction.</p>
<p>Now, we can define some simple functions over the nodes of a trie.  First, to extract the <span style="font-family: Courier New;">option</span> value associated with a node:</p>
<p><span style="font-family: Courier New;"><span style="color: #0000ff;">let</span> node_value = <span style="color: #0000ff;">function</span><br />
| TNode (ov, _) -&gt; ov<br />
;;</span></p>
<p>Similarly, to extract the map representing connections from the current trie node to sub-tries:</p>
<p><span style="font-family: Courier New;"><span style="color: #0000ff;">let</span> node_map = <span style="color: #0000ff;">function</span><br />
| TNode (_, m) -&gt; m<br />
;;</span></p>
<p>To determine whether a trie is empty, and the standard empty trie:</p>
<p><span style="font-family: Courier New;"><span style="color: #0000ff;">let</span> is_empty tn = Map.is_empty (node_map tn);;<br />
<span style="color: #0000ff;">let</span> empty_trie  = TNode (None, Map.empty);;</span></p>
<p>And to find the sub-trie (if it exists) from a given node, along a specific edge:</p>
<p><span style="font-family: Courier New;"><span style="color: #0000ff;">let</span> find_subtrie tn k =<br />
 <span style="color: #0000ff;">try</span><br />
  Map.find k (node_map tn)<br />
 <span style="color: #0000ff;">with</span><br />
  Not_found -&gt; empty_trie<br />
;;</span></p>
<p>Now, the first critical function defined on a trie is to update it (here using the key sequence iterator module and maintaining the assumption that common string prefixes will be shared):</p>
<p><span style="font-family: Courier New;"><span style="color: #0000ff;">let </span>add m tn ks v =<br />
 <span style="color: #0000ff;">let rec </span>upd tn&#8217; ks&#8217; =<br />
  <span style="color: #0000ff;">if</span> (m.eos ks&#8217;) <span style="color: #0000ff;">then</span><br />
   TNode (Some v, (node_map tn&#8217;))<br />
  <span style="color: #0000ff;">else</span><br />
   <span style="color: #0000ff;">let</span> k    = (m.head ks&#8217;) <span style="color: #0000ff;">in<br />
   let <span style="color: #000000;">ov   = node_value tn&#8217; </span>in<br />
   let <span style="color: #000000;">tn&#8221; = upd (find_subtrie tn&#8217; k) (m.tail ks&#8217;)</span> in</span><br />
    TNode (ov, Map.add k tn&#8221; (node_map tn&#8217;))<br />
 <span style="color: #0000ff;">in</span><br />
  upd tn ks<br />
;;</span></p>
<p>Similarly, to lookup the <span style="font-family: Courier New;">option</span> value associated with a string:</p>
<p><span style="font-family: Courier New;"><span style="color: #0000ff;">let</span> lookup m tn ks =<br />
 <span style="color: #0000ff;">let rec </span>lv tn&#8217; ks&#8217; =<br />
  <span style="color: #0000ff;">if</span> (m.eos ks&#8217;) <span style="color: #0000ff;">then</span><br />
   node_value tn&#8217;<br />
  <span style="color: #0000ff;">else</span><br />
   <span style="color: #0000ff;">let</span> k = (m.head ks&#8217;) <span style="color: #0000ff;">in</span><br />
    lv (find_subtrie tn&#8217; k) (m.tail ks&#8217;)<br />
 <span style="color: #0000ff;">in</span><br />
  lv tn ks<br />
;;</span></p>
<p>Finally, we can determine whether or not a specific word is valid in the trie by a simple use of the <span style="font-family: Courier New;">lookup</span> function:</p>
<p><span style="font-family: Courier New;"><span style="color: #0000ff;">let</span> mem m tn ks =<br />
 <span style="color: #0000ff;">match</span> (lookup m tn ks) <span style="color: #0000ff;">with</span><br />
| Some _ -&gt; <span style="color: #0000ff;">true</span><br />
| None   -&gt; <span style="color: #0000ff;">false</span><br />
;;</span></p>
<p>Now, stepping outside of this trie definition, we can concern ourselves with implementing the spelling correction method that we worked out earlier.  First, we&#8217;ll need a couple of simple utilities.  One to determine the suffix of a string (represented by our <span style="font-family: Courier New;">string*<span style="color: #0000ff;">int</span></span> iterator):</p>
<p><span style="font-family: Courier New;"><span style="color: #0000ff;">let</span> suffix (s, i) = String.sub s i (String.length s &#8211; i);;</span></p>
<p>And another, which computes the set of words defined by a trie node if we follow any valid character from that node, and then try to follow a specific <span style="color: #0000ff; font-family: Courier New;">char</span> sequence:</p>
<p><span style="font-family: Courier New;"><span style="color: #0000ff;">let</span> strings_with_suffix pfx trie wi words =<br />
 <span style="color: #0000ff;">let</span> accumulate_paths c trie&#8217; ws =<br />
  <span style="color: #0000ff;">if</span> (mem siterm trie&#8217; wi) <span style="color: #0000ff;">then</span><br />
   Set.add (pfx ^ (string c) ^ (suffix wi)) ws<br />
  <span style="color: #0000ff;">else</span><br />
   ws<br />
 <span style="color: #0000ff;">in</span><br />
  Map.fold accumulate_paths (node_map trie) words<br />
;;</span></p>
<p>In other words, for a prefix P and a suffix S, this function finds P?S (substituting for &#8220;?&#8221; all valid characters that can follow P).</p>
<p>Finally we can write out our real spelling correction function, taking into account the insertions, replacements, and deletions that yield suggestions a maximum edit-distance of 1 from our test word:</p>
<p><span style="font-family: Courier New;"><span style="color: #0000ff;">let </span>suggestions trie word =<br />
  <span style="color: #0000ff;">let rec </span>paths_around_char pfx trie wi words =<br />
   <span style="color: #0000ff;">if</span> (siterm.eos wi) <span style="color: #0000ff;">then</span><br />
    strings_with_suffix pfx trie (&#8220;&#8221;, 0) words<br />
   <span style="color: #0000ff;">else if</span> (is_empty trie) <span style="color: #0000ff;">then</span><br />
    words<br />
   <span style="color: #0000ff;">else</span><br />
    <span style="color: #0000ff;">let </span>c      = siterm.head wi <span style="color: #0000ff;">in</span><br />
    <span style="color: #0000ff;">let</span> wi&#8217;    = siterm.tail wi <span style="color: #0000ff;">in</span><br />
    <span style="color: #0000ff;">let</span> trie&#8217;  = find_subtrie trie c <span style="color: #0000ff;">in</span><br />
    <span style="color: #0000ff;">let</span> ins_ws = strings_with_suffix pfx trie wi words <span style="color: #0000ff;">in</span><br />
    <span style="color: #0000ff;">let</span> rep_ws = strings_with_suffix pfx trie wi&#8217; ins_ws <span style="color: #0000ff;">in</span><br />
    <span style="color: #0000ff;">let</span> del_ws = <span style="color: #0000ff;">if</span> (mem siterm trie wi&#8217;) <span style="color: #0000ff;">then</span><br />
                  Set.add (pfx ^ (suffix wi&#8217;)) rep_ws<br />
                 <span style="color: #0000ff;">else</span><br />
                  rep_ws<br />
    <span style="color: #0000ff;">in</span><br />
     paths_around_char (pfx ^ (string c)) trie&#8217; wi&#8217; del_ws<br />
  <span style="color: #0000ff;">in</span><br />
   paths_around_char &#8220;&#8221; trie (word, 0) Set.empty<br />
;;</span></p>
<p><strong>Finishing touches</strong></p>
<p>To make this spelling corrector useful, some additional supporting code should be written to package it as a command, taking arguments for a dictionary and plaintext file.  We&#8217;ll also need some basic utilities for reading files and splitting them into words.  Additionally, we should provide the option to produce nice <a href="http://graphviz.org/">graphviz</a> diagrams for arbitrary tries (as was used to produce the initial trie diagram in this article):</p>
<p><span style="font-family: Courier New;"><span style="color: #0000ff;">let</span> graphviz ovstr kstr tn =<br />
 <span style="color: #0000ff;">let</span> rec nodes p tn&#8217; =<br />
  <span style="color: #0000ff;">let</span> scs k = nodes (p ^ &#8220;_&#8221; ^ (kstr k)) (find_subtrie tn&#8217; k) <span style="color: #0000ff;">in</span><br />
   <span style="color: #0000ff;">let</span> nshape = <span style="color: #0000ff;">if</span> is_terminal tn&#8217; <span style="color: #0000ff;">then</span> &#8220;circle&#8221; else &#8220;point&#8221; <span style="color: #0000ff;">in</span><br />
   (&#8221; &#8221; ^ p ^ &#8221; [shape=\"" ^ nshape ^ "\" label=\"" ^ (ovstr (node_value tn')) ^ "\"];\n&#8221;) ^<br />
   (String.concat &#8220;&#8221; (List.map scs (path_heads tn&#8217;)))<br />
 <span style="color: #0000ff;">in</span><br />
 <span style="color: #0000ff;">let</span> rec connections p tn&#8217; =<br />
  <span style="color: #0000ff;">let</span><br />
   scs k =<br />
    <span style="color: #0000ff;">let</span> sn = p ^ &#8220;_&#8221; ^ (kstr k) <span style="color: #0000ff;">in</span><br />
    (&#8221; &#8221; ^ p ^ &#8221; -&gt; &#8221; ^ sn ^ &#8221; [ label = \"" ^ (kstr k) ^ "\"];\n&#8221;) ^ (connections sn (find_subtrie tn&#8217; k))<br />
  <span style="color: #0000ff;">in</span><br />
   String.concat &#8220;&#8221; (List.map scs (path_heads tn&#8217;))<br />
 <span style="color: #0000ff;">in</span><br />
&#8220;digraph g {\n&#8221; ^ (nodes &#8220;root&#8221; tn) ^ (connections &#8220;root&#8221; tn) ^ &#8220;}\n&#8221;<br />
;;</span></p>
<p>You can download the complete source as a Visual Studio 2008, F# console project here:</p>
<p><a href="http://blog.lab49.com/wp-content/uploads/2009/03/scheck.zip">scheck.zip</a> (5 KB)</p>
<p>In the attached project, edit the &#8220;dict&#8221; and &#8220;text&#8221; files to taste, or change the project&#8217;s default arguments to generate trie-graphs from the dictionary file.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.lab49.com/archives/2841/feed</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
	</channel>
</rss>

