<?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; Featured Posts</title>
	<atom:link href="http://blog.lab49.com/archives/category/featured-posts/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>RIA: Matrix WebCast</title>
		<link>http://mdavey.wordpress.com/2009/07/21/ria-matrix-webcast/</link>
		<comments>http://mdavey.wordpress.com/2009/07/21/ria-matrix-webcast/#comments</comments>
		<pubDate>Tue, 21 Jul 2009 20:36:12 +0000</pubDate>
		<dc:creator>Matt Davey</dc:creator>
				<category><![CDATA[Featured Posts]]></category>
		<category><![CDATA[Finance]]></category>
		<category><![CDATA[RIA]]></category>

		<guid isPermaLink="false">http://mdavey.wordpress.com/?p=1949</guid>
		<description><![CDATA[Finextra webcast &#8211; registration here.
       <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=mdavey.wordpress.com&#38;blog=18454&#38;post=1949&#38;subd=mdavey&#38;ref=&#38;feed=1" />]]></description>
			<content:encoded><![CDATA[<div class='snap_preview'>
<p>Finextra <a href="http://www.ashorten.com/2009/07/21/upcoming-webcast-featuring-morgan-stanley-matrix-ria/">webcast</a> &#8211; registration <a href="http://www.finextra.com/fullfeature.asp?id=1169">here</a>.</p>
<p>  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/mdavey.wordpress.com/1949/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/mdavey.wordpress.com/1949/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/mdavey.wordpress.com/1949/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/mdavey.wordpress.com/1949/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/mdavey.wordpress.com/1949/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/mdavey.wordpress.com/1949/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/mdavey.wordpress.com/1949/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/mdavey.wordpress.com/1949/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/mdavey.wordpress.com/1949/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/mdavey.wordpress.com/1949/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=mdavey.wordpress.com&amp;blog=18454&amp;post=1949&amp;subd=mdavey&amp;ref=&amp;feed=1" /></div>
]]></content:encoded>
			<wfw:commentRss>http://mdavey.wordpress.com/2009/07/21/ria-matrix-webcast/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>Mix09 Podcast Roundup</title>
		<link>http://blog.lab49.com/archives/2932</link>
		<comments>http://blog.lab49.com/archives/2932#comments</comments>
		<pubDate>Tue, 24 Mar 2009 21:04:05 +0000</pubDate>
		<dc:creator>Daniel Chait</dc:creator>
				<category><![CDATA[.Net]]></category>
		<category><![CDATA[ASP.NET]]></category>
		<category><![CDATA[Featured Posts]]></category>
		<category><![CDATA[Lab49 @ Mix09]]></category>
		<category><![CDATA[Silverlight]]></category>
		<category><![CDATA[Technology]]></category>
		<category><![CDATA[WPF]]></category>
		<category><![CDATA[Web]]></category>

		<guid isPermaLink="false">http://blog.lab49.com/archives/2932</guid>
		<description><![CDATA[Lab49’s Marc Jacobs and I were out at Microsoft’s Mix09 conference last week and, in conjunction with Zoom-In Online, we produced a number of blog postings &#38; podcasts. We produced a bunch of stuff, so here are all the podcasts in one place for your easy consumption.&#160; As you will see &#38; hear there’s a [...]]]></description>
			<content:encoded><![CDATA[</p>
<p>Lab49’s <a href="http://www.lab49.com/aboutus/management/marcjacobs" target="_blank">Marc Jacobs</a> and I were out at Microsoft’s Mix09 conference last week and, in conjunction with <a title="Zoom-In Online" href="http://www.zoom-in.com" target="_blank">Zoom-In Online</a>, we produced a number of blog postings &amp; podcasts.</p>
<p>We produced a bunch of stuff, so here are all the podcasts in one place for your easy consumption.&#160; As you will see &amp; hear there’s a lot to keep up on.&#160; But there was so much great information and exciting new developments that I’m sure we didn’t cover it all! </p>
<ul>
<li>Christian Schormann, Group Program Manager for Expression Blend -&#160; <a href="https://mail.lab49.com/exchweb/bin/redir.asp?URL=http://edgecastcdn.net/0005A0/blog/mix09_ChristianSchormann.mp3">http://edgecastcdn.net/0005A0/blog/mix09_ChristianSchormann.mp3</a></li>
<li>James Pratt, Senior Product Manager for Internet Explorer &#8211; <a href="https://mail.lab49.com/exchweb/bin/redir.asp?URL=http://edgecastcdn.net/0005A0/blog/mix09_JamesPratt.mp3">http://edgecastcdn.net/0005A0/blog/mix09_JamesPratt.mp3</a></li>
<li>John Lam, Program Manager, Dynamic Language Runtime &#8211; <a href="https://mail.lab49.com/exchweb/bin/redir.asp?URL=http://edgecastcdn.net/0005A0/blog/mix09_JohnLam.mp3">http://edgecastcdn.net/0005A0/blog/mix09_JohnLam.mp3</a></li>
<li>Johnny Lee, Researcher, Microsoft Applied Sciences &#8211; <a href="https://mail.lab49.com/exchweb/bin/redir.asp?URL=http://edgecastcdn.net/0005A0/blog/mix09_JohnnyLee.mp3">http://edgecastcdn.net/0005A0/blog/mix09_JohnnyLee.mp3</a></li>
<li>Kevin Gjerstadt, Principal Group Program Manager, WPF &#8211; <a href="https://mail.lab49.com/exchweb/bin/redir.asp?URL=http://edgecastcdn.net/0005A0/blog/mix09_KevinGjerstad.mp3">http://edgecastcdn.net/0005A0/blog/mix09_KevinGjerstad.mp3</a></li>
<li>Lou Carbone, Founder &amp; CEO of Experience Engineering &#8211; <a href="https://mail.lab49.com/exchweb/bin/redir.asp?URL=http://edgecastcdn.net/0005A0/blog/mix09_LouCarbone.mp3">http://edgecastcdn.net/0005A0/blog/mix09_LouCarbone.mp3</a></li>
</ul>
<p>Enjoy listening to these.</p>
<p>Also you should check out Marc’s blog postings <a title="Marc Jacobs&#39;s blog postings from Mix09" href="http://www.zoom-in.com/blog/marc-jacobs" target="_blank">here</a>.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.lab49.com/archives/2932/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
<enclosure url="http://edgecastcdn.net/0005A0/blog/mix09_ChristianSchormann.mp3" length="15263920" type="audio/mpeg" />
<enclosure url="http://edgecastcdn.net/0005A0/blog/mix09_JamesPratt.mp3" length="12081570" type="audio/mpeg" />
<enclosure url="http://edgecastcdn.net/0005A0/blog/mix09_JohnLam.mp3" length="11799863" type="audio/mpeg" />
<enclosure url="http://edgecastcdn.net/0005A0/blog/mix09_JohnnyLee.mp3" length="23988391" type="audio/mpeg" />
<enclosure url="http://edgecastcdn.net/0005A0/blog/mix09_KevinGjerstad.mp3" length="11296646" type="audio/mpeg" />
<enclosure url="http://edgecastcdn.net/0005A0/blog/mix09_LouCarbone.mp3" length="11602589" type="audio/mpeg" />
		</item>
		<item>
		<title>Learning C# Fast</title>
		<link>http://blog.lab49.com/archives/2664</link>
		<comments>http://blog.lab49.com/archives/2664#comments</comments>
		<pubDate>Tue, 18 Nov 2008 02:18:46 +0000</pubDate>
		<dc:creator>Choy Rim</dc:creator>
				<category><![CDATA[Featured Posts]]></category>
		<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false">http://blog.lab49.com/?p=2664</guid>
		<description><![CDATA[An experienced C++ developer recently asked me what he needed to focus on as he learns C# and .net. He&#8217;s already reading books and going through exercises and was looking for some guidance to speed the process up. Being naturally overconfident and condescending, I was more than happy to furnish a lecture or two. Surprisingly [...]]]></description>
			<content:encoded><![CDATA[<p>An experienced C++ developer recently asked me what he needed to focus on as he learns C# and .net. He&#8217;s already reading books and going through exercises and was looking for some guidance to speed the process up. Being naturally overconfident and condescending, I was more than happy to furnish a lecture or two. Surprisingly enough, the one of the emails was coherent enough to share.</p>
<p>I switched from C++ to Java and then Java to C# so I feel somewhat qualified to speak on the topic of switching languages.</p>
<p>Here my recommendations to guide your language studies:</p>
<ul>
<li>Leverage existing strengths. </li>
<li>Attack “cognitive noise”. </li>
<li>Consider contributing to an open source project. </li>
</ul>
<p><span id="more-2664"></span></p>
<h3><b>Leverage existing strengths</b></h3>
<p>You’re still a great coder. Then the only issue is finding way to manifest that greatness on this new platform. Identify some of those techniques and capabilities from C++ that you’re awesome in, and find the “.net way” of doing the same thing. By “.net way,” I mean finding something appropriate for the platform instead of doing a literal port of C++ techniques to C#. In all likelihood, you have some “cash cow” knowledge that made you valuable in the C++ world. If you were an STL god, then go through the .net generic collections and find their limitations and strengths.</p>
<p>For example, if you’re wondering whether to learn IL, you should ask yourself, “did I get into the machine code when I worked with C++?”&#160; If you were good at disassembling and/or stepping through code with gdb, windebug or what-have-you, then you should study the .net way of the same. It served you well as a C++ coder – so it’s a cash cow. It has a high likelihood of serving you well in C#. You tend to ask yourself the same questions in C# as you do in C++. “I wonder what that looks like in IL?”</p>
<p>For other features (like attributes and serialization) that don’t have direct C++ equivalents, find out why they’re useful and how you have accomplished similar things in the past. If you find that the feature is useful for one of your cash cows, then study in-depth. Otherwise, study it only when a real business case might find it useful.</p>
<h3><b>Attack cognitive noise</b> </h3>
<p>As far as I can tell, the biggest obstacle to a new language is not the language. It is just getting into the “zone” – being effective, more signal, less noise. A lot of coding is spent addressing noise elements. For example, an inordinate amount of time can be wasted on naming stuff, access control, organizing directories, deployment units, unit testing, navigating between source files, getting documentation, and trying to do things the way I used to. In the beginning, most of my code-test-debug cycle is spent thinking about noise items. Just navigating the IDE is a significant cognitive burden.</p>
<p>When you notice this cognitive noise, attack it forcefully. Your goal is to find ways to reduce the cognitive load. Give yourself a time limit, say, an hour to find a better way.</p>
<p>For example, if you keep mistyping “interface,” you can go off into a text editor and type it a thousand times.</p>
<h3><b>Consider contributing to an open source project</b></h3>
<p>When I made the transition from Java to C#, I joined the Spring.NET project. I had been using Spring in Java and was going to miss the framework dearly. I learned a tremendous amount from all the developers. Just reading the code addressed most of the cognitive noise issues. This worked well because (1) I knew a lot about Spring Java, and (2) Spring.NET had spectacular developers on it.</p>
<p>You may have used some open source C++ stuff, e.g. boost. Some of those have inspired open source ports of those projects. For example, the BGL (Boost Graph Library) inspired QuickGraph.</p>
<p>Observing other more experienced developers on the platform is a great way to learn.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.lab49.com/archives/2664/feed</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Jason Dolinger on Model-View-ViewModel</title>
		<link>http://blog.lab49.com/archives/2650</link>
		<comments>http://blog.lab49.com/archives/2650#comments</comments>
		<pubDate>Thu, 06 Nov 2008 21:19:52 +0000</pubDate>
		<dc:creator>Daniel Simon</dc:creator>
				<category><![CDATA[.Net]]></category>
		<category><![CDATA[Featured Posts]]></category>
		<category><![CDATA[Learning]]></category>
		<category><![CDATA[Seminars]]></category>
		<category><![CDATA[WPF]]></category>
		<category><![CDATA[M-V-VM]]></category>
		<category><![CDATA[Silverlight]]></category>
		<category><![CDATA[Unity]]></category>

		<guid isPermaLink="false">http://blog.lab49.com/?p=2650</guid>
		<description><![CDATA[A while back, Jason Dolinger, a consultant here at Lab49, gave us a presentation on design in WPF with the Model-View-ViewModel pattern and the Unity dependency injection framework. Jason started with an application that one would write in a &#8220;traditional&#8221; way, with button clicks handled by event-handlers in the code-behind that then updated other parts [...]]]></description>
			<content:encoded><![CDATA[<p>A while back, Jason Dolinger, a consultant here at Lab49, gave us a presentation on design in WPF with the <a href="http://blogs.msdn.com/dancre/archive/2006/10/11/datamodel-view-viewmodel-pattern-series.aspx">Model-View-ViewModel</a> pattern and the <a href="http://www.codeplex.com/unity">Unity</a> dependency injection framework.</p>
<p>Jason started with an application that one would write in a &#8220;traditional&#8221; way, with button clicks handled by event-handlers in the code-behind that then updated other parts of the UI.  Using WPF data-binding, Commands, and Unity, he transformed it, piece by piece, in a much more manageable, encapsulated, readable, and testable M-V-VM design.  It was awesome.</p>
<p>It was so awesome, in fact, that after the presentation Jason recorded the demo for all to see <a href="http://www.lab49.com/wp-content/uploads/2011/12/Jason_Dolinger_MVVM.wmv" target="_blank">here</a>.</p>
<p>Check it out.  It&#8217;s the most practically instructive explanation of WPF design I&#8217;ve seen.</p>
<p><strong>UPDATE:</strong> I thought I should mention that while Jason&#8217;s presentation is geared towards WPF, the patterns he describes are very applicable for Silverlight as well.  There are a few things to take note of, though:</p>
<p>1) Jason creates ViewModels that are DependencyObjects.  For some (apparently undocumented) reason, DataContexts in Silverlight cannot be DependencyObject descendants.  That means that you need to implement ViewModels as INotifyPropertyChanged (an option also available for WPF that Jason mentions in his video).  This doesn&#8217;t fundamentally affect the pattern, but should be noted.</p>
<p>2) Unity, which Jason uses for dependency injection, is available for Silverlight right now as part of pre-release Composite WPF &amp; Silverlight (Prism) v2.  You can download it <a href="http://www.codeplex.com/CompositeWPF/Release/ProjectReleases.aspx?ReleaseId=19170">here</a>.  (I haven&#8217;t been able to find Unity for Silverlight as a separate download.)</p>
<p>3) Silverlight does not support bindings for Commands out of the box.  It does, however, expose the ICommand interface.  With just a little bit more work using an &#8220;Attached Behavior&#8221; approach, we can get the kind of Commanding that Jason uses in Silverlight as well.  Check out the description <a href="http://blogs.southworks.net/jdominguez/2008/08/icommand-for-silverlight-with-attached-behaviors/">here</a>.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.lab49.com/archives/2650/feed</wfw:commentRss>
		<slash:comments>26</slash:comments>
<enclosure url="http://www.lab49.com/wp-content/uploads/2011/12/Jason_Dolinger_MVVM.wmv" length="101673673" type="video/asf" />
		</item>
		<item>
		<title>A maze of twisty little Java web service standards, all alike</title>
		<link>http://joemorrison.org/blog/2008/10/22/a-maze-of-twisty-little-java-web-service-standards-all-alike/</link>
		<comments>http://joemorrison.org/blog/2008/10/22/a-maze-of-twisty-little-java-web-service-standards-all-alike/#comments</comments>
		<pubDate>Wed, 22 Oct 2008 21:40:57 +0000</pubDate>
		<dc:creator>Joe Morrison</dc:creator>
				<category><![CDATA[Featured Posts]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[Open Source]]></category>
		<category><![CDATA[SOA]]></category>

		<guid isPermaLink="false">http://joemorrison.org/blog/?p=18</guid>
		<description><![CDATA[It&#8217;s almost impossible to keep up with all the fractal-like Java standards related to web services. As fast as each can be learned, Sun invents another, and a dozen open source implementations appear. For my own sanity I tried to create a rough map of some of them. I&#8217;ll try to avoid making recommendations; my [...]]]></description>
			<content:encoded><![CDATA[<p>It&#8217;s almost impossible to keep up with all the fractal-like Java standards related to web services. As fast as each can be learned, Sun invents another, and a dozen open source implementations appear. For my own sanity I tried to create a rough map of some of them. I&#8217;ll try to avoid making recommendations; my main objective is to sketch out how they fit together.<br />
<span></span><br />
First, it&#8217;s important to understand that there are three main players with implementations of of these standards: <a href="http://www.sun.com/">Sun</a>, the <a href="http://www.apache.org/">Apache</a> foundation, and <a href="http://codehaus.org/">Codehaus</a>. There are many other open source implementations as well, but these are the three 800 pound gorillas, for a total of 2400 pounds, or almost exactly one metric tonne (for our international audience).</p>
<p>Second, keep in mind that there are three important APIs which are inter-related: JAX-WS, JAXB, and StAX. Once you understand how these fit together, everything else falls into place more easily.</p>
<p><strong>JAX-WS</strong></p>
<p>Let&#8217;s begin our journey with the latest Sun standard for creating and consuming web services: <strong>JAX-WS</strong>, which stands for Java API for XML Web Services. This standard was introduced in 2004. You can ignore JAX-RPC, since JAX-WS replaces it.</p>
<p>There are three noteworthy implementations of JAX-WS. The first is from Sun, and is called <strong>JAX-WS RI</strong> for the JAX-WS Reference Implementation (they always had a way with names). The second and third are both from the Apache Group and are called <strong>Axis2</strong> and <strong>CXF</strong>. You can ignore Axis1, XFire, and Celtix, since they are all obsolete. There is also a web service framework called Spring-WS, but it&#8217;s not JAX-WS compliant.</p>
<p>So if you are creating web services in Java, the first order of business is to to choose an implementation to work with, and unless you have a reason not to, you should probably stick to one that complies with JAX-WS, which means either JAX-WS RI, Axis2, or CXF.</p>
<p>Related to these is an open source project from Sun called Web Services Interoperability Technologies (<strong>WSIT</strong>), previously known as Project Tango. This is an implementation of several web service standards (WS-SecurityPolicy, WS-ReliableMessaging, and so on). <strong>Metro</strong> is an open source web service stack which is a combination of JAX-WS RI and WSIT (so it&#8217;s actually a reasonable fourth option).</p>
<p>JAX-WS is oriented around SOAP web services, but many programmers are now using the <a href="http://en.wikipedia.org/wiki/Representational_State_Transfer">REST</a> approach. Sun is coming out with the <strong>JAX-RS</strong> API to support that, but it&#8217;s not quite ready yet.</p>
<p><strong>JAXB</strong></p>
<p>Web service development requires mapping between XML and Java objects. <strong>JAXB</strong> is the Sun API for that (also referred to as JAXB2 since the latest version is the important one). There are two noteworthy implementations: <strong>JAXB-RI</strong> (Sun&#8217;s reference implementation) and <strong>JaxMe</strong> (the unfortunately named contribution from Apache). JaxMe is in the incubation stage and is not formally part of Apache yet. There are many other interesting and popular XML/Java mapping frameworks, but most of them are not compliant with JAXB. Examples include Castor (from Codehaus), JiBX (a spectacularly fast open source implementation), and XMLBeans (a flexible implementation from Apache).</p>
<p>A recurring source of confusion is that in the past, Sun was less clear about the distinction between APIs and reference implementations, so people would take JAXB to mean both, and you would often see online articles like &#8220;Which is better: JAXB or JiBX?&#8221; But today developers should always try to use the JAXB API, which will enable a choice of compliant implementations such as JAXB-RI or JaxMe with minimal or no code changes.</p>
<p><strong>StAX</strong></p>
<p>For Java code that needs to read and write large XML documents quickly without necessarily mapping them to objects, there is the Streaming API for XML (<strong>StAX</strong>). There are several implementations of this API too. There is the Sun Java Streaming XML Parser called <strong>SJSXP</strong> (another snappy name from Sun), the <strong>Woodstox</strong> open source implementation which is excellent, and the <strong>StAX reference implementation</strong> from Codehaus which is referred to simply as StAX (unfortunately perpetuating the confusion between APIs and implementations). <strong>Xerces</strong> is a streaming XML processing library which used to be part of the Apache project, and work was underway to make it StAX compliant, but that was dropped.</p>
<p><strong>Putting it all together</strong></p>
<p>Web services need to process XML, sometimes mapping it to and from Java objects (e.g. for creating proxy objects and an RPC-like experience), and sometimes processing it directly (e.g. for streaming results when high performance is needed). Therefore Sun designed the JAX-WS API to rely on the JAXB API, which makes perfect sense; any JAX-WS compliant web service implementation should therefore be able to use any JAXB compliant mapping library. Other relationships between these APIs are up to individual implementations. For example, JAX-WS RI supports the StAX API, so you can use any StAX implementation for streaming. CXF also supports the StAX API, as well as a host of Java/XML mapping options including JAXB (allowing the use of any JAXB compliant implementation), XMLBeans, Castor, and JiBX. Yes, they are heroes.</p>
<p>So if you get confused, just ask yourself clarifying questions like: Does this Java web service library support JAX-WS? Which JAXB compliant Java/XML mapping implentation shall I use? Which is better for processing streaming XML? Woodstox or the StAX reference implementation?</p>
<p>If you&#8217;re still confused, then just accept the recommendations I promised not to make: Use CXF for your web services (which complies with JAX-WS), JAXB-RI for your Java/XML mapping (which complies with JAXB), and Woodstox for streaming (which complies with StAX).</p>
]]></content:encoded>
			<wfw:commentRss>http://joemorrison.org/blog/2008/10/22/a-maze-of-twisty-little-java-web-service-standards-all-alike/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Practical PLT Part 2: An S-Expression Parser</title>
		<link>http://blog.lab49.com/archives/2220</link>
		<comments>http://blog.lab49.com/archives/2220#comments</comments>
		<pubDate>Fri, 02 May 2008 01:44:15 +0000</pubDate>
		<dc:creator>Kalani Thielen</dc:creator>
				<category><![CDATA[Featured Posts]]></category>
		<category><![CDATA[Languages]]></category>

		<guid isPermaLink="false">http://blog.lab49.com/archives/2220</guid>
		<description><![CDATA[In the last article we saw how to build a simple interpreter.&#160; We quickly ran into the problem that complex program terms (like the definition of the factorial function) were incredibly difficult to construct manually.&#160; In this article we&#8217;ll address that problem by first establishing a shorthand for program terms: S-Expressions.&#160; Then we&#8217;ll see how [...]]]></description>
			<content:encoded><![CDATA[<p>In the <a href="http://blog.lab49.com/archives/2013">last article</a> we saw how to build a simple interpreter.&nbsp; We quickly ran into the problem that complex program terms (like the definition of the factorial function) were incredibly difficult to construct manually.&nbsp; In this article we&#8217;ll address that problem by first establishing a <em>shorthand</em> for program terms: S-Expressions.&nbsp; Then we&#8217;ll see how we can mechanically translate textual S-Expressions into the linked <font face="Courier New">Pair</font> structure that our interpreter requires.</p>
<p><span id="more-2220"></span></p>
<p><strong>Philosophical Preliminaries</strong></p>
<p>We first got into trouble in our interpreter when we introduced compound expressions.&nbsp; Primitive <font face="Courier New">Number</font> and <font face="Courier New">Symbol</font> values were still fairly easy to construct (and should be even simpler in our S-Expression form), but constructing a program to sum three numbers was still difficult.&nbsp; It required a box-pointer diagram like this:</p>
<p>&nbsp;</p>
<p>Further, we said that this corresponded to an S-Expression: <font face="Courier New">(+ 1 (+ 1 1))</font>.</p>
<p>This example demonstrates that we have three important cases to consider when parsing expressions: symbols (as &#8220;+&#8221; in the above example), numbers, and (trickiest of all) lists of expressions (everything between parentheses, broken by spaces).</p>
<p>Here we can significantly simplify the problem of parsing lists by <em>flattening</em> the representation.&nbsp; In this case, that means recognizing that parsing <font face="Courier New">(+ 1 (+ 1 1))</font> can be viewed as parsing <font face="Courier New">(+ 1 <strong><em>b</em></strong>)</font> where <strong><em><font face="Courier New">b</font></em></strong> is the result of parsing <font face="Courier New">(+ 1 1)</font>.&nbsp; So we need to be able to <em>set aside</em> a parsed-list mid-way, and <em>resume</em> it later with the result of a nested parsed-list.</p>
<p>Now we can use the &#8220;<font face="Courier New">(</font>&#8221; character as an indication that a new list is beginning, and &#8220;<font face="Courier New">)</font>&#8221; that the most current list has ended.</p>
<p>Finally, we have a strategy for parsing S-Expressions.&nbsp; To parse an expression, we ignore characters up to the first non-whitespace character.&nbsp; If it&#8217;s numeric, process the rest of the input up to a non-numeric character as data for a <font face="Courier New">Number</font> value, construct the <font face="Courier New">Number</font>, and return it.&nbsp; Likewise (but for alphabetic characters), construct <font face="Courier New">Symbol</font> values.&nbsp; If a &#8220;<font face="Courier New">(</font>&#8221; character is encountered, push a new <font face="Courier New">Pair</font> value onto <em>the stack</em>, then proceed to parse sub-expressions by allocating a new <font face="Courier New">Pair</font> for each one, linked to the end of the list on the top of the stack.&nbsp; Finally, when a &#8220;<font face="Courier New">)</font>&#8221; character is found, pop the <font face="Courier New">Pair</font> from the top of <em>the stack</em> and either insert it in the outer list (if the stack isn&#8217;t empty), or return it as the final result.</p>
<p>This informal description essentially captures a <em><a href="http://en.wikipedia.org/wiki/Push_down_automaton">push-down automaton</a></em>.&nbsp; By explicitly defining the set of states we can be in, rules for transitioning from one state to the next, and rules for constructing terms from the strings captured between states, we can completely define our S-Expression parser.</p>
<p><strong>Actual Code</strong></p>
<p>Just as we did last time, we&#8217;ll start with the basic type signature of the function we aim to define:</p>
<p><font face="Courier New">Value* ReadSExpression(std::istream&amp; input);<br /></font>
<p>This says that if we can provide a source of text (whether from the console, a file, the network, etc), the <font face="Courier New">ReadSExpression</font> function will produce a <font face="Courier New">Value </font>usable by our interpreter.</p>
<p>Using the general strategy of defining a push-down automaton outlined above, we ought to be able to create a class to encapsulate that process, which should be straightforward to use in our final implementation of <font face="Courier New">ReadSExpression</font> by the end of this article.</p>
<p>Following this trail of thought, we can immediately begin by making explicit the set of states we expect to be in:</p>
<p><font face="Courier New"><font color="#0000ff">enum</font> SExprReadState<br />{<br />&nbsp;&nbsp;&nbsp; LookingForValue,<br />&nbsp;&nbsp;&nbsp; ReadingAtom<br />};</font></p>
<p>Here we&#8217;ll collapse the states for reading a <font face="Courier New">Symbol</font> or a <font face="Courier New">Number</font> into the <font face="Courier New">ReadingAtom</font> state (once we&#8217;ve read the &#8220;atom&#8221; we&#8217;ll determine which type to use).</p>
<p>Now we&#8217;ll need some machinery for understanding these states and the various transitions between them that we may define.&nbsp; I&#8217;ve prepared this machinery ahead of time (which can be safely ignored until the end, when we&#8217;ve got to compile the whole thing) in a class, <font face="Courier New">StreamFSM</font>:</p>
<p><font face="Courier New">&nbsp;&nbsp;&nbsp; <a href="http://code.lab49.com/stackland/trunk/scm/parse/StreamFSM.hpp">StreamFSM.hpp</a></font></p>
<p>To use this class, we&#8217;ll need to provide it with a <em>character type</em> (<font face="Courier New" color="#0000ff">char</font> should be good enough, unless we&#8217;ll need to parse UNICODE), a <em>state type</em> (our <font face="Courier New">SExprReadState</font> above), and the <em>implementation type</em> (the type of the S-Expression reader we intend to define).&nbsp; We can conveniently forward-declare the whole bundle like this:</p>
<p><font face="Courier New"><font color="#0000ff">class</font> SExprReader;<br /><font color="#0000ff">typedef</font> StreamFSM&lt;<font color="#0000ff">char</font>, SExprReadState, SExprReader&gt; SERBase;</font></p>
<p>Now we can begin to define the actual <font face="Courier New">SExprReader</font> class.&nbsp; Here we&#8217;ll inherit from the StreamFSM to import the basic machinery, which lets us define our initial state (<font face="Courier New">LookingForValue</font>), the procedures to invoke when reading characters in any of our defined states, and the procedures to invoke when transitioning between states:</p>
<p><font face="Courier New"><font color="#0000ff">class</font> SExprReader : <font color="#0000ff">public</font> SERBase<br />{<br /><font color="#0000ff">public</font>:<br />&nbsp; SExprReader() : SERBase(LookingForValue), output_value(0)<br />&nbsp; {<br />&nbsp;&nbsp; AddStateHandler(LookingForValue, &amp;SExprReader::LookForValue);<br />&nbsp;&nbsp; AddStateHandler(ReadingAtom,&nbsp;&nbsp;&nbsp;&nbsp; &amp;SExprReader::ReadAtom);</p>
<p>&nbsp;&nbsp; AddTransitionHandler<br />&nbsp;&nbsp;&nbsp; (ReadingAtom, AnyState, &amp;SExprReader::AddAtom);<br />&nbsp;&nbsp; AddTransitionHandler<br />&nbsp;&nbsp;&nbsp; (AnyState, EndOfStream, &amp;SExprReader::ValidateState);<br />&nbsp; }</p>
<p>&nbsp; <font color="#008000">// [...]</font></font>
<p>This is the most important part of our parser, so it&#8217;s worth going over the exact meaning of the code above.&nbsp; First, the <font face="Courier New">SExprReader</font> class inherits the parsing machinery from <font face="Courier New">SERBase</font>.&nbsp; In its constructor, <font face="Courier New">SExprReader</font> must give <font face="Courier New">SERBase</font> its initial state (here that initial state is <font face="Courier New">LookingForValue</font>).&nbsp; It also introduces the variable <font face="Courier New">output_value</font> &#8212; which we&#8217;ll see later is the accumulator for the final parse result.</p>
<p>The rest of the constructor here uses <font face="Courier New">AddStateHandler</font> to map states to procedures that should be invoked for each input character (while that state is active), and <font face="Courier New">AddTransitionHandler</font> to map a pair of <em>meta-states</em> to a procedure that should be invoked when a transition between the two meta-states occurs.&nbsp; A meta-state can be the symbol <font face="Courier New">AnyState</font> (which stands in for any of our <font face="Courier New">SExprReadState</font> values), <font face="Courier New">StartOfStream</font> (the state that&#8217;s set when we first begin parsing), <font face="Courier New">EndOfStream</font> (the state that&#8217;s set after we&#8217;ve reached the end of input), or any of our standard <font face="Courier New">SExprReadState</font> values.</p>
<p>In English, these state and transition mappings can be read as: When in the <font face="Courier New">LookingForValue</font> state, call the <font face="Courier New">LookForValue</font> procedure.&nbsp; When in the <font face="Courier New">ReadingAtom</font> state, call the <font face="Courier New">ReadAtom</font> procedure.&nbsp; When transitioning between the <font face="Courier New">ReadingAtom</font> state and <strong>any other state</strong>, call the <font face="Courier New">AddAtom </font>procedure.&nbsp; When transitioning between <strong>any state</strong> and the end of input, call the <font face="Courier New">ValidateState</font> procedure.</p>
<p>Continuing to fill out this class, we&#8217;ll need local data for building up parsed expressions:</p>
<p><font face="Courier New"><font color="#0000ff">private</font>:<br />&nbsp;&nbsp;&nbsp; <font color="#0000ff">typedef</font> std::pair&lt;Pair*, Pair*&gt; ListState;<br />&nbsp;&nbsp;&nbsp; <font color="#0000ff">typedef</font> std::stack&lt;ListState&gt;&nbsp;&nbsp; NestedExprs;<br />&nbsp;&nbsp;&nbsp; NestedExprs nested_exprs;<br />&nbsp;&nbsp;&nbsp; <font color="#008000">// [...]</font></font></p>
<p>Here the <font face="Courier New">nested_exprs</font> stack will keep track of lists within lists, and the <font face="Courier New">ListState</font> type will hold the initial <font face="Courier New">Pair</font> node of a linked list, and the final node of the list (this is important because we&#8217;ll append new nodes to the final node, but we&#8217;ll return or insert the initial node).</p>
<p>Now, since it will be the first procedure to run while parsing, let&#8217;s fill out the <font face="Courier New">LookForValue</font> procedure:</p>
<p><font face="Courier New"><font color="#0000ff">void</font> LookForValue(<font color="#0000ff">const char</font>&amp; c)<br />{<br />&nbsp;&nbsp;&nbsp; <font color="#0000ff">switch</font> (c)<br />&nbsp;&nbsp;&nbsp; {<br />&nbsp;&nbsp;&nbsp; <font color="#0000ff">case</font> &#8216;(&#8216;:<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; nested_exprs.push(ListState(0, 0));<br /></font><font face="Courier New">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <font color="#0000ff">break</font>;<br />&nbsp;&nbsp;&nbsp; <font color="#0000ff">case</font> &#8216;)&#8217;:<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <font color="#0000ff">if</font> (nested_exprs.size() &gt; 0)<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; {<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; ListState ne = nested_exprs.top();<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; nested_exprs.pop();<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; AddToResult(ne.first);<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; }<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <font color="#0000ff">else</font><br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; {<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <font color="#0000ff">throw</font> std::runtime_error(&#8220;Unexpected &#8216;)&#8217;.&#8221;);<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; }<br /></font><font face="Courier New">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <font color="#0000ff">break</font>;<br />&nbsp;&nbsp;&nbsp; <font color="#0000ff">default</font>:<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <font color="#0000ff">if</font> (!is_whitespace(c))<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; {<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; PutBack(c);<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; SetState(ReadingAtom);<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <font color="#0000ff">break</font>;<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; }<br />&nbsp;&nbsp;&nbsp; }<br />}</font>
<p>Again, there are a lot of things being done here, so let&#8217;s take them case by case.
<p>If we receive the &#8216;<font face="Courier New">(</font>&#8216; character, we push a new <font face="Courier New">ListState</font> onto the stack (as described earlier).&nbsp; Here we make the choice to push <strong>nil</strong> on the stack initially &#8212; this will allow us to use the (arguably more elegant) notion that <strong>nil</strong> should be equivalent to the empty list: <font face="Courier New">()</font>.&nbsp; We&#8217;ll achieve this by only allocating <font face="Courier New">Pair</font> nodes for the list as they&#8217;re needed (i.e.: as we read actual <font face="Courier New">Value</font>s within the list), so that if none are needed (i.e.: we read &#8220;<font face="Courier New">()</font>&#8220;) the result will be the null pointer, <strong>nil</strong>.
<p>Next, if we receive the &#8216;<font face="Courier New">)</font>&#8216; character, we should complete the active list.&nbsp; If <font face="Courier New">nested_exprs</font> is empty, that means there is no active list (so we raise an error).&nbsp; Otherwise, we pop off the state for the active list, and use the <font face="Courier New">AddToResult</font> procedure (we&#8217;ll examine this later) to either set the final parse result or accumulate this newly-completed list into the next active list.&nbsp; Notice the symmetry with the &#8216;<font face="Courier New">(</font>&#8216; case here, where we&#8217;ll call <font face="Courier New">AddToResult(<font face="Verdana"><strong>nil</strong></font>)</font> if the active list has had nothing accumulated into it.
<p>Finally, if we receive any character that isn&#8217;t whitespace (given the trivial <font face="Courier New">is_whitespace</font> function), we&#8217;ll put that character back (as the <font face="Courier New">PutBack</font> procedure makes the character available for the next state-handler) and set the state to <font face="Courier New">ReadingAtom</font>, which brings us directly to the <font face="Courier New">ReadAtom</font> state-handler:
<p><font face="Courier New"><font color="#0000ff">void </font>ReadAtom(<font color="#0000ff">const char</font>&amp; c)<br />{<br />&nbsp;&nbsp;&nbsp; <font color="#0000ff">if</font> (is_whitespace(c) || c == &#8216;(&#8216; || c == &#8216;)&#8217;)<br />&nbsp;&nbsp;&nbsp; {<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; PutBack(c);<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; SetState(LookingForValue);<br />&nbsp;&nbsp;&nbsp; }<br />}</font>
<p>This state-handler is simple enough.&nbsp; If we get a character that&#8217;s either whitespace or a command to begin/end an active list, the current atom must be ending.&nbsp; Hopefully this jives with the notion that a number should only consist of a contiguous sequence of numeric characters, and a symbol should only consist of a contiguous sequence of alpha-numeric characters.
<p>If we do get a character that indicates the end of the current atom, we just put it back, and switch back into the <font face="Courier New">LookingForValue</font> state (whose handler we&#8217;ve already covered).
<p>You may wonder how the actual parsed text turns into a Value that&#8217;s either returned or inserted into the active list.&nbsp; That&#8217;s the job of the transition handlers, which we&#8217;ll examine now.
<p><font face="Courier New"><font color="#0000ff">void</font> AddAtom(elem_iter begin, elem_iter end)<br />{<br />&nbsp;&nbsp;&nbsp; std::string val(begin, end);<br />&nbsp;&nbsp;&nbsp; <font color="#0000ff">if</font> (is_numeric(val))<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; AddToResult(allocate&lt;Number&gt;(from_string&lt;double&gt;(val)));<br />&nbsp;&nbsp;&nbsp; <font color="#0000ff">else</font><br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; AddToResult(allocate&lt;Symbol&gt;(val));<br />}</font>
<p>Here our <font face="Courier New">SERBase</font> machinery gives our transition handlers the sequence of characters recognized between being in the first state and transitioning to the second.&nbsp; We use it to construct an <font face="Courier New">std::string</font>, which is used either to construct a <font face="Courier New">Number</font> (given the trivial <font face="Courier New">is_numeric</font> function), or a <font face="Courier New">Symbol</font>.&nbsp; Here we also use the <font face="Courier New">allocate&lt;T&gt;</font> function to allocate a garbage-collected value of type <font face="Courier New">T</font>, which in the last article we decided to defer to a later article (and which we&#8217;ll again defer to a later article).&nbsp; Finally, we use the same <font face="Courier New">AddToResult</font> procedure as we used earlier to add this value (in either case) to the overall parse result.&nbsp;
<p>Additionally, if the <font face="Courier New">from_string</font> function doesn&#8217;t seem trivial, we can use some existing machinery provided by the STL to define it as easily as:
<p><font face="Courier New"><font color="#0000ff">template </font>&lt;<font color="#0000ff">typename</font> T&gt;<br />&nbsp;&nbsp;&nbsp; T from_string(<font color="#0000ff">const</font> std::string&amp; s)<br />&nbsp;&nbsp;&nbsp; {<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; T ret;<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; std::istringstream ss(s);<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; ss &gt;&gt; ret;<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <font color="#0000ff">return </font>ret;<br />&nbsp;&nbsp;&nbsp; }</font>
<p>We have one other transition handler to consider, which really just makes sure that we don&#8217;t finish parsing our input if we haven&#8217;t closed off all active lists:
<p><font face="Courier New"><font color="#0000ff">void</font> ValidateState(elem_iter begin, elem_iter end)<br />{<br />&nbsp;&nbsp;&nbsp; <font color="#0000ff">if</font> (nested_exprs.size() &gt; 0)<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <font color="#0000ff">throw</font> std::runtime_error(&#8220;Expected &#8216;)&#8217;.&#8221;);<br />}</font>
<p>Now, we&#8217;ve only left one procedure to define in order to complete our <font face="Courier New">SExprReader</font> class:
<p><font face="Courier New"><font color="#0000ff">void</font> AddToResult(Value* v)<br />{<br /><font color="#008000">&nbsp;&nbsp;&nbsp; // if we&#8217;re not accumulating values on an active list<br />&nbsp;&nbsp;&nbsp; //&nbsp;&nbsp; return this value as the result value<br />&nbsp;&nbsp;&nbsp; // otherwise add this value to the end of the active list</font></font><font face="Courier New"><br /></font><font face="Courier New">&nbsp;&nbsp;&nbsp; <font color="#0000ff">if</font> (nested_exprs.size() == 0)<br />&nbsp;&nbsp;&nbsp; {<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; output_value = v;<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; Detach();<br />&nbsp;&nbsp;&nbsp; }<br />&nbsp;&nbsp;&nbsp; <font color="#0000ff">else</font><br />&nbsp;&nbsp;&nbsp; {<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; NestedExpr&amp; ne&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; = nested_exprs.top();<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; Pair*&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; cur_pair = allocate&lt;Pair&gt;(v, (Value*)0);</p>
<p><font color="#008000">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; // if we&#8217;ve already allocated the initial node,<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; //&nbsp;&nbsp; append the new node as the final node<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; // else set the initial and final node to the new node<br /></font></font><font face="Courier New">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <font color="#0000ff">if</font> (ne.first != 0)<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; ne.second-&gt;tail(cur_pair);<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <font color="#0000ff">else</font><br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; ne.first = cur_pair;</p>
<p></font><font face="Courier New">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; ne.second = cur_pair;<br />&nbsp;&nbsp;&nbsp; }<br /></font><font face="Courier New">}</font> </p>
<p>Finally we&#8217;ve wrapped the trickiest part of the whole problem into this procedure.&nbsp; The purpose of this procedure is to add a single value to the result &#8212; if there are no active lists, the value should be the final result but if there is an active list, the value should be appended to the end of it.&nbsp; Here that&#8217;s achieved essentially with two cases.
<p>In the first case, when <font face="Courier New">nested_exprs</font> is empty that means that there are no active lists to append to.&nbsp; So here we&#8217;ll set <font face="Courier New">output_value</font> to the input <font face="Courier New">Value </font>and use <font face="Courier New">SERBase</font>&#8216;s <font face="Courier New">Detach</font> procedure to stop processing input.&nbsp; This is the most basic case, and in typical circumstances this is where the complete parse bottoms out.
<p>In the next case, however, we&#8217;ve got to append the input <font face="Courier New">Value</font> to the active list.&nbsp; Because we were a little clever in not allocating the initial node before any values are added to the list, we need to account for that decision here.&nbsp; First we allocate a new list node containing just the input value.&nbsp; Then, if the active list has no initial node set, we&#8217;ll make our new node the initial node (this will be the start of the list, and it will be used as the value for the entire list).&nbsp; If the active list does have an initial node, we&#8217;ll append our new node to the active list&#8217;s final node.&nbsp; In either case, this new node will be the new final node for the active list.
<p>Now we just need to make the final result accessible:
<p><font face="Courier New">Value* value() <font color="#0000ff">const</font><br />{<br />&nbsp;&nbsp;&nbsp; <font color="#0000ff">return</font> output_value;<br />}</font>
<p>And we&#8217;ll need to close off the definition of this <font face="Courier New">SExprReader</font> class:
<p><font face="Courier New">};</font>
<p>Now we can bring this all together in a simple function that makes use of this class:
<p><font face="Courier New">Value* ReadSExpression(std::istream&amp; input)<br />{<br />&nbsp;&nbsp;&nbsp; SExprReader reader;<br />&nbsp;&nbsp;&nbsp; reader.Run(input);<br />&nbsp;&nbsp;&nbsp; <font color="#0000ff">return </font>reader.value();<br />}</font>
<p>There we have it!&nbsp; We now have an easy way to parse S-Expressions from any input source (a file, the console, the network, etc), which can be used in conjunction with the <font face="Courier New">Eval </font>function we defined last time!&nbsp; It&#8217;s so easy to use with <font face="Courier New">Eval</font>, in fact, that (provided we make a simple function <font face="Courier New">PrintExpression </font>to serialize a <font face="Courier New">Value </font>to an output stream) we can concisely define <font face="Courier New">REPL</font>, the procedure for running a <strong>R</strong>ead-<strong>E</strong>val-<strong>P</strong>rint-<strong>L</strong>oop:
<p><font face="Courier New"><font color="#0000ff">void </font>REPL(std::istream&amp; i, std::ostream&amp; o, EnvironmentFrame* e)<br />{<br />&nbsp;&nbsp;&nbsp; <font color="#0000ff">while</font> (i)<br />&nbsp;&nbsp;&nbsp; {<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <font color="#0000ff">try</font><br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; {<br /><font color="#008000">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; // read<br /></font>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; Value* inexp = ReadSExpression(i);</p>
<p><font color="#008000">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; // eval<br /></font>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; Value* outexp = Eval(inexp, e); </font>
<p><font face="Courier New"><font color="#008000">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; // print<br /></font>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; PrintExpression(outexp, o); </font>
<p><font face="Courier New"><font color="#008000">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; // loop<br /></font>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; output &lt;&lt; std::endl;<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; }<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <font color="#0000ff">catch </font>(std::runtime_error&amp; e)<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; {<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; o &lt;&lt; &#8220;*&#8221;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &lt;&lt; std::endl<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &lt;&lt; &#8220;** &#8221; &lt;&lt; e.what() &lt;&lt; std::endl<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &lt;&lt; &#8220;*&#8221;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &lt;&lt; std::endl;<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; }<br />&nbsp;&nbsp;&nbsp; }<br />}</font>
<p>Which could be used just as easily to enable an RPC-like session (where input and output streams are network connections) as it could to interact with the console.&nbsp; In the (maybe more typical) example of console use, all that&#8217;s necessary to run a REPL session is the following call (assuming that your root <font face="Courier New">EnvironmentFrame</font> is prepared in the variable <font face="Courier New">root_env</font>):
<p><font face="Courier New">REPL(std::cin, std::cout, root_env);</font>
<p>Clearly we&#8217;ve come a long way toward making very simple what may have once seemed hopelessly complex!
<p>In the next article, we&#8217;ll look at how to make it even more convenient to bind functions to our interpreter, and we&#8217;ll add some advanced functions that take us beyond the simple arithmetic we&#8217;ve done so far into <em>list processing</em>.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.lab49.com/archives/2220/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Practical PLT Part 1: A Scheme Interpreter</title>
		<link>http://blog.lab49.com/archives/2013</link>
		<comments>http://blog.lab49.com/archives/2013#comments</comments>
		<pubDate>Wed, 23 Apr 2008 01:21:16 +0000</pubDate>
		<dc:creator>Kalani Thielen</dc:creator>
				<category><![CDATA[Featured Posts]]></category>
		<category><![CDATA[Languages]]></category>

		<guid isPermaLink="false">http://blog.lab49.com/archives/2013</guid>
		<description><![CDATA[&#8220;What?! You&#8217;re going to create another programming language? It&#8217;s going to be too hard for new people to learn, and there&#8217;s just too much complication involved! Interpreters, type-checkers, compilers, parsers, garbage collectors: these things are too difficult for average programmers to understand. And what&#8217;s the real business value anyway? You shouldn&#8217;t reinvent the wheel! Have [...]]]></description>
			<content:encoded><![CDATA[<p>&#8220;What?! You&#8217;re going to create <em>another</em> programming language? It&#8217;s going to be too hard for new people to learn, and there&#8217;s just too much <strong>complication</strong> involved! Interpreters, type-checkers, compilers, parsers, garbage collectors: these things are too difficult for <em>average programmers</em> to understand. And what&#8217;s the real <strong>business value</strong> anyway? You shouldn&#8217;t reinvent the wheel! Have you taken a look at Jimmy&#8217;s XML configuration system? He says that his files let you just <em>wire up components</em>, and surely that&#8217;s simpler than a new language.&#8221;</p>
<p>This series of articles on practical programming language theory (PLT) will be an answer to the above refrain. In this first article, I&#8217;ll show just how simple it is to make an interpreter for a basic functional language using any modern C++ compiler.</p>
<p><span id="more-2013"></span><br />
<strong>Philosophical Preliminaries</strong>
</p>
<p>What is an interpreter? There are many different ways to view an interpreter, but (since we&#8217;re choosing to implement a <em>particular</em> one) we&#8217;ve got to choose a consistent way to think about it. Generically, an interpreter has some input (a program), and some output (what the program computes). We can view interpretation as the <em>progressive refinement</em> of our program, up to a fixed point. For example, imagine the program <span style="font-family: courier new">1+1+1</span>. The first step in a refinement of this program will either be <span style="font-family: courier new">2+1</span> or <span style="font-family: courier new">1+2</span>, and in this case that choice is arbitrary. Either way, the final result will be <span style="font-family: courier new">3</span>, which can be refined no further (evaluation reaches a fixed point in that <span style="font-size: x-small; font-family: courier new">3</span> evaluates to <span style="font-size: x-small; font-family: courier new">3</span>, which evaluates to <span style="font-size: x-small; font-family: courier new">3</span>, &#8230;).</p>
<p>All that&#8217;s necessary to make this view match our intuition of programming is to add <em>abstractions</em>. An abstraction, as its name implies, is an expression with a single value <em>abstracted</em> out of it. For example, with the expression <span style="font-family: courier new">1+2</span>, we may want to <em>abstract away</em> the number <span style="font-family: courier new">1</span>. This is written <span style="font-family: courier new"><strong>λ</strong>x.x+2</span>. Finally, we&#8217;ll need to <em>apply</em> values to abstractions, which requires substituting the actual value where the abstraction&#8217;s variable appears in its expression. For example, to regain our original <span style="font-family: courier new">1+2</span>, we can write the <em>application</em> <span style="font-family: courier new">((<strong>λ</strong>x.x+2) 1)</span> &#8212; substituting <span style="font-family: courier new">1</span> for <span style="font-family: courier new">x</span> yields <span style="font-family: courier new">1+2</span>.</p>
<p>This perspective is elaborated colorfully in <a href="http://swiss.csail.mit.edu/classes/6.001/abelson-sussman-lectures/">these famous videos</a>, based on Harold Abelson and Gerald Sussman&#8217;s foundational book <a href="http://mitpress.mit.edu/sicp/full-text/book/book.html">Structure and Interpretation of Computer Programs</a>.</p>
<p>This view of interpretation follows the tradition of <a href="http://en.wikipedia.org/wiki/Lambda_calculus">the λ-calculus</a>, in contrast to the view in <a href="http://en.wikipedia.org/wiki/Turing_machine">Turing machines</a>. A useful rule of thumb in thinking about these two views is that the λ-calculus closely matches the way people traditionally think (and write) about calculation, while Turing machines closely match the way real physical computers are organized and manufactured.</p>
<p><strong>Actual Code</strong></p>
<p>Now that we&#8217;ve chosen a theoretical model of computation, we&#8217;ve got to get our hands dirty and write some code to make it work. There are many problems to start with in building a real interpreter, but a good first approximation is to start with the type signature:</p>
<p><span style="font-family: courier new">Value* Eval(Value* program, EnvironmentFrame* env);</span></p>
<p>This says that the <span style="font-family: courier new">Eval</span> function will take a <span style="font-family: courier new">Value</span> and an <span style="font-family: courier new">EnvironmentFrame</span> (a map of variables <span style="font-family: courier new">-&gt;</span> values, which accounts for the substitutions necessary when <em>applying abstractions</em>) and return a <span style="font-family: courier new">Value</span> &#8212; the fixed point of evaluating the input program. We should expect that the following examples of the <span style="font-family: courier new">Eval</span> function should be defined:</p>
<p><span style="font-family: courier new">Eval(1, {}) = 1<br />Eval(<strong>x</strong>, { <strong>x</strong> -&gt; 42 }) = 42<br />Eval(1+1+1, { + -&gt; <em>machine-code</em> }) = 3<br />Eval(((<strong>λ</strong>x.1+x) 2), { + -&gt; <em>machine-code</em> }) = 3 </span></p>
<p>Having covered the essential boundary of the problem, let&#8217;s refine it further to fill out these <span style="font-family: courier new">Value</span> and <span style="font-family: courier new">EnvironmentFrame</span> types, and provide a full definition of this special <span style="font-family: courier new">Eval</span> function.</p>
<p><strong>Data Types</strong></p>
<p>In the example definitions of Eval above, we actually define the function over four different data types. In the first case we interpret a number, in the second case we interpret a symbol (the variable <strong><span style="font-family: courier new">x</span></strong>), in the third case we interpret a compound expression representing the function associated with the symbol &#8220;+&#8221; applied to three numbers, and in the fourth case we apply an abstraction (itself a kind of function) to a value. Somehow we&#8217;ll have to capture all of these cases in the <span style="font-family: courier new">Value</span> data type. Classes in the C++ language give us a method of describing each of these cases, inheriting from the most generic case &#8212; which we can use to define the empty base type:</p>
<p><span style="font-family: courier new"><span style="color: #0000ff">class</span> Value<br />{<br />};</span></p>
<p>Having set this much down, we can try to cover every case we considered above. First, numbers can be defined as:</p>
<p><span style="font-family: courier new"><span style="color: #0000ff">class</span> Number : <span style="color: #0000ff">public</span> Value<br />{<br /><span style="color: #0000ff">public</span>:<br />&nbsp;&nbsp;&nbsp; Number(<span style="color: #0000ff">double</span> v) : val(v) { }<br /><span style="color: #0000ff">&nbsp;&nbsp;&nbsp; double</span> value() <span style="color: #0000ff">const</span> { <span style="color: #0000ff">return</span> val; }<br /><span style="color: #0000ff">private</span>:<br /><span style="color: #0000ff">&nbsp;&nbsp;&nbsp; double</span> val;<br />};</span></p>
<p>This effectively &#8220;boxes&#8221; the primitive <span style="font-family: courier new">double</span> type. Moving on, we can similarly represent symbols:</p>
<p><span style="font-family: courier new"><span style="color: #0000ff">class</span> Symbol : <span style="color: #0000ff">public</span> Value<br />{<br /><span style="color: #0000ff">public</span>:<br />&nbsp;&nbsp;&nbsp; Symbol(std::string v) : val(v) { }<br />&nbsp;&nbsp;&nbsp; std::string value() <span style="color: #0000ff">const</span> { <span style="color: #0000ff">return</span> val; }<br /><span style="color: #0000ff">private</span>:<br />&nbsp;&nbsp;&nbsp; std::string val;<br />};</span></p>
<p>Having put those two cases to rest, we have to deal with the case of compound values. We could approach this in a number of ways, but perhaps the simplest is to view any case of compound values as a <strong>pair</strong> of values. In the case of a compound computation (as in the third example of <span style="font-family: courier new">Eval</span> above), the <strong>head</strong> of the pair will represent the function to apply to the values represented by the <strong>tail</strong> of the pair. Following from this, the tail can be another pair, which allows us to chain together several values (or compound values) up to some final value: <strong>nil</strong>, the empty pair. For example, the expression <span style="font-family: courier new">1+1+1</span> above can be represented in <em>constructor form</em> as:</p>
<p><span style="font-family: courier new">Pair(<strong>+</strong>, Pair(1, Pair(Pair(<strong>+</strong>, Pair(1, Pair(1, <strong>nil</strong>))), <strong>nil</strong>)))</span></p>
<p>This type of structure is commonly visualized in <em>box-pointer diagrams</em> like this:</p>
<p><img alt="(+ 1 (+ 1 1))" src="http://blog.lab49.com/wp-content/uploads/2008/08/box_ptr.jpg"> </p>
<p>Here, each box points to a value, and each box-pair represents a <span style="font-family: courier new">Pair</span> (itself a value), and the image <img src="http://blog.lab49.com/wp-content/uploads/2008/08/nil.jpg">  represents <span style="font-family: courier new">nil</span>.</p>
<p>This structure can also be written as an <em>S-expression</em>: <span style="font-family: courier new">(+ 1 (+ 1 1))</span>.</p>
<p>With all of that said, the actual definition of this pair type is very simple:</p>
<p><span style="font-family: courier new"><span style="color: #0000ff">class</span> Pair : <span style="color: #0000ff">public</span> Value<br />{<br /><span style="color: #0000ff">public</span>:<br />&nbsp;&nbsp;&nbsp; Pair(Value* h, Value* t) : hd(h), tl(t) { }<br />&nbsp;&nbsp;&nbsp; Value* head() <span style="color: #0000ff">const</span> { <span style="color: #0000ff">return</span> hd; }<br />&nbsp;&nbsp;&nbsp; Value* tail() <span style="color: #0000ff">const</span> { <span style="color: #0000ff">return</span> tl; }<br /><span style="color: #0000ff">private</span>:<br />&nbsp;&nbsp;&nbsp; Value* hd; Value* tl;<br />};</span></p>
<p>Finally, we need to define the data type of functions, so that we can make the above program (with its references to a &#8220;+&#8221; function) meaningful and so that we can generally define abstractions.</p>
<p><span style="font-family: courier new"><span style="color: #0000ff">class</span> Function : <span style="color: #0000ff">public</span> Value<br />{<br /><span style="color: #0000ff">public</span>:<br /><span style="color: #0000ff">&nbsp;&nbsp;&nbsp; virtual</span> Value* Invoke(Pair* args, EnvironmentFrame* env)=0;<br />};</span></p>
<p>This leaves us with an interface that all functions must satisfy. It&#8217;s important to define this interface, because we&#8217;ll implement it differently for primitive functions than we will for abstractions. In either case, when a &#8220;function&#8221; is invoked, it will be given an argument list (a linked list of values, as described above) of <em>unevaluated</em> expressions (later we&#8217;ll see why it&#8217;s important that they be unevaluated). Because the argument list is unevaluated, we will also need to provide the <span style="font-family: courier new">EnvironmentFrame</span> (the record of variable/value mappings).</p>
<p>To fill this out, let&#8217;s look at implementing the addition function required by the <span style="font-family: courier new">1+1+1</span> program:</p>
<p><span style="font-family: courier new"><span style="color: #0000ff">class</span> AddFunction : <span style="color: #0000ff">public</span> Function<br />{<br />&nbsp;&nbsp;&nbsp; Value* Invoke(Pair* args, EnvironmentFrame* env)<br />&nbsp;&nbsp;&nbsp; {<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; Number* n1 = (Number*)Eval(args-&gt;head(), env);<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; Pair* arg_tail = (Pair*)args-&gt;tail();</span></p>
<p><span style="font-family: courier new">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; Number* n2 = (Number*)Eval(arg_tail-&gt;head(), env);</span></p>
<p><span style="font-family: courier new">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <span style="font-family: courier new"><span style="color: #0000ff">return</span> allocate&lt;Number&gt;(n1-&gt;value() + n2-&gt;value());<br />&nbsp;&nbsp;&nbsp; }<br />};</span></span></p>
<p>Later we&#8217;ll see how primitive functions can be defined more concisely, but for now it&#8217;s useful to stop here and understand just what the class is doing.First of all, it&#8217;s a subclass of <span style="font-family: courier new">Function</span>, so it provides an <span style="font-family: courier new">Invoke</span> method. Next it calls <span style="font-family: courier new">Eval</span> (the interpreter function we have yet to define) on the <strong>head </strong>of the argument list, casting the result to a <span style="font-family: courier new">Number</span>. Of course we could be safer here, perhaps using <span style="color: #0000ff; font-family: courier new">dynamic_cast</span> to ensure that it&#8217;s safe to treat the value as a number, but for the purposes of this exercise we&#8217;ll keep it simple (and unsafe).</p>
<p>Next, the <strong>tail</strong> of the argument list is read (and cast to a <span style="font-family: courier new">Pair</span>). Because the argument list is effectively a linked list, this is similar to (say) incrementing a <span style="font-family: courier new">std::list&lt;Value*&gt;::iterator</span>. Having loaded the next node in the argument list, we again evaluate the head of this node, to acquire the second argument.</p>
<p>Finally, we return a new <span style="font-family: courier new">Number</span> value made of the sum of the first two numbers. Ignoring the <span style="font-family: courier new">allocate&lt;T&gt;</span> function for now (which should allocate a garbage collected value of type <span style="font-family: courier new">T</span>), we&#8217;ve now completely come to terms with how a primitive function can be defined for this interpreter.</p>
<p>We now have almost enough detail worked out to implement <span style="font-family: courier new">Eval</span>, the actual interpreter. Before we do that, we should fill out the <span style="font-family: courier new">EnvironmentFrame</span> type, which keeps track of variable-name to <span style="font-family: courier new">Value</span> substitutions:</p>
<p><span style="font-family: courier new"><span style="color: #0000ff">class</span> EnvironmentFrame<br />{<br /><span style="color: #0000ff">public</span>:<br />&nbsp;&nbsp;&nbsp; EnvironmentFrame(EnvironmentFrame* p) : parent(p) { }</span></p>
<p><span style="font-family: courier new">&nbsp;&nbsp;&nbsp; <span style="font-family: courier new"><span style="color: #0000ff">void</span> define(<span style="color: #0000ff">const</span> std::string&amp; var, Value* val)<br />&nbsp;&nbsp;&nbsp; {<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; substitutions[var] = val;<br />&nbsp;&nbsp;&nbsp; }</span></span></p>
<p><span style="font-family: courier new">&nbsp;&nbsp;&nbsp; <span style="font-family: courier new">Value* lookup(<span style="color: #0000ff">const</span> std::string&amp; var)<br />&nbsp;&nbsp;&nbsp; {<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; ValMap::iterator vi = substitutions.find(var);</span></span></p>
<p><span style="font-family: courier new">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <span style="color: #0000ff">if</span> (vi != substitutions.end())<br /><span style="color: #0000ff">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; return</span> vi-&gt;second;<br /><span style="color: #0000ff">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; else if</span> (parent != 0)<br /><span style="color: #0000ff">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; return</span> parent-&gt;lookup(var);<br /><span style="color: #0000ff">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; else</span><br /><span style="color: #0000ff">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; throw</span> std::runtime_error(&#8220;Undefined: &#8221; + var);<br /></span><span style="font-family: courier new"><span style="font-family: courier new">&nbsp;&nbsp;&nbsp; }<br /><span style="color: #0000ff">private</span>:<br /><span style="color: #0000ff">&nbsp;&nbsp;&nbsp; typedef</span> std::map&lt;std::string, Value*&gt;<span style="font-family: courier new"> ValMap;<br />&nbsp;&nbsp;&nbsp; EnvironmentFrame* parent;<br />&nbsp;&nbsp;&nbsp; ValMap substitutions;<br />};</span></span></p>
<p></span></p>
<p>This type effectively just maps variable names to values, with the small distinction that it defers to an outer <span style="font-family: courier new">EnvironmentFrame</span> if the variable isn&#8217;t immediately defined. Later we&#8217;ll look at implementing abstractions, where this ability to define hierarchies of substitutions is critical.&nbsp; With this type defined, we can create the <em>root environment frame</em> to hold our addition function:</p>
<p><span style="font-family: courier new">EnvironmentFrame* root = allocate&lt;EnvironmentFrame&gt;(0);<br />root-&gt;define(&#8220;+&#8221;, allocate&lt;AddFunction&gt;());</span></p>
<p>Now we&#8217;ve come far enough to finally define <span style="font-family: courier new">Eval</span>, the actual interpreter.</p>
<p><strong>The Eval Function</strong></p>
<p><span style="font-family: courier new">Value* Eval(Value* e, EnvironmentFrame* env)<br />{<br /><span style="color: #0000ff">&nbsp;&nbsp;&nbsp; if</span> (Symbol* s = <span style="color: #0000ff">dynamic_cast</span>&lt;Symbol*&gt;(e))<br /><span style="color: #0000ff">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; return</span> env-&gt;lookup(s-&gt;value());<br /><span style="color: #0000ff">&nbsp;&nbsp;&nbsp; else if</span> (<span style="color: #0000ff">dynamic_cast<span style="color: #000000">&lt;Pair*&gt;</span></span>(e) == 0)<br /><span style="color: #0000ff">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; return</span> e;</span></p>
<p><span style="font-family: courier new">&nbsp;&nbsp;&nbsp; Pair* p = (Pair*)e;<br />&nbsp;&nbsp;&nbsp; Function* fn = (Function*)Eval(p-&gt;head(), env);</span></p>
<p><span style="font-family: courier new"><span style="color: #0000ff">&nbsp;&nbsp;&nbsp; return</span> fn-&gt;Invoke(p-&gt;tail(), env);<br />}</span></p>
<div>Maybe it&#8217;s surprising that it takes less code to define the core of the interpreter than it took to define the type <font face="Courier New">EnvironmentFrame</font>, but (modulo safety) this is all we&#8217;ve got to write! Again, let&#8217;s cover the cases here (which roughly correspond to the four cases we considered when we first set out to define ).&nbsp; First, if the expression is a <span style="font-family: courier new">Symbol</span> value, we should interpret it as a variable, so we&#8217;ll return whatever is defined for that variable in the current <span style="font-family: courier new">EnvironmentFrame</span>. Then, if the expression <em>is not</em> a compound value, we&#8217;ll return it immediately (currently this would just catch the <span style="font-family: courier new">Number</span> type and the special <strong>nil</strong> value, but would catch any other special types we may create).</div>
<p>If the expression is a compound value, it&#8217;s interpreted as a <em>function application</em>. As we saw previously, the <strong>head</strong> of this compound expression must evaluate to a <span style="font-family: courier new">Function</span> value. Having produced a <span style="font-family: courier new">Function</span> value then, all that&#8217;s left is to call its <span style="font-family: courier new">Invoke</span> implementation with the <strong>tail</strong> of the compound expression (the function&#8217;s argument list).</p>
<p>In a sense, that&#8217;s all there is to writing an interpreter. Although this explanation may appear lengthy, there&#8217;s very little code involved. All that&#8217;s left for us to do now is to &#8220;fill out&#8221; the interpreter with useful functions (since presently the only function we can apply is addition).</p>
<p><strong>Additional Functions</strong></p>
<p>In most &#8220;real world&#8221; programs, we&#8217;ll need some form of conditional statement. Currently our interpreter doesn&#8217;t support this, but it&#8217;s easy enough to add as a <span style="font-family: courier new">Function</span> value.</p>
<p><span style="font-family: courier new"><span style="color: #0000ff">class</span> IfFunction : <span style="color: #0000ff">public</span> Function<br />{<br /><span style="color: #0000ff">public</span>:<br />&nbsp;&nbsp;&nbsp; Value* Invoke(Pair* args, EnvironmentFrame* env)<br />&nbsp;&nbsp;&nbsp; {<br /><span style="color: #008000">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; // extract function arguments</span><br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; Value* test_exp = args-&gt;head();<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; args = (Pair*)args-&gt;tail();<br /></span><span style="font-family: courier new">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; Value* cons_exp = args-&gt;head();<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; args = (Pair*)args-&gt;tail();</span></p>
<p><span style="font-family: courier new">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; Value* alt_exp = args-&gt;head();</span></p>
<p><span style="font-family: courier new"><span style="color: #008000">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; // if the condition is true, evaluate the<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; // consequent else evaluate the alternative<br /></span><span style="color: #0000ff">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; if</span> (Eval(test_exp, env) != 0)<br /><span style="color: #0000ff">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; return</span> Eval(cons_exp, env);<br /><span style="color: #0000ff">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; else</span><br /><span style="color: #0000ff">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; return</span> Eval(alt_exp, env);<br />&nbsp;&nbsp;&nbsp; }<br />};</span></p>
<div>First we extract the expressions standing in for the condition of the if statement, the consequence, and the alternative. Then, we evaluate the condition expression and return either the evaluation of the consequence (if the condition does <em>not</em> evaluate to <strong>nil</strong>), or the evaluation of the alternative. It&#8217;s clear now that iterating over and extracting values out of the argument list is tedious (it required even more code above than the central logic of the <span style="font-family: courier new">IfFunction</span>!). To save ourselves from this hassle, we can define a simple utility to extract the nth element of a list:</div>
<div>&nbsp;</div>
<div><span style="font-family: courier new">Value* nth(Pair* p, <span style="color: #0000ff">int</span> n)<br />{<br /><span style="color: #0000ff">&nbsp;&nbsp;&nbsp; int</span> i = 0;<br /><span style="color: #0000ff">&nbsp;&nbsp;&nbsp; while</span> (i++ != n) p = (Pair*)p-&gt;tail();<br /><span style="color: #0000ff">&nbsp;&nbsp;&nbsp; return</span> p-&gt;head();<br />}</span></div>
<p>Now we can use this utility to create a function that allows programmers to define new variables:</p>
<p><span style="font-family: courier new"><span style="color: #0000ff">class</span> DefineFunction : <span style="color: #0000ff">public</span> Function<br />{<br /><span style="color: #0000ff">public</span>:<br />&nbsp;&nbsp;&nbsp; Value* Invoke(Pair* args, EnvironmentFrame* env)<br />&nbsp;&nbsp;&nbsp; {<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; Symbol* var = (Symbol*)nth(args, 0);<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; Value*&nbsp;&nbsp;&nbsp; v = Eval(nth(args, 1), env);</span></p>
<p><span style="font-family: courier new">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <span style="font-family: courier new">env-&gt;define(var-&gt;value(), v);<br /></span><span style="font-family: courier new"><span style="color: #0000ff"><span style="color: #000000">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; </span>return</span> 0;<br />&nbsp;&nbsp;&nbsp; }<br />};</span></span></p>
<p>Here it&#8217;s important that we <strong>not</strong> evaluate the first argument, since it should be the name of the variable we want to define (and since it isn&#8217;t already defined, if we evaluated it we&#8217;d get an error!). The second value (the value to be associated with the variable) should be evaluated though, and so it is. Finally, we update the environment with this new variable and (arbitrarily) return.&nbsp; Just to fill out our interpreter a little more, we can also add more arithmetic-related functions: one to multiply two numbers and another to check two numbers for equality:</p>
<p><span style="font-family: courier new"><span style="color: #0000ff">class</span> MultiplyFunction : <span style="color: #0000ff">public</span> Function<br />{<br /><span style="color: #0000ff">public</span>:<br />&nbsp;&nbsp;&nbsp; Value* Invoke(Pair* args, EnvironmentFrame* env)<br />&nbsp;&nbsp;&nbsp; {<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; Number* n1 = (Number*)Eval(nth(args, 0), env);<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; Number* n2 = (Number*)Eval(nth(args, 1), env);</span></p>
<div><span style="font-family: courier new">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <span style="font-family: courier new"><span style="color: #0000ff">return</span> allocate&lt;Number&gt;(n1-&gt;value() * n2-&gt;value());<br />&nbsp;&nbsp;&nbsp; }<br />};</span></span></div>
<p><span style="font-family: courier new"><span style="color: #0000ff">class</span> EqFunction : <span style="color: #0000ff">public</span> Function<br />{<br /><span style="color: #0000ff">public</span>:<br />&nbsp;&nbsp;&nbsp; Value* Invoke(Pair* args, EnvironmentFrame* env)<br />&nbsp;&nbsp;&nbsp; {<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; Number* n1 = (Number*)Eval(nth(args, 0), env);<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; Number* n2 = (Number*)Eval(nth(args, 1), env);</span></p>
<div><span style="font-family: courier new">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <span style="font-family: courier new"><span style="color: #0000ff">if</span> (n1-&gt;value() == n2-&gt;value())<br /><span style="color: #0000ff"><span style="color: #000000">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; </span>return</span> allocate&lt;Number&gt;(1);<br /><span style="color: #0000ff"><span style="color: #000000">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; </span>else</span><br /><span style="color: #0000ff"><span style="color: #000000">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; </span>return</span> 0;<br />&nbsp;&nbsp;&nbsp; }<br />};</span></span></div>
<p>Here, the result of <font face="Courier New">EqFunction</font> is meant to match the condition value of <font face="Courier New">IfFunction</font> &#8212; so the value returned to represent &#8220;true&#8221; is arbitrary, but the value for &#8220;false&#8221; must be <strong>nil</strong>. Now that we&#8217;ve collected some important functions, we should add them all to our root environment:</p>
<p><span style="font-family: courier new">root-&gt;define(&#8220;if&#8221;,&nbsp;&nbsp;&nbsp;&nbsp; allocate&lt;IfFunction&gt;());<br />root-&gt;define(&#8220;define&#8221;, allocate&lt;DefineFunction&gt;());<br />root-&gt;define(&#8220;*&#8221;,&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; allocate&lt;MultiplyFunction&gt;());<br />root-&gt;define(&#8220;=&#8221;,&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; allocate&lt;EqFunction&gt;());</span></p>
<p>We&#8217;ve now assembled a pretty respectable interpreter and runtime environment, but we&#8217;ve still got one critical feature to define.</p>
<p><strong>Abstractions</strong></p>
<p>To complete the goal we set out for ourselves initially, we&#8217;ve still got to implement abstractions. Our implementation should support the intuition we&#8217;ve developed that the <em>application</em> of an abstraction just substitutes the arguments for the parameters in the body of the abstraction. Luckily, in the <span style="font-family: courier new">EnvironmentFrame</span> type we have already implemented a method of mapping variable names to values. Also, because we have implemented this substitution method by recording variable/value mappings in an <span style="font-family: courier new">EnvironmentFrame</span>, we&#8217;ll need to <em>capture</em> the active <span style="font-family: courier new">EnvironmentFrame</span> in the implementation for an abstraction.</p>
<p>To motivate this notion of capturing an <span style="font-family: courier new">EnvironmentFrame</span> in an abstraction, consider the case of <span style="font-family: courier new"><strong>λ</strong>x.<strong>λ</strong>y.x+y</span>. Here we have an abstraction that returns an abstraction! The inner abstraction refers to a variable <em>bound</em> by the outer abstraction, and the clearest way to make that work in our interpreter is to give the outer abstraction&#8217;s <span style="font-family: courier new">EnvironmentFrame</span> to the inner abstraction.</p>
<p>Now we should be able to define the <span style="font-family: courier new">Abstraction</span> type:</p>
<div><span style="font-family: courier new"><span style="color: #0000ff">class</span> Abstraction : <span style="color: #0000ff">public</span> Function<br />{<br /><font color="#0000ff">public</font>:<br />&nbsp;&nbsp;&nbsp; Abstraction(Pair* pa, Pair* pb, EnvironmentFrame* pe) :<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; arg_names(pa), body(pb), edef(pe) { }</span></div>
<p><span style="font-family: courier new"></p>
<div><span style="font-family: courier new">&nbsp;&nbsp;&nbsp; <span style="font-family: courier new">Value* Invoke(Pair* arg_vals, EnvironmentFrame* env)<br />&nbsp;&nbsp;&nbsp; {</span></span><span style="font-family: courier new"><span style="font-family: courier new"><br /><span style="color: #008000"><span style="color: #000000">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; </span>// prepare a fresh environment for this call</span><br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; EnvironmentFrame* cenv = allocate(edef);</span></span></div>
<p><font face="Courier New"></font></span></p>
<div><span style="font-family: courier new"><span style="font-family: courier new"><span style="font-family: courier new">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <span style="font-family: courier new"><span style="color: #008000">// evaluate each input value and map it to the<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; // appropriate parameter name<br /></span>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; Pair* argn_iter = arg_names;<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; Pair* argv_iter = arg_vals;</span></span><font face="Courier New"><font face="Courier New">
<p></font></font></span><font face="Courier New"></p>
<p></font></span></p>
</div>
<div><span style="font-family: courier new"><span style="font-family: courier new"><span style="font-family: courier new">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <span style="color: #0000ff">while</span> (argn_iter != 0)<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; {<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; Symbol* var = (Symbol*)argn_iter-&gt;head();<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; Value* val = Eval(argv_iter-&gt;head(), env); </span>
<div><span style="font-family: courier new">
<div><span style="font-family: courier new">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; cenv-&gt;define(var-&gt;value(), val);</span></div>
<p></span></p>
</div>
<div><span style="font-family: courier new"><span style="font-family: courier new">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; argn_iter = (Pair*)argn_iter-&gt;tail();<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; argv_iter = (Pair*)argv_iter-&gt;tail();<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; }</span></span></div>
<p><span style="font-family: courier new"><span style="font-family: courier new">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <span style="color: #008000">// now evaluate the list of expressions in the body<br /><span style="color: #000000">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; </span>// of the abstraction in the EnvironmentFrame<br /><span style="color: #000000">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; </span>// for this call<br /></span>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; Value* r = 0;<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; Pair* body_iter = body;</span></span></p>
<div><span style="font-family: courier new"><span style="font-family: courier new">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <span style="color: #0000ff">while</span> (body_iter != 0)<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; r = Eval(body_iter-&gt;head(), cenv);</span></span></div>
<p></span></span></p>
</div>
<p><span style="font-family: courier new"><span style="font-family: courier new">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <span style="color: #0000ff">return</span> r;<br />&nbsp;&nbsp;&nbsp; }<br /><span style="color: #0000ff">private</span>:<br />&nbsp;&nbsp;&nbsp; Pair* arg_names;<br />&nbsp;&nbsp;&nbsp; Pair* body;<br />&nbsp;&nbsp;&nbsp; EnvironmentFrame* edef;<br />};</p>
<p></span></span></p>
<p>This is probably the most complicated piece of code we&#8217;ve written in this interpreter! Still, if we go through it line-by-line we shouldn&#8217;t find anything particularly surprising. First, an <span style="font-family: courier new">Abstraction</span> must be constructed with an argument list (a list of <span style="font-family: courier new">Symbol</span>s representing parameter names), a body (a list of expressions to be evaluated when the abstraction is applied), and an <span style="font-family: courier new">EnvironmentFrame</span> (the active substitutions when the <span style="font-family: courier new">Abstraction</span> is created).</p>
<p>Next, a new <span style="font-family: courier new">EnvironmentFrame</span> is created to hold the variable/value mappings for the parameters of the <span style="font-family: courier new">Abstraction</span>. It is then filled by iterating over both the list of parameter names and the list of arguments (expressions applied to the <span style="font-family: courier new">Abstraction</span>). Each argument is evaluated and associated with its parameter name.</p>
<p>Finally, once the <span style="font-family: courier new">EnvironmentFrame</span> for the call has been filled, it is used to evaluate each expression in the body (with the result of evaluating the last expression in the body used as the return value for <span style="font-family: courier new">Invoke</span>).</p>
<p>To come to grips with this important aspect of our interpreter, let&#8217;s consider the case of <span style="font-family: courier new">((<strong>λ</strong>x.x+2) 1)</span>, which we considered early on. First, we&#8217;ll create <span style="font-family: courier new">Abstraction((x), ((+ x 2)), root)</span>. Here, <span style="font-family: courier new">(x)</span> is just the parameter list, <span style="font-family: courier new">((+ x 2))</span> the (one-element) list of expressions in the body, and root is the <span style="font-family: courier new">EnvironmentFrame</span> in use when the <span style="font-family: courier new">Abstraction</span> is first created (this should contain the definition of <span style="font-family: courier new">+</span> which we use in the body). Then we apply the abstraction to the argument list (1). This produces an <span style="font-family: courier new">EnvironmentFrame</span> for the call that looks like <span style="font-family: courier new">{ x -&gt; 1 { + -&gt; <em>PlusFunction </em>} }</span> (the nested mapping is meant to represent the contents of the <em>parent</em> <span style="font-family: courier new">EnvironmentFrame</span>). Finally, the body is evaluated in this <span style="font-family: courier new">EnvironmentFrame</span>, yielding a sequence of evaluations that looks as follows:</p>
<p><span style="font-family: courier new">Eval((+ x 2), { x -&gt; 1 { + -&gt; <em>PlusFunction</em> } })<br />PlusFunction-&gt;Invoke((x 2), { x -&gt; 1 { + -&gt; PlusFunction } })<br />3</span></p>
<p>All that&#8217;s left is to provide a way for the programmer to construct these <span style="font-family: courier new">Abstraction</span> values at runtime:</p>
<div><span style="font-family: courier new"><span style="color: #0000ff">class</span> MakeAbstractionFn : <span style="color: #0000ff">public</span> Function<br />{<br /><span style="color: #0000ff">public</span>:<br />&nbsp;&nbsp;&nbsp; Value* Invoke(Pair* args, EnvironmentFrame* env)<br />&nbsp;&nbsp;&nbsp; {<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; Pair* pa = (Pair*)args-&gt;head();<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; Pair* pb = (Pair*)args-&gt;tail();</span></div>
<p><span style="font-family: courier new"></p>
<div><span style="font-family: courier new"><span style="color: #0000ff"><span style="color: #000000">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; </span>return</span> allocate&lt;Abstraction&gt;(pa, pb, env);<br />&nbsp;&nbsp;&nbsp; }<br />};</span></div>
<p></span></p>
<p>And we&#8217;ll need to put this function into the root <span style="font-family: courier new">EnvironmentFrame</span>, so that it&#8217;s available to use. Traditionally, this function is written &#8220;lambda&#8221; (the less-convenient way of saying &#8220;<strong>λ</strong>&#8220;) so we&#8217;ll (arbitrarily) stick with that:</p>
<p><span style="font-family: courier new">root-&gt;define(&#8220;lambda&#8221;, allocate&lt;MakeAbstractionFn&gt;());</span></p>
<p><strong>Bringing it all together</strong></p>
<p>We now have a minimalist interpreter for a <a href="http://en.wikipedia.org/wiki/Scheme_%28programming_language%29">Scheme</a>-like programming language. There are still additions we may want to make, and plenty of supporting tools, but at this point we can already write very sophisticated programs. For example, we can construct a program to compute factorials:</p>
<p><span style="font-family: courier new">Pair* program =<br />allocate&lt;Pair&gt;<br />(<br />&nbsp; allocate&lt;Symbol&gt;(&#8220;define&#8221;),<br />&nbsp; allocate&lt;Pair&gt;<br />&nbsp; (<br />&nbsp;&nbsp; allocate&lt;Symbol&gt;(&#8220;factorial&#8221;),<br />&nbsp;&nbsp; allocate&lt;Pair&gt;<br />&nbsp;&nbsp; (<br />&nbsp;&nbsp;&nbsp; allocate&lt;Pair&gt;<br />&nbsp;&nbsp;&nbsp; (<br />&nbsp;&nbsp;&nbsp;&nbsp; allocate&lt;Symbol&gt;(&#8220;lambda&#8221;),<br />&nbsp;&nbsp;&nbsp;&nbsp; allocate&lt;Pair&gt;<br />&nbsp;&nbsp;&nbsp;&nbsp; (<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; allocate&lt;Pair&gt;(allocate&lt;Symbol&gt;(&#8220;x&#8221;), 0),<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; allocate&lt;Pair&gt;<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; (<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; allocate&lt;Symbol&gt;(&#8220;if&#8221;),<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; allocate&lt;Pair&gt;<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; (<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; allocate&lt;Pair&gt;<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; (<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; allocate&lt;Symbol&gt;(&#8220;=&#8221;),<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; allocate&lt;Pair&gt;<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; (<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; allocate&lt;Symbol&gt;(&#8220;x&#8221;),<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; allocate&lt;Pair&gt;<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; (<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; allocate&lt;Number&gt;(0),<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; 0<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; )<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; )<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; ),<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; allocate&lt;Pair&gt;<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; (<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; allocate&lt;Number&gt;(1),<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; allocate&lt;Pair&gt;<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; (<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; allocate&lt;Pair&gt;<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; (<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; allocate&lt;Symbol&gt;(&#8220;*&#8221;),<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; allocate&lt;Pair&gt;<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; (<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; allocate&lt;Symbol&gt;(&#8220;x&#8221;),<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; allocate&lt;Pair&gt;<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; (<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; allocate&lt;Pair&gt;<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; (<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; allocate&lt;Symbol&gt;(&#8220;factorial&#8221;),<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; allocate&lt;Pair&gt;<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; (<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; allocate&lt;Pair&gt;<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; (<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; allocate&lt;Symbol&gt;(&#8220;+&#8221;),<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; allocate&lt;Pair&gt;<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; (<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; allocate&lt;Number&gt;(-1),<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; allocate&lt;Pair&gt;<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; (<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; allocate&lt;Symbol&gt;(&#8220;x&#8221;),<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; 0<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; )<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; )<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; ),<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; 0<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; )<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; ),<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; 0<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; )<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; )<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; ),<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; 0<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; )<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; )<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; )<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; )<br />&nbsp;&nbsp;&nbsp;&nbsp; )<br />&nbsp;&nbsp;&nbsp; ),<br />&nbsp;&nbsp;&nbsp; 0<br />&nbsp;&nbsp; )<br />&nbsp; )<br />);</span></p>
<p>Yikes! That&#8217;s horrible! That will correctly construct a program to define the factorial function (which our interpreter will correctly evaluate), but nobody would want to write programs if they had to be written like that!</p>
<p>Using the <em>S-Expression</em> form, this program can be represented much more concisely:</p>
<p><span style="font-family: courier new">(define factorial<br /> (lambda (x)<br />&nbsp; (if (= x 0)<br />&nbsp;&nbsp; 1<br />&nbsp;&nbsp; (* x (factorial (+ x -1)))<br />&nbsp; )<br /> )<br />)</span></p>
<p>That&#8217;s certainly much closer to what we humans would prefer to write! The job of translating the convenient shorthand of <em>S-Expressions</em> into the explicit in-memory construction required by our interpreter is the responsibility of a <em>parser</em>. We&#8217;ll look at how to write an <em>S-Expression parser</em> in the next installment.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.lab49.com/archives/2013/feed</wfw:commentRss>
		<slash:comments>6</slash:comments>
		</item>
		<item>
		<title>Microsoft MVP 2008</title>
		<link>http://feeds.feedburner.com/~r/KennyKerr/~3/262250401/microsoft-mvp-2008.aspx</link>
		<comments>http://feeds.feedburner.com/~r/KennyKerr/~3/262250401/microsoft-mvp-2008.aspx#comments</comments>
		<pubDate>Tue, 30 Nov 1999 00:00:00 +0000</pubDate>
		<dc:creator>Kenny Kerr</dc:creator>
				<category><![CDATA[C++]]></category>
		<category><![CDATA[Featured Posts]]></category>

		<guid isPermaLink="false"></guid>
		<description><![CDATA[I just heard that I have received the Microsoft MVP award again this year for my contributions to the Visual C++ community. Thanks to my friends at Microsoft. It’s been a pleasure getting to know all of you. Unfortunately the MVP Summit is no longer just “down the road” for me. Maybe next year. My [...]]]></description>
			<content:encoded><![CDATA[<p>I just heard that I have received the Microsoft MVP award again this year for my contributions to the Visual C++ community. Thanks to my friends at Microsoft. It’s been a pleasure getting to know all of you. Unfortunately the MVP Summit is no longer just “down the road” for me. Maybe next year. My colleague, Matt Davey , just got his first award this year. Congrats pal.</p>
]]></content:encoded>
			<wfw:commentRss>http://feeds.feedburner.com/~r/KennyKerr/~3/262250401/microsoft-mvp-2008.aspx/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Delta, Lambda, Pi (the fraternity of calculi)</title>
		<link>http://blog.lab49.com/archives/1187</link>
		<comments>http://blog.lab49.com/archives/1187#comments</comments>
		<pubDate>Thu, 28 Jun 2007 21:01:54 +0000</pubDate>
		<dc:creator>Kalani Thielen</dc:creator>
				<category><![CDATA[Featured Posts]]></category>
		<category><![CDATA[Languages]]></category>
		<category><![CDATA[Lisp]]></category>

		<guid isPermaLink="false">http://blog.lab49.com/?p=1187</guid>
		<description><![CDATA[We recently had an internal presentation covering a variety of fundamental theories of computation that underly several important programming languages. Here are a few papers that might help explain those theories in more depth (if not the actual interpreters we developed): Foundational Calculi for Programming Languages Introduction to Lambda Calculus Making [Erlang] (Joe Armstrong&#8217;s PhD [...]]]></description>
			<content:encoded><![CDATA[<p>We recently had an internal presentation covering a variety of fundamental theories of computation that underly several important programming languages.  Here are a few papers that might help explain those theories in more depth (if not the actual interpreters we developed):</p>
<ul>
<li><a href="http://citeseer.ist.psu.edu/pierce95foundational.html">Foundational Calculi for Programming Languages</a></li>
<li><a href="http://citeseer.ist.psu.edu/barendregt94introduction.html">Introduction to Lambda Calculus</a></li>
<li><a title="Making [Erlang] (Joe Armstrong's PhD thesis)" href="http://www.sics.se/~joe/thesis/armstrong_thesis_2003.pdf">Making [Erlang] (Joe Armstrong&#8217;s PhD thesis)</a></li>
</ul>
<p><span id="more-1187"></span></p>
<p>The &#8220;foundational calculi&#8221; paper introduces both the lambda and pi calculus.  It explains Church numerals, booleans, and data structures purely in terms of lambda expressions.  It&#8217;s written by Benjamin Pierce, whose book <a title="Types and Programming Languages" href="http://www.cis.upenn.edu/~bcpierce/tapl/">Types and Programming Languages</a> is one of the holy books of programming language theory.</p>
<p>Joe Armstrong&#8217;s thesis is especially interesting for this little insight into the politics of software development at large companies:</p>
<blockquote><p>In February 1998 Erlang was banned for new product development within Ericsson—the main reason for the ban was that Ericsson wanted to be a consumer of software technologies rather than a producer.</p></blockquote>
<p>They reversed this position a short time later, much to the relief of their bottom line.  This case especially highlights the central role that niche programming languages (formalized industry jargon) play in realizing the dreams of businesses.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.lab49.com/archives/1187/feed</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
	</channel>
</rss>

