<?xml version="1.0" encoding="UTF-8" ?>
<?xml-stylesheet type="text/xsl" href="http://blogs.msdn.com/utility/FeedStylesheets/rss.xsl" media="screen"?><rss version="2.0" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:slash="http://purl.org/rss/1.0/modules/slash/" xmlns:wfw="http://wellformedweb.org/CommentAPI/"><channel><title>Yet Another Language Geek : C#</title><link>http://blogs.msdn.com/wesdyer/archive/tags/C_2300_/default.aspx</link><description>Tags: C#</description><dc:language>en-US</dc:language><generator>CommunityServer 2.1 SP1 (Build: 61025.2)</generator><item><title>Continuation-Passing Style</title><link>http://blogs.msdn.com/wesdyer/archive/2007/12/22/continuation-passing-style.aspx</link><pubDate>Sat, 22 Dec 2007 09:51:58 GMT</pubDate><guid isPermaLink="false">91d46819-8472-40ad-a661-2c78acb4018c:6833509</guid><dc:creator>wesdyer</dc:creator><slash:comments>9</slash:comments><comments>http://blogs.msdn.com/wesdyer/comments/6833509.aspx</comments><wfw:commentRss>http://blogs.msdn.com/wesdyer/commentrss.aspx?PostID=6833509</wfw:commentRss><description>&lt;p&gt;There are some technical words that cause quite a stir even amongst geeks.&amp;#160; When someone says the word &lt;a href="http://en.wikipedia.org/wiki/Continuation"&gt;&amp;quot;continuation&amp;quot;&lt;/a&gt;, people's eyes glaze over and they seek the first opportunity to change the subject.&amp;#160; The stir is caused because most people don't understand what a continuation is or why someone would want to use one.&amp;#160; This is unfortunate, because they really are rather more simple than they sound. &lt;/p&gt;  &lt;p&gt;&lt;strong&gt;Defining Continuations&lt;/strong&gt;&lt;/p&gt;  &lt;p&gt;A continuation represents the remainder of a computation given a point in that computation.&amp;#160; For example, suppose that two methods are defined: &lt;em&gt;M&lt;/em&gt; and &lt;em&gt;Main&lt;/em&gt;.&amp;#160; The method &lt;em&gt;Main&lt;/em&gt; invokes &lt;em&gt;M&lt;/em&gt; and then writes &amp;quot;Done&amp;quot; to the console.&amp;#160; The method &lt;em&gt;M&lt;/em&gt; assigns &lt;em&gt;x &lt;/em&gt;the value five, invokes &lt;em&gt;F&lt;/em&gt;, increments &lt;em&gt;x&lt;/em&gt;, and writes &lt;em&gt;x&lt;/em&gt; to the console.&lt;/p&gt;  &lt;blockquote&gt;   &lt;pre class="code"&gt;&lt;span style="color: blue"&gt;static void &lt;/span&gt;M()
{
    &lt;span style="color: blue"&gt;var &lt;/span&gt;x = 5;
    F();  &lt;span style="color: green"&gt;// &amp;lt;----------- Point in the computation
    &lt;/span&gt;++x;
    &lt;span style="color: #2b91af"&gt;Console&lt;/span&gt;.WriteLine(x);
}

&lt;span style="color: blue"&gt;static void &lt;/span&gt;Main()
{
    M();
    &lt;span style="color: #2b91af"&gt;Console&lt;/span&gt;.WriteLine(&lt;span style="color: #a31515"&gt;&amp;quot;Done&amp;quot;&lt;/span&gt;);
}&lt;/pre&gt;
&lt;/blockquote&gt;
&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;

&lt;p&gt;The continuation of the computation at the invocation of &lt;em&gt;F &lt;/em&gt;is the remainder of the program execution beginning with incrementing &lt;em&gt;x&lt;/em&gt; in the method &lt;em&gt;M&lt;/em&gt;.&amp;#160; In this case, the continuation includes incrementing &lt;em&gt;x&lt;/em&gt;, writing &lt;em&gt;x&lt;/em&gt;, returning to &lt;em&gt;Main&lt;/em&gt;, and writing &amp;quot;Done&amp;quot; to the console.&lt;/p&gt;

&lt;p&gt;Some languages give programmers explicit access to continuations.&amp;#160; For example, Scheme has a function which calls a function passing a function representing the current continuation.&amp;#160; The function is aptly named &lt;a href="http://community.schemewiki.org/?call-with-current-continuation"&gt;call with current continuation&lt;/a&gt; or &lt;em&gt;call/cc&lt;/em&gt;.&amp;#160; If such a function existed in .NET it might return a T given a delegate that returns a T given a delegate from T to T.&lt;/p&gt;

&lt;blockquote&gt;
  &lt;pre class="code"&gt;T CallCC&amp;lt;T&amp;gt;(&lt;span style="color: #2b91af"&gt;Func&lt;/span&gt;&amp;lt;&lt;font color="#2b91af"&gt;Func&lt;/font&gt;&amp;lt;T,T&amp;gt;, T&amp;gt; f)&lt;/pre&gt;
&lt;/blockquote&gt;

&lt;p&gt;Continuations are the functional counterparts of GOTOs both in power and inscrutability.&amp;#160; They can express arbitrary control flow like coroutines and exceptions while bewildering some of the brightest programmers.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Returning Values with Continuations&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;The simplest use of a continuation is to simulate returning out of a function.&amp;#160; Suppose that .NET had the function &lt;em&gt;CallCC&lt;/em&gt;.&amp;#160; If &lt;em&gt;Main&lt;/em&gt; calls a function &lt;em&gt;Foo&lt;/em&gt; passing the value four and if &lt;em&gt;Foo&lt;/em&gt; immediately invokes &lt;em&gt;CallCC&lt;/em&gt; with a lambda that binds &lt;em&gt;Return&lt;/em&gt; to the continuation at the point of the call to &lt;em&gt;CallCC, &lt;/em&gt;then when &lt;em&gt;Return&lt;/em&gt; is invoked inside of the lambda with the value four, computation will immediately jump out of the lambda to the point after &lt;em&gt;CallCC&lt;/em&gt; but before the return with the value four on the stack.&amp;#160; This happens regardless what of occurs after the invocation of &lt;em&gt;Return&lt;/em&gt; inside the lambda.&lt;/p&gt;

&lt;blockquote&gt;
  &lt;pre class="code"&gt;&lt;span style="color: blue"&gt;static int &lt;/span&gt;Foo(&lt;span style="color: blue"&gt;int &lt;/span&gt;n)
{
    &lt;span style="color: blue"&gt;return &lt;/span&gt;CallCC&amp;lt;&lt;span style="color: blue"&gt;int&lt;/span&gt;&amp;gt;(Return =&amp;gt;
        {
            Return(n);
            &lt;span style="color: blue"&gt;return &lt;/span&gt;n + 1;
        });
}

&lt;span style="color: blue"&gt;static void &lt;/span&gt;Main()
{
    Foo(4);
}&lt;/pre&gt;
  &lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;&lt;/blockquote&gt;

&lt;p&gt;The result of running the program is therefore four and not five.&lt;/p&gt;

&lt;p&gt;All of this demonstrates that returning from a function is equivalent to invoking the continuation defined at the function's call-site.&amp;#160; When a function &amp;quot;returns&amp;quot;, it implicitly invokes the continuation of its call-site.&lt;/p&gt;

&lt;p&gt;When people explain continuations, they usually discuss stack frames and instruction pointers.&amp;#160; It is easy to see why.&amp;#160; The implicit invocation of the &amp;quot;return&amp;quot; continuation restores the stack frame at the call-site and sets the instruction pointer to the instruction immediately after the call-site.&amp;#160; This is what invoking a continuation does: restore the appropriate stack frame and set the instruction pointer.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Continuation-Passing Style&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;It is still possible to use continuations if a language does not support a function like &lt;em&gt;call/cc&lt;/em&gt;.&amp;#160; A programmer can explicitly construct the continuation of a computation and pass it directly to a function.&lt;/p&gt;

&lt;p&gt;To illustrate this transformation, suppose that a function, &lt;em&gt;Identity,&lt;/em&gt; is defined that returns the value it is given. &lt;/p&gt;

&lt;blockquote&gt;
  &lt;pre class="code"&gt;&lt;span style="color: blue"&gt;static &lt;/span&gt;T Identity&amp;lt;T&amp;gt;(T value)
{
    &lt;span style="color: blue"&gt;return &lt;/span&gt;value;
}&lt;/pre&gt;
&lt;/blockquote&gt;

&lt;p&gt;The return statement in &lt;em&gt;Identity&lt;/em&gt; implicitly invokes the continuation of the call-site causing computation to leave &lt;em&gt;Identity&lt;/em&gt; and resume at the point immediately after the invocation of &lt;em&gt;Identity&lt;/em&gt; at the call-site.&amp;#160; If &lt;em&gt;Main&lt;/em&gt; contains only a call to &lt;em&gt;WriteLine&lt;/em&gt; passing the result of the call to &lt;em&gt;Identity,&lt;/em&gt; then computation resumes with the call to &lt;em&gt;WriteLine&lt;/em&gt;.&lt;/p&gt;

&lt;blockquote&gt;
  &lt;pre class="code"&gt;&lt;span style="color: blue"&gt;static void &lt;/span&gt;Main()
{
    &lt;span style="color: #2b91af"&gt;Console&lt;/span&gt;.WriteLine(Identity(&lt;span style="color: #a31515"&gt;&amp;quot;foo&amp;quot;&lt;/span&gt;));
}&lt;/pre&gt;
&lt;/blockquote&gt;
&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;

&lt;p&gt;However, instead of implicitly invoking &lt;em&gt;Identity's&lt;/em&gt; continuation, the programmer can pass the continuation to &lt;em&gt;Identity &lt;/em&gt;explicitly.&amp;#160; An extra argument is added to &lt;em&gt;Identity&lt;/em&gt; which is a void-returning delegate with one parameter that is the same type as the return type of the former &lt;em&gt;Identity&lt;/em&gt; function.&lt;/p&gt;

&lt;blockquote&gt;
  &lt;pre class="code"&gt;&lt;span style="color: blue"&gt;static void &lt;/span&gt;Main()
{
    Identity(&lt;span style="color: #a31515"&gt;&amp;quot;foo&amp;quot;&lt;/span&gt;, s =&amp;gt; &lt;span style="color: #2b91af"&gt;Console&lt;/span&gt;.WriteLine(s));
}

&lt;span style="color: blue"&gt;static void &lt;/span&gt;Identity&amp;lt;T&amp;gt;(T value, &lt;span style="color: #2b91af"&gt;Action&lt;/span&gt;&amp;lt;T&amp;gt; k)
{
    k(value);
}&lt;/pre&gt;
&lt;/blockquote&gt;
&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;

&lt;p&gt;At the call-site, the remainder of the computation has moved into the lambda passed to &lt;em&gt;Identity&lt;/em&gt;.&amp;#160; The continuation is explicitly passed.&amp;#160; On the callee's side, the return statement is replaced by the invocation of the continuation parameter, &lt;em&gt;k&lt;/em&gt;, with the return value.&lt;/p&gt;

&lt;p&gt;This pattern is called &lt;a href="http://en.wikipedia.org/wiki/Continuation-passing_style"&gt;continuation-passing style&lt;/a&gt; or CPS.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Converting to CPS&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Now that we know enough to be dangerous, let's see what we can do.&amp;#160; Consider the typical &lt;em&gt;Max&lt;/em&gt; function.&lt;/p&gt;

&lt;blockquote&gt;
  &lt;pre class="code"&gt;&lt;span style="color: blue"&gt;static int &lt;/span&gt;Max(&lt;span style="color: blue"&gt;int &lt;/span&gt;n, &lt;span style="color: blue"&gt;int &lt;/span&gt;m)
{
    &lt;span style="color: blue"&gt;if &lt;/span&gt;(n &amp;gt; m)
        &lt;span style="color: blue"&gt;return &lt;/span&gt;n;
    &lt;span style="color: blue"&gt;else
        return &lt;/span&gt;m;
}&lt;/pre&gt;
&lt;/blockquote&gt;

&lt;p&gt;To convert this function to CPS, follow these steps:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;1.&amp;#160; Change the return type to void&lt;/p&gt;

  &lt;p&gt;2.&amp;#160; Add an extra argument of type &lt;em&gt;Action&amp;lt;T&amp;gt;&lt;/em&gt; where &lt;em&gt;T&lt;/em&gt; is the original return type&lt;/p&gt;

  &lt;p&gt;3.&amp;#160; Replace all return statements with invocations of the new continuation argument passing the expression used in the return statement&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;Applying these steps to the integer version of &lt;em&gt;Max&lt;/em&gt;, the function now returns void, takes an extra parameter, &lt;em&gt;k&lt;/em&gt;, of type &lt;em&gt;Action&amp;lt;int&amp;gt;&lt;/em&gt;, and invokes &lt;em&gt;k&lt;/em&gt; everywhere a return statement appeared.&lt;/p&gt;

&lt;blockquote&gt;
  &lt;pre class="code"&gt;&lt;span style="color: blue"&gt;static void &lt;/span&gt;Max(&lt;span style="color: blue"&gt;int &lt;/span&gt;n, &lt;span style="color: blue"&gt;int &lt;/span&gt;m, &lt;span style="color: #2b91af"&gt;Action&lt;/span&gt;&amp;lt;&lt;span style="color: blue"&gt;int&lt;/span&gt;&amp;gt; k)
{
    &lt;span style="color: blue"&gt;if &lt;/span&gt;(n &amp;gt; m)
        k(n);
    &lt;span style="color: blue"&gt;else
        &lt;/span&gt;k(m);
}&lt;/pre&gt;
&lt;/blockquote&gt;
&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;

&lt;p&gt;To convert the call-site to CPS:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;1.&amp;#160; Remove all of the remaining computation after the call-site&lt;/p&gt;

  &lt;p&gt;2.&amp;#160; Put the remaining computation in the body of the lambda corresponding to the continuation argument&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;For example, suppose the user defined a method &lt;em&gt;Main&lt;/em&gt; which invokes &lt;em&gt;WriteLine&lt;/em&gt; with the result of applying &lt;em&gt;Max&lt;/em&gt; to three and four.&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;&lt;font face="Courier New"&gt;&lt;span style="color: blue"&gt;&lt;font face="Verdana"&gt;&lt;/font&gt;static void &lt;/span&gt;Main()

      &lt;br /&gt;{

      &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;span style="color: #2b91af"&gt;Console&lt;/span&gt;.WriteLine(Max(3, 4));

      &lt;br /&gt;}&lt;/font&gt;&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;The remaining computation after the invocation of &lt;em&gt;Max &lt;/em&gt;is the call to &lt;em&gt;WriteLine&lt;/em&gt;.&amp;#160; Therefore, the call to &lt;em&gt;WriteLine &lt;/em&gt;is moved into the lambda representing the continuation passed to &lt;em&gt;Max&lt;/em&gt;.&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;&lt;font face="Courier New"&gt;&lt;span style="color: blue"&gt;static void &lt;/span&gt;Main()

      &lt;br /&gt;{

      &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; Max(3, 4, x =&amp;gt; &lt;span style="color: #2b91af"&gt;Console&lt;/span&gt;.WriteLine(x));

      &lt;br /&gt;}&lt;/font&gt;&lt;/p&gt;
&lt;/blockquote&gt;
&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;

&lt;p&gt;The steps for converting the call-site skirted the issue of what to do with return statements in the continuation.&amp;#160; For example, suppose there are three methods &lt;em&gt;Main&lt;/em&gt;, &lt;em&gt;F&lt;/em&gt;, and &lt;em&gt;G&lt;/em&gt; where &lt;em&gt;Main &lt;/em&gt;calls &lt;em&gt;F&lt;/em&gt; and &lt;em&gt;F&lt;/em&gt; calls &lt;em&gt;G.&amp;#160; &lt;/em&gt;To convert &lt;em&gt;F&lt;/em&gt; and &lt;em&gt;G &lt;/em&gt;to CPS, follow the same transformation steps as with &lt;em&gt;Max&lt;/em&gt;.&lt;/p&gt;

&lt;blockquote&gt;
  &lt;pre class="code"&gt;&lt;span style="color: blue"&gt;static void &lt;/span&gt;Main()
{
    &lt;span style="color: #2b91af"&gt;Console&lt;/span&gt;.WriteLine(F(1) + 1);
}

&lt;span style="color: blue"&gt;static int &lt;/span&gt;F(&lt;span style="color: blue"&gt;int &lt;/span&gt;n)
{
    &lt;span style="color: blue"&gt;return &lt;/span&gt;G(n + 1) + 1;
}

&lt;span style="color: blue"&gt;static int &lt;/span&gt;G(&lt;span style="color: blue"&gt;int &lt;/span&gt;n)
{
    &lt;span style="color: blue"&gt;return &lt;/span&gt;n + 1;
}&lt;/pre&gt;
&lt;/blockquote&gt;
&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;

&lt;p&gt;However, what should the transformation do with the return statement in &lt;em&gt;F&lt;/em&gt;?&amp;#160; The continuation passed to &lt;em&gt;G&lt;/em&gt; should definitely not attempt to return a result because the continuation is a void-returning delegate.&lt;/p&gt;

&lt;blockquote&gt;
  &lt;pre class="code"&gt;&lt;span style="color: blue"&gt;static void &lt;/span&gt;F(&lt;span style="color: blue"&gt;int &lt;/span&gt;n, &lt;span style="color: #2b91af"&gt;Action&lt;/span&gt;&amp;lt;&lt;span style="color: blue"&gt;int&lt;/span&gt;&amp;gt; k)
{
    G(n + 1, x =&amp;gt; { &lt;span style="color: blue"&gt;return &lt;/span&gt;x + 1; });  &lt;span style="color: green"&gt;// error, Action&amp;lt;int&amp;gt; cannot return a value
&lt;/span&gt;}&lt;/pre&gt;
  &lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;&lt;/blockquote&gt;
&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;

&lt;p&gt;That wouldn't make any sense.&amp;#160; Delegates with void return-types cannot return values.&amp;#160; Furthermore, the code completely ignores &lt;em&gt;k&lt;/em&gt;.&lt;/p&gt;

&lt;p&gt;Instead, the return statement should be transformed into an invocation of &lt;em&gt;k&lt;/em&gt;.&lt;/p&gt;

&lt;blockquote&gt;
  &lt;pre class="code"&gt;&lt;span style="color: blue"&gt;static void &lt;/span&gt;Main()
{
    F(1, x =&amp;gt; &lt;span style="color: #2b91af"&gt;Console&lt;/span&gt;.WriteLine(x + 1));
}

&lt;span style="color: blue"&gt;static void &lt;/span&gt;F(&lt;span style="color: blue"&gt;int &lt;/span&gt;n, &lt;span style="color: #2b91af"&gt;Action&lt;/span&gt;&amp;lt;&lt;span style="color: blue"&gt;int&lt;/span&gt;&amp;gt; k)
{
    G(n + 1, x =&amp;gt; k(x + 1));
}

&lt;span style="color: blue"&gt;static void &lt;/span&gt;G(&lt;span style="color: blue"&gt;int &lt;/span&gt;n, &lt;span style="color: #2b91af"&gt;Action&lt;/span&gt;&amp;lt;&lt;span style="color: blue"&gt;int&lt;/span&gt;&amp;gt; k)
{
    k(n + 1);
}&lt;/pre&gt;
  &lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;&lt;/blockquote&gt;
&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;

&lt;p&gt;This is how functions that use explicit continuations are composed together.&lt;/p&gt;

&lt;p&gt;What about recursive functions like Factorial?&lt;/p&gt;

&lt;blockquote&gt;
  &lt;pre class="code"&gt;&lt;span style="color: blue"&gt;static void &lt;/span&gt;Main()
{
    &lt;span style="color: #2b91af"&gt;Console&lt;/span&gt;.WriteLine(Factorial(5));
}

&lt;span style="color: blue"&gt;static int &lt;/span&gt;Factorial(&lt;span style="color: blue"&gt;int &lt;/span&gt;n)
{
    &lt;span style="color: blue"&gt;if &lt;/span&gt;(n == 0)
        &lt;span style="color: blue"&gt;return &lt;/span&gt;1;
    &lt;span style="color: blue"&gt;else
        return &lt;/span&gt;n * Factorial(n - 1);
}&lt;/pre&gt;
&lt;/blockquote&gt;
&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;

&lt;p&gt;Recursive functions can be transformed just as easily following the same steps.&lt;/p&gt;

&lt;blockquote&gt;
  &lt;pre class="code"&gt;&lt;span style="color: blue"&gt;static void &lt;/span&gt;Main()
{
    Factorial(5, x =&amp;gt; &lt;span style="color: #2b91af"&gt;Console&lt;/span&gt;.WriteLine(x));
}

&lt;span style="color: blue"&gt;static void &lt;/span&gt;Factorial(&lt;span style="color: blue"&gt;int &lt;/span&gt;n, &lt;span style="color: #2b91af"&gt;Action&lt;/span&gt;&amp;lt;&lt;span style="color: blue"&gt;int&lt;/span&gt;&amp;gt; k)
{
    &lt;span style="color: blue"&gt;if &lt;/span&gt;(n == 0)
        k(1);
    &lt;span style="color: blue"&gt;else
        &lt;/span&gt;Factorial(n - 1, x =&amp;gt; k(n * x));
}&lt;/pre&gt;
&lt;/blockquote&gt;
&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;

&lt;p&gt;CPS turns a program inside-out.&amp;#160; In the process, the programmer may feel that his brain has been turned inside-out as well.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Why CPS?&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;What exactly can a programmer do with CPS besides showoff at parties?&lt;/p&gt;

&lt;p&gt;Compilers use a more thorough CPS transformation to produce an intermediate form amenable to many analyses.&amp;#160; UI frameworks use CPS to keep the UI responsive while allowing nonlinear program interaction.&amp;#160; Web servers use CPS to allow computation to flow asynchronously across pages.&lt;/p&gt;

&lt;p&gt;Most programmers have used functions which take a callback.&amp;#160; Often, the callback is the code that is invoked upon completion of the function.&amp;#160; In these cases, the callback is an explicitly-passed continuation.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Asynchronous Calls&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Hiding network latency requires asynchronous calls.&amp;#160; In the first technology preview, Volta allows programmers to add asynchronous versions of methods on tier boundaries.&lt;/p&gt;

&lt;blockquote&gt;
  &lt;pre class="code"&gt;[&lt;span style="color: #2b91af"&gt;RunAtOrigin&lt;/span&gt;]
&lt;span style="color: blue"&gt;static class &lt;/span&gt;&lt;span style="color: #2b91af"&gt;C
&lt;/span&gt;{
    &lt;span style="color: blue"&gt;public static int &lt;/span&gt;F(&lt;span style="color: blue"&gt;string &lt;/span&gt;s)
    {
        &lt;span style="color: blue"&gt;return &lt;/span&gt;s != &lt;span style="color: blue"&gt;null &lt;/span&gt;? s.Length : 0;
    }
}&lt;/pre&gt;
&lt;/blockquote&gt;

&lt;p&gt;To make a method asynchronous, define the CPS-equivalent method signature and annotate it with the &lt;em&gt;Async &lt;/em&gt;attribute.&amp;#160; Volta will generate the body and modify the call-sites accordingly.&lt;/p&gt;

&lt;blockquote&gt;
  &lt;pre class="code"&gt;[&lt;span style="color: #2b91af"&gt;Async&lt;/span&gt;]
&lt;span style="color: blue"&gt;public static void &lt;/span&gt;F(&lt;span style="color: blue"&gt;string &lt;/span&gt;s, &lt;span style="color: #2b91af"&gt;Action&lt;/span&gt;&amp;lt;&lt;span style="color: blue"&gt;int&lt;/span&gt;&amp;gt; k);&lt;/pre&gt;
&lt;/blockquote&gt;
&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;

&lt;p&gt;If the programmer invokes an asynchronous method &lt;em&gt;F, &lt;/em&gt;then Volta will launch the invocation on another thread and invoke the continuation upon completion of the call to &lt;em&gt;F.&lt;/em&gt;&lt;/p&gt;

&lt;blockquote&gt;
  &lt;pre class="code"&gt;&lt;span style="color: #2b91af"&gt;C&lt;/span&gt;.F(&lt;span style="color: #a31515"&gt;&amp;quot;foo&amp;quot;&lt;/span&gt;, x =&amp;gt; &lt;span style="color: #2b91af"&gt;Console&lt;/span&gt;.WriteLine(x));&lt;/pre&gt;
&lt;/blockquote&gt;
&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;

&lt;p&gt;&lt;strong&gt;Wrapping it Up&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Continuations are powerful.&amp;#160; CPS gives programmers a way to use continuations in their day-to-day work.&amp;#160; Perhaps, someday soon we'll discuss how to make CPS more palatable, but we will need to discuss the &amp;quot;M&amp;quot; word first.&lt;/p&gt;&lt;img src="http://blogs.msdn.com/aggbug.aspx?PostID=6833509" width="1" height="1"&gt;</description><category domain="http://blogs.msdn.com/wesdyer/archive/tags/C_2300_/default.aspx">C#</category><category domain="http://blogs.msdn.com/wesdyer/archive/tags/Functional+Programming/default.aspx">Functional Programming</category><category domain="http://blogs.msdn.com/wesdyer/archive/tags/Volta/default.aspx">Volta</category></item><item><title>In Case You Haven't Heard</title><link>http://blogs.msdn.com/wesdyer/archive/2007/05/23/in-case-you-haven-t-heard.aspx</link><pubDate>Wed, 23 May 2007 21:19:06 GMT</pubDate><guid isPermaLink="false">91d46819-8472-40ad-a661-2c78acb4018c:2820432</guid><dc:creator>wesdyer</dc:creator><slash:comments>93</slash:comments><comments>http://blogs.msdn.com/wesdyer/comments/2820432.aspx</comments><wfw:commentRss>http://blogs.msdn.com/wesdyer/commentrss.aspx?PostID=2820432</wfw:commentRss><description>&lt;p&gt;It has been a while since I have posted.&amp;nbsp;&amp;nbsp;We have been&amp;nbsp;working hard to get Orcas beta 1 and beta 2 done.&amp;nbsp; So I apologize for the long interlude between posts but I hope that you are enjoying beta 1 and that you are looking forward to beta 2.&lt;/p&gt; &lt;p&gt;Now that beta 1 is out there, what do you all think of it?&amp;nbsp; Beta 1 has &lt;em&gt;most&lt;/em&gt; of the features that we intend to put into Orcas but not all of them.&amp;nbsp; Some notable differences you will see in later releases are improved performance, error messages, error recovery, stability, and a few refinements.&amp;nbsp; Basically the kind of polish that people expect as a product nears completion.&lt;/p&gt; &lt;p&gt;&lt;strong&gt;Partial Methods&lt;/strong&gt;&lt;/p&gt; &lt;p&gt;One feature that you may have not heard of yet is a feature called partial methods.&amp;nbsp; This is some of the work that I did in the last coding milestone a few months back.&amp;nbsp; Partial methods are methods that enable lightweight event handling.&amp;nbsp; Here is an example declaration:&lt;/p&gt; &lt;blockquote&gt; &lt;p&gt;&lt;font face="Courier New"&gt;&lt;/font&gt; &lt;p&gt;&lt;font face="Courier New"&gt;partial class C&lt;br&gt;{&lt;br&gt;&amp;nbsp; static partial void M(int i);&lt;br&gt;}&lt;/font&gt;&lt;/p&gt;&lt;/blockquote&gt; &lt;p&gt;There are a few notable things here:&lt;/p&gt; &lt;blockquote&gt; &lt;p&gt;1.&amp;nbsp; Partial methods must be declared within partial classes&lt;/p&gt; &lt;p&gt;2.&amp;nbsp; Partial methods are indicated by the partial modifier&lt;/p&gt; &lt;p&gt;3.&amp;nbsp; Partial methods do not always have a body (well look at this more below)&lt;/p&gt; &lt;p&gt;4.&amp;nbsp; Partial methods must return void&lt;/p&gt; &lt;p&gt;5.&amp;nbsp; Partial methods &lt;em&gt;can&lt;/em&gt; be static&lt;/p&gt; &lt;p&gt;6.&amp;nbsp; Partial methods can have arguments (including this, ref, and params modifiers)&lt;/p&gt; &lt;p&gt;&lt;strong&gt;7.&amp;nbsp; Partial methods &lt;em&gt;must&lt;/em&gt; be private&lt;/strong&gt;&lt;/p&gt;&lt;/blockquote&gt; &lt;p&gt;Now suppose that I make a call to C.M.&lt;/p&gt; &lt;blockquote&gt; &lt;p&gt;&lt;font face="Courier New"&gt;partial class C&lt;br&gt;{&lt;/font&gt;  &lt;p&gt;&lt;font face="Courier New"&gt;&amp;nbsp; static void Main()&lt;br&gt;&amp;nbsp; {&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; C.M(Calculation());&lt;br&gt;&amp;nbsp; }&lt;br&gt;}&lt;/font&gt;&lt;/p&gt;&lt;/blockquote&gt; &lt;p&gt;Since M has no body, all calls to C.M are removed at compile time &lt;em&gt;as well as the evaluation of the arguments&lt;/em&gt;.&amp;nbsp; So the above program is equivalent to:&lt;/p&gt; &lt;blockquote&gt; &lt;p&gt;&lt;font face="Courier New"&gt;partial class C&lt;br&gt;{&lt;/font&gt;  &lt;p&gt;&lt;font face="Courier New"&gt;&amp;nbsp; static void Main()&lt;br&gt;&amp;nbsp; {&lt;br&gt;&amp;nbsp; }&lt;br&gt;}&lt;/font&gt;&lt;/p&gt;&lt;/blockquote&gt; &lt;p&gt;In this sense, partial methods are the distant cousins of conditional methods which also sometimes remove the call and the evaluation of the arguments.&amp;nbsp; But partial methods go even further.&amp;nbsp; When a partial method has no body then the partial method is not even emitted to metadata.&lt;/p&gt; &lt;p&gt;So far this might seem a little confusing.&amp;nbsp; C# now allows users to declare methods for which the calls, the evaluation of the arguments, and the method itself are not emitted.&amp;nbsp; Fortunately, the story doesn't end there.&amp;nbsp; Partial methods allow users to define a body for the method so that the method, the calls, and the evaluation of the arguments are emitted.&lt;/p&gt; &lt;blockquote&gt; &lt;p&gt;&lt;font face="Courier New"&gt;partial class C&lt;br&gt;{&lt;br&gt;&amp;nbsp; static partial void M(int i); // defining declaration&lt;br&gt;&amp;nbsp; static partial void M(int i)&amp;nbsp; // implementing declaration&lt;br&gt;&amp;nbsp; {&lt;br&gt;&amp;nbsp; }&lt;br&gt;}&lt;/font&gt;&lt;/p&gt;&lt;/blockquote&gt; &lt;p&gt;In the code above, we see that there is a difference between a defining declaration of a partial method and an implementing declaration of a partial method and the difference is whether or not the method has a body.&amp;nbsp; These definitions don't have to be in the same partial class declaration.&amp;nbsp; There may only be one defining declaration and if a defining declaration exists then there may be an implementing declaration.&lt;/p&gt; &lt;p&gt;&lt;strong&gt;Why Partial Methods?&lt;/strong&gt;&lt;/p&gt; &lt;p&gt;So how are these partial methods used?&amp;nbsp; The common scenario is to use them to do lightweight event handling.&amp;nbsp; For example a tool that generates code may wish to have hooks for users to customize what code is run.&amp;nbsp; For example, imagine that a tool generated a bunch of code for a class representing a customer.&amp;nbsp; It might look like this:&lt;/p&gt; &lt;blockquote&gt; &lt;p&gt;&lt;font face="Courier New"&gt;partial class Customer&lt;br&gt;{&lt;br&gt;&amp;nbsp; string name; &lt;/font&gt; &lt;p&gt;&lt;font face="Courier New"&gt;&amp;nbsp; public string Name&lt;br&gt;&amp;nbsp; {&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; get&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; {&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; return name;&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;}&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; set&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; {&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; OnBeforeUpdateName();&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; OnUpdateName();&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; name = value;&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; OnAfterUpdateName();&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; }&lt;br&gt;&amp;nbsp;&amp;nbsp;} &lt;/font&gt; &lt;p&gt;&lt;font face="Courier New"&gt;&amp;nbsp; partial void OnBeforeUpdateName();&lt;br&gt;&amp;nbsp; partial void OnAfterUpdateName();&lt;br&gt;&amp;nbsp; partial void OnUpdateName();&lt;br&gt;}&lt;/font&gt;&lt;/p&gt;&lt;/blockquote&gt; &lt;p&gt;If the user doesn't add any implementing definitions then this code is equivalent to:&lt;/p&gt; &lt;blockquote&gt; &lt;p&gt;&lt;font face="Courier New"&gt;partial class Customer&lt;br&gt;{&lt;br&gt;&amp;nbsp; string name; &lt;/font&gt; &lt;p&gt;&lt;font face="Courier New"&gt;&amp;nbsp; public string Name&lt;br&gt;&amp;nbsp; {&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; get&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; {&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; return name;&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;}&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; set&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; {&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; name = value;&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; }&lt;br&gt;&amp;nbsp;&amp;nbsp;} &lt;/font&gt; &lt;p&gt;&lt;font face="Courier New"&gt;}&lt;/font&gt;&lt;/p&gt;&lt;/blockquote&gt; &lt;p&gt;No extra metadata for things that are not used and no extra instructions for useless operations.&amp;nbsp; On the other hand if the user listened to the OnUpdateName "event" like this:&lt;/p&gt; &lt;blockquote&gt; &lt;p&gt;&lt;font face="Courier New"&gt;partial class Customer&lt;br&gt;{&lt;br&gt;&amp;nbsp; partial void OnUpdateName()&lt;br&gt;&amp;nbsp; {&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; DoSomething();&lt;br&gt;&amp;nbsp; }&lt;br&gt;}&lt;/font&gt;&lt;/p&gt;&lt;/blockquote&gt; &lt;p&gt;Then the original definition is equivalent to:&lt;/p&gt; &lt;blockquote&gt; &lt;p&gt;&lt;font face="Courier New"&gt;partial class Customer&lt;br&gt;{&lt;br&gt;&amp;nbsp; string name; &lt;/font&gt; &lt;p&gt;&lt;font face="Courier New"&gt;&amp;nbsp; public string Name&lt;br&gt;&amp;nbsp; {&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; get&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; {&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; return name;&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;}&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; set&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; {&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; OnUpdateName();&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; name = value;&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; }&lt;br&gt;&amp;nbsp;&amp;nbsp;} &lt;/font&gt; &lt;p&gt;&lt;font face="Courier New"&gt;&amp;nbsp; partial void OnUpdateName();&lt;br&gt;}&lt;/font&gt;&lt;/p&gt;&lt;/blockquote&gt; &lt;p&gt;&lt;strong&gt;Comparing Partial Methods to the Alternatives&lt;/strong&gt;&lt;/p&gt; &lt;p&gt;At this point, it is sensible to ask why not just use subclassing and virtual methods?&amp;nbsp; Of course, this would also work but it does have the drawback that the calls, the methods, and the evaluation of the arguments will still be emitted even if the virtual methods are not overridden.&amp;nbsp; So in a system like Linq to SQL that has thousands of little events it allows these events to be very lightweight so that the user only pays for those events that she uses.&lt;/p&gt; &lt;p&gt;&lt;strong&gt;A Few Fine Points&lt;/strong&gt;&lt;/p&gt; &lt;p&gt;Consider the following program...&lt;/p&gt; &lt;blockquote&gt; &lt;p&gt;&lt;font face="Courier New"&gt;partial class C&lt;br&gt;{&lt;br&gt;&amp;nbsp; static void Main()&lt;br&gt;&amp;nbsp; {&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; int i = 3;&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; C.M(i = 5);&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; Console.WriteLine(i);&lt;br&gt;&amp;nbsp; }&lt;br&gt;}&lt;/font&gt;&lt;/p&gt;&lt;/blockquote&gt; &lt;p&gt;What does it write to the console?&amp;nbsp; 3, 5, ...?&lt;/p&gt; &lt;p&gt;Actually, it is impossible to tell from just this code.&amp;nbsp; If there is no implementing declaration then the program will display 3 because the i = 5 will never be evaluated, but if there is an implementing declaration then the program will display 5.&amp;nbsp; The same is true for conditional methods.&amp;nbsp; So if you want a side-effect to occur make sure you do not cause the side-effect to occur as an argument to a partial method.&amp;nbsp; Of course, the same trick can be used to hide expensive calculations.&lt;/p&gt; &lt;blockquote&gt; &lt;p&gt;&lt;font face="Courier New"&gt;partial class C&lt;br&gt;{&lt;br&gt;&amp;nbsp; static void Main()&lt;br&gt;&amp;nbsp; {&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; C.M(VeryVeryExpensiveCalculation());&lt;br&gt;&amp;nbsp; }&lt;br&gt;}&lt;/font&gt;&lt;/p&gt;&lt;/blockquote&gt; &lt;p&gt;If there is no implementing declaration then the very very expensive calculation will never be performed.&lt;/p&gt; &lt;p&gt;Now what about attributes, how does those work?&lt;/p&gt; &lt;blockquote&gt; &lt;p&gt;&lt;font face="Courier New"&gt;partial class D&lt;br&gt;{&lt;br&gt;&amp;nbsp; [W]&lt;br&gt;&amp;nbsp; [return:X]&lt;br&gt;&amp;nbsp; partial void M&amp;lt;[Y]T&amp;gt;([Z]int foo)&lt;br&gt;&amp;nbsp; {&lt;br&gt;&amp;nbsp; } &lt;/font&gt; &lt;p&gt;&lt;font face="Courier New"&gt;&amp;nbsp; [Z]&lt;br&gt;&amp;nbsp; [return:W]&lt;br&gt;&amp;nbsp; partial void M&amp;lt;[X]T&amp;gt;([Y]int foo);&lt;br&gt;}&lt;/font&gt;&lt;/p&gt;&lt;/blockquote&gt; &lt;p&gt;What attributes are actually emitted on M?&amp;nbsp; W and Z are the attributes on M; X and W are the attributes on the return type; Y and X are the attributes on the type parameter; Z and Y are the attributes on the parameter.&lt;/p&gt; &lt;p&gt;Enjoy!&lt;/p&gt;&lt;img src="http://blogs.msdn.com/aggbug.aspx?PostID=2820432" width="1" height="1"&gt;</description><category domain="http://blogs.msdn.com/wesdyer/archive/tags/C_2300_/default.aspx">C#</category></item><item><title>All About Iterators</title><link>http://blogs.msdn.com/wesdyer/archive/2007/03/23/all-about-iterators.aspx</link><pubDate>Fri, 23 Mar 2007 11:26:00 GMT</pubDate><guid isPermaLink="false">91d46819-8472-40ad-a661-2c78acb4018c:1935848</guid><dc:creator>wesdyer</dc:creator><slash:comments>16</slash:comments><comments>http://blogs.msdn.com/wesdyer/comments/1935848.aspx</comments><wfw:commentRss>http://blogs.msdn.com/wesdyer/commentrss.aspx?PostID=1935848</wfw:commentRss><description>&lt;p&gt;&lt;a href="http://en.wikipedia.org/wiki/Design_pattern_(computer_science)"&gt;Design patterns&lt;/a&gt; have been all of the rage for a number of years now.&amp;nbsp; We have design patterns for concurrency, user interfaces, data access, object creation, and so many other things.&amp;nbsp; The seminal work on the topic is the &lt;a href="http://en.wikipedia.org/wiki/Gang_of_Four_%28software%29"&gt;Gang of Four&lt;/a&gt;'s book, &lt;a href="http://www.amazon.com/Design-Patterns-Object-Oriented-Addison-Wesley-Professional/dp/0201633612/ref=pd_bbs_1/002-3886557-6494420?ie=UTF8&amp;amp;s=books&amp;amp;qid=1174622120&amp;amp;sr=8-1"&gt;Design Patterns&lt;/a&gt;.&amp;nbsp; When used appropriately they are a fantastic way to codify the wisdom gleaned from the battles we have fought building software systems.&lt;/p&gt; &lt;p&gt;&lt;a href="http://www.paulgraham.com/icad.html"&gt;One&lt;/a&gt; &lt;a href="http://perl.plover.com/yak/design/"&gt;of&lt;/a&gt; &lt;a href="http://discuss.joelonsoftware.com/default.asp?joel.3.219431.12"&gt;the&lt;/a&gt; &lt;a href="http://norvig.com/design-patterns/ppframe.htm"&gt;criticisms&lt;/a&gt; &lt;a href="http://www.parand.com/say/index.php/2005/07/18/i-hate-patterns/"&gt;leveled&lt;/a&gt; &lt;a href="http://citeseer.ist.psu.edu/felleisen90expressive.html"&gt;at&lt;/a&gt; &lt;a href="http://etymon.blogspot.com/2006/04/perils-of-avoiding-heresy-or-what-are.html"&gt;design&lt;/a&gt; &lt;a href="http://blog.plover.com/prog/design-patterns.html"&gt;patterns&lt;/a&gt; is that they are simply formalisms to address&amp;nbsp;weaknesses in&amp;nbsp;programming languages.&amp;nbsp; They require&amp;nbsp;the human compiler to generate code&amp;nbsp;whenever a&amp;nbsp;specific recurring problem is encountered that cannot be solved directly with language support.&amp;nbsp; Now this might sound like heresy to some, but&amp;nbsp;there is some truth to the criticism.&amp;nbsp; Programmers adapt to the shortcomings in the languages they use by generating pattern like code either by hand or with &lt;a href="http://en.wikipedia.org/wiki/Metaprogramming"&gt;metaprogramming&lt;/a&gt; (generics, dynamic code generation, reflection, expression trees, macros).&lt;/p&gt; &lt;p&gt;Let's take a look at one such example.&lt;/p&gt; &lt;p&gt;&lt;strong&gt;The Iterator Design Pattern&lt;/strong&gt;&lt;/p&gt; &lt;p&gt;Among the many patterns&amp;nbsp;in the literature is the &lt;a href="http://en.wikipedia.org/wiki/Iterator_pattern"&gt;iterator pattern&lt;/a&gt;.&lt;/p&gt; &lt;p&gt;&lt;img height="275" alt="Iterator Design Pattern" src="http://blogs.msdn.com/blogfiles/wesdyer/WindowsLiveWriter/TheCostofIterators_A895/image015.png" width="420"&gt;&amp;nbsp;&lt;/p&gt; &lt;p&gt;In .NET this pattern is embodied by &lt;a href="http://msdn2.microsoft.com/en-us/library/system.collections.ienumerable.aspx"&gt;IEnumerable&lt;/a&gt;/&lt;a href="http://msdn2.microsoft.com/en-us/library/9eekhta0.aspx"&gt;IEnumerable&amp;lt;T&amp;gt;&lt;t&gt;&lt;/a&gt; and &lt;a href="http://msdn2.microsoft.com/en-us/library/system.collections.ienumerator.aspx"&gt;IEnumerator&lt;/a&gt;/&lt;a href="http://msdn2.microsoft.com/en-us/library/78dfe2yb.aspx"&gt;IEnumerator&amp;lt;T&amp;gt;&lt;t&gt;&lt;/a&gt;.&lt;/p&gt; &lt;p&gt;&lt;img height="78" alt="IEnumerable&amp;lt;T&amp;gt; and IEnumerator&amp;lt;T&amp;gt;" src="http://blogs.msdn.com/blogfiles/wesdyer/WindowsLiveWriter/TheCostofIterators_A895/image014.png" width="425"&gt; &lt;/p&gt; &lt;p&gt;An IEnumerable&amp;lt;T&amp;gt; is something that can be enumerated (iterated) by calling GetEnumerator which will return an IEnumerator&amp;lt;T&amp;gt; (iterator).&amp;nbsp; The IEnumerator&amp;lt;T&amp;gt; is used to move a virtual cursor over the items that are iterated.&lt;/p&gt; &lt;p&gt;Implementing the iterator pattern is a bit onerous.&amp;nbsp; For example, here is the suggested iterator implementation for List&amp;lt;T&amp;gt;&amp;nbsp;from the Design Pattern book.&lt;/p&gt; &lt;blockquote&gt; &lt;p&gt;&lt;font face="Courier New"&gt;class ListIterator&amp;lt;T&amp;gt; : IEnumerator&amp;lt;T&amp;gt;&lt;br&gt;{&lt;br&gt;&amp;nbsp; List&amp;lt;T&amp;gt; list;&lt;br&gt;&amp;nbsp; int current; &lt;/font&gt; &lt;p&gt;&lt;font face="Courier New"&gt;&amp;nbsp; public ListIterator(List&amp;lt;T&amp;gt; list)&lt;br&gt;&amp;nbsp; {&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; this.list = list;&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; current = -1;&lt;br&gt;&amp;nbsp; } &lt;/font&gt; &lt;p&gt;&lt;font face="Courier New"&gt;&amp;nbsp; public T Current {&amp;nbsp;get { return list[current]; } } &lt;/font&gt; &lt;p&gt;&lt;font face="Courier New"&gt;&amp;nbsp; public bool MoveNext()&lt;br&gt;&amp;nbsp; {&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; return ++current &amp;lt; list.Count;&lt;br&gt;&amp;nbsp; } &lt;/font&gt; &lt;p&gt;&lt;font face="Courier New"&gt;&amp;nbsp; public void Reset()&lt;br&gt;&amp;nbsp; {&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; current = -1;&lt;br&gt;&amp;nbsp; }&lt;br&gt;}&lt;/font&gt;&lt;/p&gt;&lt;/blockquote&gt; &lt;p&gt;Since we can't change the list itself, we can introduce a ListIterable&amp;lt;T&amp;gt; that wraps a list.&lt;/p&gt; &lt;blockquote&gt; &lt;p&gt;&lt;font face="Courier New"&gt;class ListIterable&amp;lt;T&amp;gt; : IEnumerable&amp;lt;T&amp;gt;&lt;br&gt;{&lt;br&gt;&amp;nbsp; List&amp;lt;T&amp;gt; list; &lt;/font&gt; &lt;p&gt;&lt;font face="Courier New"&gt;&amp;nbsp; public ListIterable(List&amp;lt;T&amp;gt; list)&lt;br&gt;&amp;nbsp; {&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; this.list = list;&lt;br&gt;&amp;nbsp; } &lt;/font&gt; &lt;p&gt;&lt;font face="Courier New"&gt;&amp;nbsp; public IEnumerator&amp;lt;T&amp;gt; GetEnumerator()&lt;br&gt;&amp;nbsp; {&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; return new ListIterator&amp;lt;T&amp;gt;(list);&lt;br&gt;&amp;nbsp; } &lt;/font&gt; &lt;p&gt;&lt;font face="Courier New"&gt;} &lt;/font&gt;&lt;/p&gt;&lt;/blockquote&gt; &lt;p&gt;And finally, we can write a method called GetElements which returns an IEnumerable&amp;lt;T&amp;gt; over the elements of a List&amp;lt;T&amp;gt;.&lt;/p&gt; &lt;blockquote&gt; &lt;p&gt;&lt;font face="Courier New"&gt;static IEnumerable&amp;lt;T&amp;gt; GetElements&amp;lt;T&amp;gt;(this List&amp;lt;T&amp;gt; list)&lt;br&gt;{&lt;br&gt;&amp;nbsp; return new ListIterable&amp;lt;T&amp;gt;(list);&lt;br&gt;}&lt;/font&gt;&lt;/p&gt;&lt;/blockquote&gt; &lt;p&gt;&lt;strong&gt;Iterators in C#&lt;/strong&gt;&lt;/p&gt; &lt;p&gt;Fortunately in most cases programmers don't need to deal with the iterator design pattern directly since the introduction of iterators in C# 2.0.&amp;nbsp; Instead of writing the iterator above, we can simply write the following:&lt;/p&gt; &lt;blockquote&gt; &lt;p&gt;&lt;font face="Courier New"&gt;static IEnumerable&amp;lt;T&amp;gt; GetElements&amp;lt;T&amp;gt;(this List&amp;lt;T&amp;gt; list)&lt;br&gt;{&lt;br&gt;&amp;nbsp; for (int index = 0; index &amp;lt; list.Count; ++index)&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; yield return list[index];&lt;br&gt;}&lt;/font&gt;&lt;/p&gt;&lt;/blockquote&gt; &lt;p&gt;When the C# compiler sees this method, it translates it into something very similar to the ListIterator&amp;lt;T&amp;gt; and ListIterable&amp;lt;T&amp;gt;&amp;nbsp;above.&amp;nbsp; Using Reflector or ILDasm we can see that the GetElements method is rewritten as (the names have been changed for clarity as the compiler generates unspeakable names;):  &lt;blockquote&gt;&lt;pre&gt;&lt;/pre&gt;
&lt;p&gt;&lt;font face="Courier New"&gt;private static IEnumerable&amp;lt;T&amp;gt; GetElements&amp;lt;T&amp;gt;(this List&amp;lt;T&amp;gt; list)&lt;br&gt;{&lt;br&gt;&amp;nbsp; GetElementsIterator&amp;lt;T&amp;gt; temp = new GetElementsIterator&amp;lt;T&amp;gt;(-2);&lt;br&gt;&amp;nbsp; temp.listParameter = list;&lt;br&gt;&amp;nbsp; return temp;&lt;br&gt;}&lt;/font&gt;&lt;pre&gt;&lt;/pre&gt;&lt;/blockquote&gt;
&lt;p&gt;This is remarkably closer to the first GetElements&amp;nbsp;we wrote rather than the second.&amp;nbsp;&amp;nbsp;Like in the first GetElements, we create an object that implements IEnumerable&amp;lt;T&amp;gt; and parameterize this object with the list that was passed in.&amp;nbsp; The &lt;em&gt;only&lt;/em&gt; other thing that happens in this implementation that doesn't in the first GetElements method&amp;nbsp;is a -2 is passed into the object.&amp;nbsp; I'll come back to this later, but first let's take a look at the GetElementsIterator&amp;lt;T&amp;gt; class (I omitted a few details and changed names&amp;nbsp;for clarity). 
&lt;blockquote&gt;&lt;pre&gt;&lt;/pre&gt;
&lt;p&gt;&lt;font face="Courier New"&gt;private sealed class GetElementsIterator&amp;lt;T&amp;gt; : IEnumerable&amp;lt;T&amp;gt;, IEnumerator&amp;lt;T&amp;gt;&lt;br&gt;{&lt;br&gt;&amp;nbsp; int state;&lt;br&gt;&amp;nbsp; T current;&lt;br&gt;&amp;nbsp; public List&amp;lt;T&amp;gt; listParameter;&lt;br&gt;&amp;nbsp; int initialThreadId;&lt;br&gt;&amp;nbsp; public int index;&lt;br&gt;&amp;nbsp; public List&amp;lt;T&amp;gt; list; &lt;/font&gt;
&lt;p&gt;&lt;font face="Courier New"&gt;&amp;nbsp; public GetElementsIterator(int state);&lt;br&gt;&amp;nbsp; private bool MoveNext();&lt;br&gt;&amp;nbsp; IEnumerator&amp;lt;T&amp;gt; IEnumerable&amp;lt;T&amp;gt;.GetEnumerator();&lt;br&gt;&amp;nbsp; void IEnumerator.Reset(); &lt;/font&gt;
&lt;p&gt;&lt;font face="Courier New"&gt;&amp;nbsp; T IEnumerator&amp;lt;T&amp;gt;.Current { get; }&lt;br&gt;}&lt;/font&gt;&lt;/p&gt;&lt;/blockquote&gt;
&lt;p&gt;The most important thing to note at this time is that GetElementsIterator implements &lt;em&gt;both &lt;/em&gt;IEnumerable&amp;lt;T&amp;gt; and IEnumerator&amp;lt;T&amp;gt;.&amp;nbsp; A strange combination, but we will see why in a little while.&amp;nbsp; Now let's look at what actually happened when we ran the constructor.&amp;nbsp; &lt;pre&gt;&lt;/pre&gt;
&lt;p&gt;
&lt;blockquote&gt;
&lt;p&gt;&lt;font face="Courier New"&gt;public GetElementsIterator(int state)&lt;br&gt;{&lt;br&gt;&amp;nbsp; this.state = state;&lt;br&gt;&amp;nbsp; this.initialThreadId = Thread.CurrentThread.ManagedThreadId;&lt;br&gt;}&lt;/font&gt;&lt;/p&gt;&lt;/blockquote&gt;
&lt;p&gt;Did the constructor run the for loop?&amp;nbsp; No, it didn't.&amp;nbsp; It took some variable called state in and marked what thread created the iterator (if you look at Whidbey code the initialThreadId stuff won't be there...I'll get to that).&amp;nbsp; The state variable marks what state the GetElementsIterator is in.&amp;nbsp; The number -2 is the "I'm an IEnumerable&amp;lt;T&amp;gt;" state.&amp;nbsp; Now, let's look at the GetEnumerator method. 
&lt;blockquote&gt;&lt;pre&gt;&lt;/pre&gt;
&lt;p&gt;&lt;font face="Courier New"&gt;IEnumerator&amp;lt;T&amp;gt; IEnumerable&amp;lt;T&amp;gt;.GetEnumerator()&lt;br&gt;{&lt;br&gt;&amp;nbsp; GetElementsIterator&amp;lt;T&amp;gt; temp;&lt;br&gt;&amp;nbsp; if ((Thread.CurrentThread.ManagedThreadId == initialThreadId) &amp;amp;&amp;amp; (state == -2))&lt;br&gt;&amp;nbsp; {&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; state = 0;&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; temp = this;&lt;br&gt;&amp;nbsp; }&lt;br&gt;&amp;nbsp; else&lt;br&gt;&amp;nbsp; {&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; temp = new GetElementsIterator&amp;lt;T&amp;gt;(0);&lt;br&gt;&amp;nbsp; }&lt;br&gt;&amp;nbsp; temp.list = this.listParameter;&lt;br&gt;&amp;nbsp; return temp;&lt;br&gt;}&lt;/font&gt;&lt;/p&gt;&lt;/blockquote&gt;&lt;pre&gt;&lt;/pre&gt;
&lt;p&gt;The method first checks to see if the thread that is calling GetEnumerator is the same thread that created the GetElementsIterator object.&amp;nbsp; If it is the same thread and if the GetElementsIterator is in the "I'm an IEnumerable&amp;lt;T&amp;gt;" state then the state is changed to the "I'm an initialized IEnumerator&amp;lt;T&amp;gt;" state.&amp;nbsp; Otherwise, a new object of the same type is created but it is immediately put in the "I'm an initialized IEnumerator&amp;lt;T&amp;gt;" state so that thread safety is maintained.&amp;nbsp; Finally, in either case the list that was passed from the GetElements method is copied into the list field for consumption by the MoveNext method. 
&lt;p&gt;In Whidbey code, you will see that the if statement is different because an Interlock.Exchange was used to perform the same task.&amp;nbsp; The change was made to improve performance (especially for iterators that have 0 or 1 items to iterate over). 
&lt;p&gt;Now we have seen why GetElementsIterator implements both IEnumerable&amp;lt;T&amp;gt; and IEnumerator&amp;lt;T&amp;gt;, because it can morph from the IEnumerable&amp;lt;T&amp;gt; role into the IEnumerator&amp;lt;T&amp;gt; role without creating any new objects in most cases. 
&lt;p&gt;The Current property is very simple. 
&lt;blockquote&gt;&lt;pre&gt;&lt;/pre&gt;
&lt;p&gt;&lt;font face="Courier New"&gt;T IEnumerator&amp;lt;T&amp;gt;.Current&lt;br&gt;{&lt;br&gt;&amp;nbsp; get&lt;br&gt;&amp;nbsp; {&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; return current;&lt;br&gt;&amp;nbsp; }&lt;br&gt;}&lt;/font&gt;&lt;/p&gt;&lt;/blockquote&gt;&lt;pre&gt;&lt;/pre&gt;
&lt;p&gt;The Reset method simply throws a NotSupportedException. 
&lt;p&gt;This leaves us with only the MoveNext to examine.&amp;nbsp; We still haven't seen where the for loop went.&amp;nbsp; Hopefully, it is in the MoveNext.&amp;nbsp; The following code is produced with the /o+ compiler option (optimizations turned on). 
&lt;blockquote&gt;&lt;pre&gt;&lt;/pre&gt;
&lt;p&gt;&lt;font face="Courier New"&gt;private bool MoveNext()&lt;br&gt;{&lt;br&gt;&amp;nbsp; switch (state)&lt;br&gt;&amp;nbsp; {&lt;br&gt;&amp;nbsp; case 0:&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; state = -1;&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; index = 0;&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; break; &lt;/font&gt;
&lt;p&gt;&lt;font face="Courier New"&gt;&amp;nbsp; case 1:&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; state = -1;&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; index++;&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; break; &lt;/font&gt;
&lt;p&gt;&lt;font face="Courier New"&gt;&amp;nbsp; default:&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; goto Done;&lt;br&gt;&amp;nbsp; }&lt;br&gt;&amp;nbsp; if (index &amp;lt; list.Count)&lt;br&gt;&amp;nbsp; {&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; current = list[index];&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; state = 1;&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; return true;&lt;br&gt;&amp;nbsp; }&lt;br&gt;Done:&lt;br&gt;&amp;nbsp; return false;&lt;br&gt;}&lt;/font&gt;&lt;/p&gt;&lt;/blockquote&gt;&lt;pre&gt;&lt;/pre&gt;
&lt;p&gt;Hm...a switch statement over a variable called state with a number integer case labels.&amp;nbsp; It looks like a state machine and indeed it is.&amp;nbsp; When MoveNext is first called, state is equal to 0, so the state is set to -1 (the "I'm finished" state) and the index is set to 0.&amp;nbsp; Then we check to see if the index is less than the number of things in the list.&amp;nbsp; If so then we set current to the current list element based on the index and set the state to 1.&amp;nbsp; We return true indicating that there is something to consume. 
&lt;p&gt;The second call to MoveNext will run case 1 since the state is equal to 1.&amp;nbsp; It will again set the state to -1 and increment the index.&amp;nbsp; If we still have elements in the list then the current will be set appropriately and the state will be set to 1 (the "we need to check again" state) and true will be returned. 
&lt;p&gt;This continues until there nothing left to consume and false is returned. 
&lt;p&gt;Finally, we found our for loop.&amp;nbsp; It is encoded in the MoveNext.&amp;nbsp; But note that on each call to MoveNext is only computes the part of the for loop that is relevant to realize the next element.&amp;nbsp; It never computes more than it needs to.&amp;nbsp; This is why iterators are an example of deferred execution.&amp;nbsp; When the actual GetElements method was called, no elements were realized at all!&amp;nbsp; Later as MoveNext is called, one element at a time is realized.&amp;nbsp; This of course enables all of sorts of &lt;a href="http://blogs.msdn.com/wesdyer/archive/2007/02/13/the-virtues-of-laziness.aspx"&gt;great scenarios&lt;/a&gt; such as the pay-as-you-go model and the ability to have infinite lists. 
&lt;p&gt;&lt;strong&gt;The Cost of Iterators&lt;/strong&gt; 
&lt;p&gt;Iterators are very performant.&amp;nbsp; In almost all situations that I have encountered they are more than performant enough and they simplify the code drastically as we have seen.&amp;nbsp; But sometimes you can get into trouble. 
&lt;p&gt;Consider the definition of the Concat sequence operator in Linq to Objects.&amp;nbsp; It looks something like this: 
&lt;blockquote&gt;
&lt;p&gt;&lt;font face="Courier New"&gt;static IEnumerable&amp;lt;T&amp;gt; Concat&amp;lt;T&amp;gt;(this IEnumerable&amp;lt;T&amp;gt; sequence1, IEnumerable&amp;lt;T&amp;gt; sequence2)&lt;br&gt;{&lt;br&gt;&amp;nbsp; foreach (var item in sequence1)&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; yield return item;&lt;br&gt;&amp;nbsp; foreach (var item in sequence2)&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; yield return item;&lt;br&gt;}&lt;/font&gt;&lt;/p&gt;&lt;/blockquote&gt;
&lt;p&gt;Let's write a little benchmark to evaluate the performance of concat. 
&lt;blockquote&gt;
&lt;p&gt;&lt;font face="Courier New"&gt;var stopWatch = new Stopwatch();&lt;br&gt;for (int length = 0; length &amp;lt;= 10000; length += 1000)&lt;br&gt;{&lt;br&gt;&amp;nbsp; var list = new[] { 1 };&lt;br&gt;&amp;nbsp; IEnumerable&amp;lt;int&amp;gt; ones = list;&lt;br&gt;&amp;nbsp; for (int i = 0; i &amp;lt; length; ++i)&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; ones = ones.Concat(list); &lt;/font&gt;
&lt;p&gt;&lt;font face="Courier New"&gt;&amp;nbsp; stopWatch.Reset();&lt;br&gt;&amp;nbsp; stopWatch.Start(); &lt;/font&gt;
&lt;p&gt;&lt;font face="Courier New"&gt;&amp;nbsp; foreach (var item in ones) ; &lt;/font&gt;
&lt;p&gt;&lt;font face="Courier New"&gt;&amp;nbsp; stopWatch.Stop();&lt;br&gt;&amp;nbsp; Console.WriteLine("Length: {0} Time: {1}", length, stopWatch.ElapsedMilliseconds);&lt;br&gt;}&lt;/font&gt;&lt;/p&gt;&lt;/blockquote&gt;
&lt;p&gt;The results may be perhaps surprising.&amp;nbsp; The time to evalute the foreach statement is not linearly proportional to the number of concats that are composed together.&amp;nbsp; In fact it is proportional to the square of the number of concats composed together.&lt;/p&gt;&lt;a href="http://blogs.msdn.com/blogfiles/wesdyer/WindowsLiveWriter/TheCostofIterators_A895/image022.png" atomicselection="true"&gt;&lt;img style="border-top-width: 0px; border-left-width: 0px; border-bottom-width: 0px; border-right-width: 0px" height="307" src="http://blogs.msdn.com/blogfiles/wesdyer/WindowsLiveWriter/TheCostofIterators_A895/image0_thumb14.png" width="520" border="0"&gt;&lt;/a&gt; 
&lt;p&gt;Upon closer inspection the reason why is obvious.&amp;nbsp; The time complexity of Concat is O(m+n) where m is the number of items in the first sequence and n is the number of items in the second sequence.&amp;nbsp; But note that in this example, n is always 1.&amp;nbsp; The outermost call is O(m+1).&amp;nbsp; The next call has O((m-1)+1), then O((m-2)+1), ... O(1+1).&amp;nbsp; There are m of these calls so the running time should be O(m^2).&amp;nbsp; Essentially, composing concats together like this causes O(m^2) yield returns to be executed. 
&lt;p&gt;Of course, using a List&amp;lt;T&amp;gt; here and adding on the sequences would have been much more performant because it eliminates the redundant calculations but it would not have been evaluated lazily. 
&lt;p&gt;Iterators are even more fun if the data structure that is being enumerated is more complicated.&amp;nbsp; For example, consider iterating over n-ary trees.&amp;nbsp; Here is a quick definition of a n-ary tree. 
&lt;blockquote&gt;
&lt;p&gt;&lt;font face="Courier New"&gt;&lt;/font&gt;
&lt;p&gt;&lt;font face="Courier New"&gt;class Tree&amp;lt;T&amp;gt;&lt;br&gt;{&lt;br&gt;&amp;nbsp; public T Value { get; private set; }&lt;br&gt;&amp;nbsp; public Tree&amp;lt;T&amp;gt; NextSibling { get; private set; }&lt;br&gt;&amp;nbsp; public Tree&amp;lt;T&amp;gt; FirstChild { get; private set; } &lt;/font&gt;
&lt;p&gt;&lt;font face="Courier New"&gt;&amp;nbsp; public Tree(T value, Tree&amp;lt;T&amp;gt; nextSibling, Tree&amp;lt;T&amp;gt; firstChild)&lt;br&gt;&amp;nbsp; {&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; Value = value;&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; NextSibling = nextSibling;&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; FirstChild = firstChild;&lt;br&gt;&amp;nbsp; } &lt;/font&gt;
&lt;p&gt;&lt;font face="Courier New"&gt;&amp;nbsp; public IEnumerable&amp;lt;Tree&amp;lt;T&amp;gt;&amp;gt; GetChildren()&lt;br&gt;&amp;nbsp; {&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; for (var current = FirstChild; current != null; current = current.NextSibling)&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; yield return current;&lt;br&gt;&amp;nbsp; }&lt;br&gt;}&lt;/font&gt;&lt;/p&gt;&lt;/blockquote&gt;
&lt;p&gt;Now it is easy to define an iterator that performs a preorder traversal of a n-ary tree. 
&lt;blockquote&gt;
&lt;p&gt;&lt;font face="Courier New"&gt;&lt;/font&gt;
&lt;p&gt;&lt;font face="Courier New"&gt;static IEnumerable&amp;lt;T&amp;gt; PreOrderWalk&amp;lt;T&amp;gt;(this Tree&amp;lt;T&amp;gt; tree)&lt;br&gt;{&lt;br&gt;&amp;nbsp; if (tree == null)&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; yield break;&lt;br&gt;&amp;nbsp; yield return tree.Value;&lt;br&gt;&amp;nbsp; foreach (var subTree in tree.GetChildren())&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; foreach (var item in subTree.PreOrderWalk())&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; yield return item;&lt;br&gt;}&lt;/font&gt;&lt;/p&gt;&lt;/blockquote&gt;
&lt;p&gt;Just the way that I like code: clear and concise.&amp;nbsp; The only problem is that the iterator could be more efficient.&amp;nbsp; This may or may not be a problem.&amp;nbsp; In a library it will almost certainly be a problem. 
&lt;p&gt;We can improve the efficiency somewhat by changing the code: 
&lt;blockquote&gt;
&lt;p&gt;&lt;font face="Courier New"&gt;static IEnumerable&amp;lt;T&amp;gt; PreOrderWalk&amp;lt;T&amp;gt;(this Tree&amp;lt;T&amp;gt; tree)&lt;br&gt;{&lt;br&gt;&amp;nbsp; var stack = new Stack&amp;lt;Tree&amp;lt;T&amp;gt;&amp;gt;();&lt;br&gt;&amp;nbsp; if (tree != null)&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; stack.Push(tree);&lt;br&gt;&amp;nbsp; while (stack.Count &amp;gt; 0)&lt;br&gt;&amp;nbsp; {&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; for (var current = stack.Pop(); current != null; current = current.FirstChild)&lt;br&gt;&amp;nbsp; &amp;nbsp; {&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &amp;nbsp; yield return current.Value;&lt;br&gt;&amp;nbsp; &amp;nbsp;&amp;nbsp;&amp;nbsp; if (current.NextSibling != null)&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &amp;nbsp; stack.Push(current.NextSibling);&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; }&lt;br&gt;&amp;nbsp; }&lt;br&gt;}&lt;/font&gt;&lt;/p&gt;&lt;/blockquote&gt;
&lt;p&gt;This second iterator doesn't recursively call iterators thus&amp;nbsp;avoiding both the recursive call and the extra allocations.&amp;nbsp; Instead, it maintains a stack of work to do after the leftmost path has been exhausted.&amp;nbsp; Once the leftmost path has been exhausted then a node is popped off and the leftmost traversal is resumed at that node. 
&lt;p&gt;When we measure the difference, we see that the improvement is noticeable but that the number of nodes, O(b^d) where b is the branching factor and d is depth,&amp;nbsp;dominates the cost of the traversal.&amp;nbsp; In the graph below, the green line indicates the total number of nodes in the tree.&amp;nbsp; The trees have a branching factor of 2. 
&lt;p&gt;&lt;a href="http://blogs.msdn.com/blogfiles/wesdyer/WindowsLiveWriter/TheCostofIterators_A895/image026.png" atomicselection="true"&gt;&lt;img style="border-top-width: 0px; border-left-width: 0px; border-bottom-width: 0px; border-right-width: 0px" height="310" src="http://blogs.msdn.com/blogfiles/wesdyer/WindowsLiveWriter/TheCostofIterators_A895/image0_thumb16.png" width="517" border="0"&gt;&lt;/a&gt; 
&lt;p&gt;So the key takeaway here is that iterators have great performance but as always &lt;em&gt;measure the performance of your code&lt;/em&gt;.&amp;nbsp; If you find that performance is suffering, use a combination of profiling and analysis to find the problem.&amp;nbsp; If the problem is an iterator, you might be able to increase the performance by reworking the iterator as in the n-ary tree case.&amp;nbsp; In other cases, it might be the usage of the iterators as&amp;nbsp;with pathological Concats. 
&lt;p&gt;&lt;strong&gt;One Possibility for Language Improvement (not in Orcas)&lt;/strong&gt; 
&lt;p&gt;The Concat sequence operator is interesting because there is a lot of code that is seemingly redundant.&amp;nbsp; It takes two sequences and then has to iterate over them and yield their elements.&amp;nbsp; It's like it needs to expand their insides just to package them up together again.&amp;nbsp; As we have seen this doesn't lead to the best performance and the code is overly verbose. 
&lt;p&gt;Bart Jacobs, Erik Meijer, Frank Piessens, and Wolfram Shulte wrote &lt;a href="http://citeseer.ist.psu.edu/cache/papers/cs2/355/http:zSzzSzwww.cs.kuleuven.ac.bezSz~frankzSzPAPERSzSzFTfJP2005.pdf/iterators-revisited-proof-rules.pdf"&gt;a very interesting paper&lt;/a&gt; on a possible language improvement that would improve both the usability and the performance of iterators.&amp;nbsp; The second half of the paper details what they call nested iterators which avoid the multiple evaluation problem of the composed Concats and implicitly keep an internal stack like the modified n-ary tree iterator. 
&lt;p&gt;For example with this language feature, the Concat sequence operator would look something like this: 
&lt;blockquote&gt;
&lt;p&gt;&lt;font face="Courier New"&gt;static IEnumerable&amp;lt;T&amp;gt; Concat&amp;lt;T&amp;gt;(this IEnumerable&amp;lt;T&amp;gt; sequence1, IEnumerable&amp;lt;T&amp;gt; sequence2)&lt;br&gt;{&lt;br&gt;&amp;nbsp; yield foreach sequence1;&lt;br&gt;&amp;nbsp; yield foreach sequence2;&lt;br&gt;}&lt;/font&gt;&lt;/p&gt;&lt;/blockquote&gt;
&lt;p&gt;Notice that the code is simplier and it is also more performant. 
&lt;p&gt;A&amp;nbsp;programmer could use yield return, yield break, and yield foreach in the same iterator.&amp;nbsp; An iterator FromTo can be defined recursively as follows: 
&lt;blockquote&gt;
&lt;p&gt;&lt;font face="Courier New"&gt;static IEnumerable&amp;lt;int&amp;gt; FromTo(int b, int e)&lt;br&gt;{&lt;br&gt;&amp;nbsp; if (b &amp;gt; e)&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; yield break;&lt;br&gt;&amp;nbsp; yield return b;&lt;br&gt;&amp;nbsp; yield foreach FromTo(b + 1, e);&lt;br&gt;}&lt;/font&gt;&lt;/p&gt;&lt;/blockquote&gt;
&lt;p&gt;If instead of the yield foreach, there was the foreach expansion that yielded each result then the FromTo method would suffer from quadratic performance; however, with nested iterators the performance would be linear. 
&lt;p&gt;&lt;a href="http://blogs.msdn.com/blogfiles/wesdyer/WindowsLiveWriter/TheCostofIterators_A895/image031.png" atomicselection="true"&gt;&lt;img style="border-top-width: 0px; border-left-width: 0px; border-bottom-width: 0px; border-right-width: 0px" height="368" src="http://blogs.msdn.com/blogfiles/wesdyer/WindowsLiveWriter/TheCostofIterators_A895/image0_thumb19.png" width="558" border="0"&gt;&lt;/a&gt; 
&lt;p&gt;The next post will pick up on understanding the performance of Linq to objects queries. 
&lt;img src="http://blogs.msdn.com/aggbug.aspx?PostID=1935848" width="1" height="1"&gt;</description><category domain="http://blogs.msdn.com/wesdyer/archive/tags/Programming/default.aspx">Programming</category><category domain="http://blogs.msdn.com/wesdyer/archive/tags/C_2300_/default.aspx">C#</category><category domain="http://blogs.msdn.com/wesdyer/archive/tags/Design+Patterns/default.aspx">Design Patterns</category></item><item><title>Extending the World</title><link>http://blogs.msdn.com/wesdyer/archive/2007/03/09/extending-the-world.aspx</link><pubDate>Fri, 09 Mar 2007 14:06:29 GMT</pubDate><guid isPermaLink="false">91d46819-8472-40ad-a661-2c78acb4018c:1843300</guid><dc:creator>wesdyer</dc:creator><slash:comments>26</slash:comments><comments>http://blogs.msdn.com/wesdyer/comments/1843300.aspx</comments><wfw:commentRss>http://blogs.msdn.com/wesdyer/commentrss.aspx?PostID=1843300</wfw:commentRss><description>&lt;p&gt;When people think of C# 3.0 and Linq, they commonly think of queries and databases.&amp;nbsp; The phenomenal work of the &lt;a href="http://blogs.msdn.com/mattwar/"&gt;Linq&lt;/a&gt; &lt;a href="http://forums.microsoft.com/MSDN/Search/Search.aspx?words=keith+farmer&amp;amp;localechoice=9&amp;amp;SiteID=1&amp;amp;searchscope=forumscope&amp;amp;ForumID=123"&gt;to&lt;/a&gt; &lt;a href="http://blogs.madtechnology.net/blogs/chris/"&gt;SQL&lt;/a&gt; &lt;a href="http://blogs.msdn.com/jomo_fisher/"&gt;guys&lt;/a&gt; provides ample reason to think of it this way; nevertheless, C# 3.0 and Linq&amp;nbsp;are really much much more.&amp;nbsp; I have discussed a number of things that can be done with lambdas, expression trees, and queries&amp;nbsp;and will continue to do so but I want to pause and discuss a little gem that is often overlooked in C# 3.0.&amp;nbsp; This new language feature has fundamentally changed both the way that I work in C# and &lt;a href="http://antwrp.gsfc.nasa.gov/apod/ap971026.html"&gt;my view of the world&lt;/a&gt;.&amp;nbsp; I've been using it a lot without ever drawing attention explicitly to it.&amp;nbsp; At least &lt;a href="http://base4.net/Blog.aspx?ID=334"&gt;one reader&lt;/a&gt; noticed it and the possibilities it opens up and at least a couple of readers want an expanded version of it without even knowing it.&lt;/p&gt; &lt;p&gt;So what is the feature?&amp;nbsp; It's extension methods.&lt;/p&gt; &lt;p&gt;At first glance they don't look very special.&amp;nbsp; I mean really, all they are is one extra token in the definition of a static method inside of a static class.&lt;/p&gt; &lt;blockquote&gt; &lt;p&gt;&lt;font face="Courier New"&gt;static class Foo {&lt;/font&gt;&lt;/p&gt; &lt;p&gt;&lt;font face="Courier New"&gt;&amp;nbsp; public static Bar Baz(&lt;font color="#ff8000"&gt;this&lt;/font&gt; Qux Quux) { ...&lt;/font&gt;&lt;/p&gt;&lt;/blockquote&gt; &lt;p&gt;But as is usually the case, it's the semantics that are more interesting than the particular syntax.&lt;/p&gt; &lt;p&gt;The first argument of an extension method (the argument marked with this) is the implicit receiver of the method.&amp;nbsp; The extension method &lt;em&gt;appears&lt;/em&gt; to be an instance method on the receiver but it is not.&amp;nbsp; Therefore, it cannot access private or protected members of the receiver.&lt;/p&gt; &lt;p&gt;For example, let's say that I detested the fact that the framework doesn't have a ToInt method defined on string.&amp;nbsp; Now, I can just provide my own:&lt;/p&gt; &lt;blockquote&gt; &lt;p&gt;&lt;font face="Courier New"&gt;public static int ToInt(this string s)&lt;br&gt;{&lt;br&gt;&amp;nbsp; return int.Parse(s);&lt;br&gt;}&lt;/font&gt;&lt;/p&gt;&lt;/blockquote&gt; &lt;p&gt;And I can then call it as:&lt;/p&gt; &lt;blockquote&gt; &lt;p&gt;&lt;font face="Courier New"&gt;"5".ToInt()&lt;/font&gt;&lt;/p&gt;&lt;/blockquote&gt; &lt;p&gt;The compiler transforms the call into:&lt;/p&gt; &lt;blockquote&gt; &lt;p&gt;&lt;font face="Courier New"&gt;ToInt("5")&lt;/font&gt;&lt;/p&gt;&lt;/blockquote&gt; &lt;p&gt;Notice how it turns it outside out.&amp;nbsp; So if I have three extension methods A, B, and C&lt;/p&gt; &lt;blockquote&gt; &lt;p&gt;&lt;font face="Courier New"&gt;x.A().B().C()&lt;/font&gt;&lt;/p&gt;&lt;/blockquote&gt; &lt;p&gt;The calls get turned into&lt;/p&gt; &lt;blockquote&gt; &lt;p&gt;&lt;font face="Courier New"&gt;C(B(A(x)))&lt;/font&gt;&lt;/p&gt;&lt;/blockquote&gt; &lt;p&gt;While all of this explains how extension methods work, it doesn't explain why they are so cool.&lt;/p&gt; &lt;p&gt;A few months back, I was reading various online content related to C# 3.0.&amp;nbsp; I wanted to get a feel for what customers were feeling and incorporate it as much as possible into the product.&amp;nbsp; In the process, I came across an interesting post, &lt;a href="http://lukeplant.me.uk/blog.php?id=1107301645"&gt;Why learning Haskell/Python makes you a worse programmer&lt;/a&gt;.&amp;nbsp; The author argues that learning a language like Python or Haskell can make things more difficult for you if your day job is programming in a language like C#.&lt;/p&gt; &lt;p&gt;I sympathize with what the author has to say and have had to spend enough time programming in languages that I didn't like that I think that I understand the pain.&lt;/p&gt; &lt;p&gt;That said, I hope that the author (and others who feel like him) will be pleasantly surprised by C# 3.0.&amp;nbsp; For example, let's look at his example of painful programming:&lt;/p&gt; &lt;blockquote&gt; &lt;p&gt;"I have a list of Foo objects, each having a Description() method that returns a string. I need to concatenate all the non-empty descriptions, inserting newlines between them."&lt;/p&gt;&lt;/blockquote&gt; &lt;p&gt;In Python, he says that he would write:&lt;/p&gt; &lt;blockquote&gt; &lt;p&gt;&lt;font face="Courier New"&gt;"\n".join(foo.description() for foo in mylist if foo.description() != "")&lt;/font&gt;&lt;/p&gt;&lt;/blockquote&gt; &lt;p&gt;In Haskell, his solution looks like:&lt;/p&gt; &lt;blockquote&gt; &lt;p&gt;&lt;font face="Courier New"&gt;concat $ List.intersperse "\n" $ filter (/= "") $ map description mylist&lt;/font&gt;&lt;/p&gt;&lt;/blockquote&gt; &lt;p&gt;These both look like reasonable code and I rather like them.&amp;nbsp; Fortunately, you can express them in C# 3.0.&amp;nbsp; Here is the code that looks like the Python solution.&lt;/p&gt; &lt;blockquote&gt; &lt;p&gt;&lt;font face="Courier New"&gt;"\n".Join(from x in mylist where x.Description != "" select x.Description)&lt;/font&gt;&lt;/p&gt;&lt;/blockquote&gt; &lt;p&gt;And here is the code that is closer to his Haskell solution:&lt;/p&gt; &lt;blockquote&gt; &lt;p&gt;&lt;font face="Courier New"&gt;mylist.Where(x =&amp;gt; x.Description != "").Select(x =&amp;gt; x.Description).Intersperse("\n").Concat();&lt;/font&gt;&lt;/p&gt;&lt;/blockquote&gt; &lt;p&gt;At this point, some will protest that there is no Join instance method on string and there is no Intersperse defined on IEnumerable&amp;lt;T&amp;gt;.&amp;nbsp; And for that matter, how can you define a method on an interface in the first place?&amp;nbsp; Of course, extension methods are the answer to all of these questions.&lt;/p&gt; &lt;blockquote&gt; &lt;p&gt;&lt;font face="Courier New"&gt;public static string Join(this string s, IEnumerable&amp;lt;string&amp;gt; ss)&lt;br&gt;{&lt;br&gt;&amp;nbsp; return string.Join(s, ss.ToArray());&lt;br&gt;}&lt;/font&gt;&lt;/p&gt; &lt;p&gt;&lt;font face="Courier New"&gt;&lt;/font&gt;&lt;font face="Courier New"&gt;&lt;br&gt;public static IEnumerable&amp;lt;T&amp;gt; Intersperse&amp;lt;T&amp;gt;(this IEnumerable&amp;lt;T&amp;gt; sequence, T value)&lt;br&gt;{&lt;br&gt;&amp;nbsp; bool first = true;&lt;br&gt;&amp;nbsp; foreach (var item in sequence)&lt;br&gt;&amp;nbsp; {&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; if (first)&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; first = false;&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; else&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; yield return value;&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; yield return item;&lt;br&gt;&amp;nbsp; }&lt;br&gt;}&lt;/font&gt;&lt;/p&gt;&lt;/blockquote&gt; &lt;p&gt;It is as if these methods were defined on the receiver to begin with.&amp;nbsp; At this point the realization sets in: a whole new mode of development has been opened up.&lt;/p&gt; &lt;p&gt;Typically for a given problem, a programmer is accustomed to building up a solution until it finally meets the requirements.&amp;nbsp; Now, it is possible to extend the world to meet the solution instead of solely just building up until we get to it.&amp;nbsp; That library doesn't provide what you need, just extend the library to meet your needs.&lt;/p&gt; &lt;p&gt;I find myself switching between the two modes frequently: building up some functionality here and extending some there.&amp;nbsp; In fact, these days I find that I often start with extension methods and then when certain patterns begin to emerge then I factor those into classes.&lt;/p&gt; &lt;p&gt;It also makes some interesting styles of programming&amp;nbsp;easier.&amp;nbsp; I am sure it has some name, but since I don't know what it is I'll call it data interface programming.&amp;nbsp; First we declare an immutable interface that includes only data elements.&lt;/p&gt; &lt;blockquote&gt; &lt;p&gt;&lt;font face="Courier New"&gt;interface ICustomer&lt;br&gt;{&lt;br&gt;&amp;nbsp; string Name { get; }&lt;br&gt;&amp;nbsp; int ID { get; }&lt;br&gt;} &lt;/font&gt;&lt;/p&gt;&lt;/blockquote&gt; &lt;p&gt;Then, we declare an inaccessible implementation of ICustomer that allows customers to be created through a factory that only exposes the immutable version.&lt;/p&gt; &lt;blockquote&gt; &lt;p&gt;&lt;font face="Courier New"&gt;class Factory&lt;br&gt;{&lt;br&gt;&amp;nbsp; class Customer : ICustomer&lt;br&gt;&amp;nbsp; {&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; public string Name { get; set; }&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; public int ID { get; set; }&lt;br&gt;&amp;nbsp; } &lt;/font&gt; &lt;p&gt;&lt;font face="Courier New"&gt;&amp;nbsp; public static ICustomer CreateCustomer(int id, string name)&lt;br&gt;&amp;nbsp; {&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; return new Customer { ID = id, Name = name };&lt;br&gt;&amp;nbsp; }&lt;br&gt;}&lt;/font&gt;&lt;/p&gt;&lt;/blockquote&gt; &lt;p&gt;Then we can declare behavior through extension methods.&lt;/p&gt; &lt;blockquote&gt; &lt;p&gt;&lt;font face="Courier New"&gt;public static string GetAlias(this ICustomer customer)&lt;br&gt;{&lt;br&gt;&amp;nbsp; return customer.Name + customer.ID.ToString();&lt;br&gt;}&lt;/font&gt;&lt;/p&gt;&lt;/blockquote&gt; &lt;p&gt;And finally, we can use the behavior.&lt;/p&gt; &lt;blockquote&gt; &lt;p&gt;&lt;font face="Courier New"&gt;var customer = Factory.CreateCustomer(4, "wes");&lt;br&gt;Console.WriteLine(customer.GetAlias());&lt;/font&gt;&lt;/p&gt;&lt;/blockquote&gt; &lt;p&gt;All of this may seem like a round about way to declare an&amp;nbsp;immutable abstract base class with various derived classes.&amp;nbsp; But there is a fundamental difference, &lt;em&gt;the interface and behavior can change depending upon which extension methods are in scope&lt;/em&gt;.&amp;nbsp; So one part of the program or system can treat them one way and another can have an entirely different view of things.&lt;/p&gt; &lt;p&gt;Of course, what I really want to be able to do (and we don't do it yet) is something like:&lt;/p&gt; &lt;blockquote&gt; &lt;p&gt;&lt;font face="Courier New"&gt;var customer = new ICustomer { ID = 4, Name = "wes" };&lt;br&gt;Console.WriteLine(customer.GetAlias());&lt;/font&gt;&lt;/p&gt;&lt;/blockquote&gt; &lt;p&gt;And then I skip the whole Factory thing all together.&amp;nbsp; The customer is immutable and the definition of the type is short and sweet.&amp;nbsp; All of the work of done by the compiler which incidentally doesn't need the factory because it can name mangle the implementation class and provide customized constructors automatically.&amp;nbsp; But I digress, hopefully we can do something like that in the future.&lt;/p&gt; &lt;p&gt;Of course&amp;nbsp;extension methods don't make the traditional techniques inapplicable, they are still as useful as ever.&amp;nbsp; As with all design considerations, there are trade-offs involved.&amp;nbsp; Care must be taken to manage extension methods so that chaos doesn't ensue, but when they are used appropriately they are&amp;nbsp;fantastically useful.&lt;/p&gt; &lt;p&gt;As I have been writing C# code, I have accumulated a library of useful extension methods and I encourage you to do the same thing so that the ideas that you think roll naturally off of your fingertips.&lt;/p&gt;&lt;img src="http://blogs.msdn.com/aggbug.aspx?PostID=1843300" width="1" height="1"&gt;</description><category domain="http://blogs.msdn.com/wesdyer/archive/tags/C_2300_/default.aspx">C#</category></item><item><title>Immutability, Purity, and Referential Transparency</title><link>http://blogs.msdn.com/wesdyer/archive/2007/03/01/immutability-purity-and-referential-transparency.aspx</link><pubDate>Thu, 01 Mar 2007 10:44:12 GMT</pubDate><guid isPermaLink="false">91d46819-8472-40ad-a661-2c78acb4018c:1777705</guid><dc:creator>wesdyer</dc:creator><slash:comments>32</slash:comments><comments>http://blogs.msdn.com/wesdyer/comments/1777705.aspx</comments><wfw:commentRss>http://blogs.msdn.com/wesdyer/commentrss.aspx?PostID=1777705</wfw:commentRss><description>&lt;p&gt;&lt;/p&gt; &lt;p&gt;How often do you write code that just works?&amp;nbsp; It seems to happen so rarely&amp;nbsp;that I find myself suspicious if&amp;nbsp;code does just work.&amp;nbsp; When was the last time that you wrote a non-trivial program that had no compile errors&amp;nbsp;on the first try and then ran fine as well?&amp;nbsp; If it happened recently then congratulations.&amp;nbsp; If it hasn't then join the club.&amp;nbsp; Admittedly, most programmers don't just write a whole program and then submit it to a compiler and&amp;nbsp;a&amp;nbsp;test harness&amp;nbsp;to see if it works.&amp;nbsp; Typically it is built incrementally: a function here, a class there, testing all the time.&amp;nbsp; &lt;a href="http://en.wikipedia.org/wiki/REPL"&gt;Code-Compile-Test&lt;/a&gt;...rinse and repeat.  &lt;p&gt;I recently read a post where the author describes &lt;a href="http://www.haskell.org/haskellwiki/Why_Haskell_just_works"&gt;why Haskell programs just seem to work&lt;/a&gt;.&amp;nbsp; It got me thinking about my own experience in Haskell.&amp;nbsp; One of the most interesting things about Haskell is that many programmers don't use a&amp;nbsp;debugger (&lt;a href="http://haskell.org/haskellwiki/GHC/GHCi_debugger"&gt;GHCi does have one&lt;/a&gt;).&amp;nbsp; It seems that the impulse to break out the debugger to better understand code occurs&amp;nbsp;far less than in other languages.&amp;nbsp;  &lt;p&gt;Can you imagine working in C# without a debugger?&amp;nbsp; So why is it that many Haskell users seem to get along without a debugger? &lt;p&gt;&lt;strong&gt;A Tale of Two Sorts&lt;/strong&gt;  &lt;p&gt;Consider writing a function&amp;nbsp;that sorts an IEnumerable&amp;lt;T&amp;gt; using the &lt;a href="http://en.wikipedia.org/wiki/Quicksort"&gt;quicksort algorithm&lt;/a&gt;.&amp;nbsp; Here is one&amp;nbsp;possible implementation:  &lt;blockquote&gt; &lt;p&gt;&lt;font face="Courier New"&gt;static IEnumerable&amp;lt;T&amp;gt; QuickSort&amp;lt;T&amp;gt;(this IEnumerable&amp;lt;T&amp;gt; sequence) where T : IComparable&amp;lt;T&amp;gt;&lt;br&gt;{&lt;br&gt;&amp;nbsp; var array = sequence.ToArray();&lt;br&gt;&amp;nbsp; QuickSort(array, 0, array.Length - 1);&lt;br&gt;&amp;nbsp; return array;&lt;br&gt;} &lt;/font&gt; &lt;p&gt;&lt;font face="Courier New"&gt;static void QuickSort&amp;lt;T&amp;gt;(this T[] array, int start, int end) where T : IComparable&amp;lt;T&amp;gt;&lt;br&gt;{&lt;br&gt;&amp;nbsp; if (end - start &amp;lt; 1)&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; return;&lt;br&gt;&amp;nbsp; var pivot = array[start];&lt;br&gt;&amp;nbsp; var j = start;&lt;br&gt;&amp;nbsp; for (var i = start + 1; i &amp;lt;= end; ++i)&lt;br&gt;&amp;nbsp; {&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; if (array[i].CompareTo(pivot) &amp;lt; 0)&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; {&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; ++j;&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; var temp = array[j];&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; array[j] = array[i];&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; array[i] = temp;&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; }&lt;br&gt;&amp;nbsp; }&lt;br&gt;&amp;nbsp; array[start] = array[j];&lt;br&gt;&amp;nbsp; array[j] = pivot;&lt;br&gt;&amp;nbsp; QuickSort(array, start, j - 1);&lt;br&gt;&amp;nbsp; QuickSort(array, j + 1, end);&lt;br&gt;}&lt;/font&gt;&lt;/p&gt;&lt;/blockquote&gt; &lt;p&gt;Now imagine that ++j was in the wrong place (at the end of the block).&amp;nbsp; The output of sorting  &lt;blockquote&gt; &lt;p&gt;4, 3, 6, 9, 1, 0, 2, 7, 5, 8&lt;/p&gt;&lt;/blockquote&gt; &lt;p&gt;would be &lt;blockquote&gt; &lt;p&gt;4, 4, 4, 4, 4, 9, 6, 7, 7, 8&lt;/p&gt;&lt;/blockquote&gt; &lt;p&gt;Clearly this isn't right.&amp;nbsp; So after a quick scan of the code, most programmers would attach a debugger to see what is going on.  &lt;p&gt;The programmer might then step through the code until some state transition ends in a corrupt state.&amp;nbsp; Hopefully the programmer&amp;nbsp;understands the &lt;em&gt;intent&lt;/em&gt; of the code so that a fix can be issued to bring the implementation in line with the intent.  &lt;p&gt;Contrast the previous definition of quicksort with the following definition:  &lt;blockquote&gt; &lt;p&gt;&lt;font face="Courier New"&gt;static IEnumerable&amp;lt;T&amp;gt; QuickSort&amp;lt;T&amp;gt;(this IEnumerable&amp;lt;T&amp;gt; sequence) where T : IComparable&amp;lt;T&amp;gt;&lt;br&gt;{&lt;br&gt;&amp;nbsp; if (!sequence.Any())&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; return sequence;&lt;br&gt;&amp;nbsp; var pivot = sequence.First();&lt;br&gt;&amp;nbsp; var remaining = sequence.Skip(1);&lt;br&gt;&amp;nbsp;&amp;nbsp;return ((from x in remaining where x.CompareTo(pivot) &amp;lt; 0 select x).QuickSort())&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; .Concat(pivot)&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; .Concat((from x in remaining where x.CompareTo(pivot) &amp;gt;= 0 select x).QuickSort());&lt;br&gt;}&lt;/font&gt;&lt;/p&gt;&lt;/blockquote&gt; &lt;p&gt;What do you notice that is different besides the number of lines of code? &lt;p&gt;The first definition creates an array and then does in an place quicksort on the array, destructively updating the contents.&amp;nbsp; It creates several temporary values (i, j)&amp;nbsp;needed to store intermediate results.&amp;nbsp; If&amp;nbsp;a programmer&amp;nbsp;hasn't written the algorithm recently then chances are that the code&amp;nbsp;will contain at least an&amp;nbsp;one off by one error&amp;nbsp;or some other similar error.&amp;nbsp; I've seen too many people do poorly on whiteboards on similar&amp;nbsp;problems&amp;nbsp;(where incidentally there is no debugger, syntax highlighting, or intellisense) to believe that most people would just get it right the first time.  &lt;p&gt;The second definition &lt;em&gt;does not modify any data&lt;/em&gt;.&amp;nbsp; Sure it makes assignments but each of these assignments are to a newly introduced variable.&amp;nbsp; These variables are really just aliases for the expressions that are assigned to them because the expressions are side-effect free.&amp;nbsp; Furthermore, the second definition is essentially just a brief description of what the quicksort is rather than a step by&amp;nbsp;step description of how it is accomplished.  &lt;p&gt;At this point, some people will probably be thinking, "But isn't the first approach so much faster than the second approach?" &lt;p&gt;Maybe, maybe not.&amp;nbsp; Perhaps it doesn't even matter. &lt;p&gt;I think it is important to&amp;nbsp;use the following principle:&amp;nbsp; &lt;em&gt;Make it correct, make it clear, make it concise, make&amp;nbsp;it fast.&amp;nbsp; In that order.&lt;/em&gt;&amp;nbsp; &lt;p&gt;If I find that the code in question&amp;nbsp;is not performant enough given the user scenarios that we need to support or if the code is overly complex for the sake of eliminating side-effects then I consider adding state.&amp;nbsp; But note that if I wanted to introduce state to our quicksort, I could do it in two different ways: contained within the quicksort function or&amp;nbsp;exposed to the caller of quicksort.&amp;nbsp; This is somewhat analogous to calling either the first function or the second function in the first definition of quicksort.&amp;nbsp; If the state is exposed then quicksort could do an in-place sort on&amp;nbsp;the&amp;nbsp;collection passed to&amp;nbsp;the quicksort function.&amp;nbsp; Alternatively, quicksort could simply return a new&amp;nbsp;collection that is sorted and not update the original collection.&amp;nbsp; This leads to the second principle:  &lt;blockquote&gt; &lt;p&gt;&lt;em&gt;Write&amp;nbsp;side-effect free&amp;nbsp;code.&amp;nbsp; If&amp;nbsp;side-effects are required then confine&amp;nbsp;them to the smallest scope possible.&lt;/em&gt;&lt;/p&gt;&lt;/blockquote&gt; &lt;p&gt;Most programmers have been following this to some extent for years.&amp;nbsp; We all know that generally it is not a good idea to use &lt;a href="http://en.wikipedia.org/wiki/Global_variables"&gt;global variables&lt;/a&gt;.&amp;nbsp; This is basically the extreme of exposing&amp;nbsp;side-effects (the global scope).&amp;nbsp; Unfortunately, many of the programmers who don't use global variables&amp;nbsp;don't realize that the same principles apply to fields, properties, parameters, and variables&amp;nbsp;on a more limited scale: don't mutate them unless you have a good reason.&amp;nbsp; &lt;p&gt;&lt;strong&gt;A Little Story about State&lt;/strong&gt;  &lt;p&gt;Some time ago,&amp;nbsp;I wrote &lt;a href="http://blogs.msdn.com/wesdyer/archive/2006/01/13/saving-the-state-of-enumerators.aspx"&gt;a post&lt;/a&gt; about a way to save the state of an IEnumerator&amp;lt;T&amp;gt;.&amp;nbsp; What I didn't tell is the story behind the post.  &lt;p&gt;I was writing&amp;nbsp;a managed lexer and parser generator.&amp;nbsp; The system is pretty&amp;nbsp;neat and includes things like &lt;a href="http://en.wikipedia.org/wiki/GLR_parser"&gt;GLR parsing&lt;/a&gt;, automatic inference of the &lt;a href="http://en.wikipedia.org/wiki/Abstract_syntax_tree"&gt;AST&lt;/a&gt; types, &lt;a href="http://lambda-the-ultimate.org/node/1018"&gt;automatic error recovery&lt;/a&gt;, and whole slew of other features.&amp;nbsp; The parser takes&amp;nbsp;an IEnumerable&amp;lt;IToken&amp;gt; in order to decouple the lexer from the parser.&amp;nbsp; However, for many of the features of the parser, it needs a way to save the state the of the underlying token stream and possibly restore it at a later time after more of the stream has been consumed.  &lt;p&gt;Originally, I wrote a MarkableEnumerator&amp;lt;T&amp;gt; which wrapped an IEnumerator&amp;lt;T&amp;gt; and consumed the input.&amp;nbsp; Clients could request a mark which they could then restore at a later point.&amp;nbsp; If they did this then the MarkableEnumerator&amp;lt;T&amp;gt; would continue at the restored point when MoveNext was called again.&amp;nbsp; This little piece of software (about 100 lines of code)&amp;nbsp;caused &lt;a href="http://blogs.msdn.com/cyrusn/"&gt;Cyrus&lt;/a&gt; and&amp;nbsp;me lots of trouble.&amp;nbsp; It was super complicated because it was heavily optimized to keep its internal storage as small as possible while preserving requested past state (and possibly restoring it).&amp;nbsp; It used a cyclical buffer and a number of opaque handles.&amp;nbsp; One of the worst problems is that it was a somewhat leaky abstraction since the complexity leaked into the code consuming it.  &lt;p&gt;When the code was first introduced it was reasonably contained but over time its inherent complexity began to pervade the whole parser.&amp;nbsp; Eventually, it was hard to make improvements to the parser without breaking the invariants of the MarkableEnumerator.&amp;nbsp; It was an absolute horror.&amp;nbsp; I remember one night&amp;nbsp;well past midnight, Cyrus and I were talking about how much we hated the thing, but&amp;nbsp;we needed&amp;nbsp;it to provide&amp;nbsp;good performance.  &lt;p&gt;Then it occurred to us that we could replace the whole mess of opaque handles, circular buffers, mark and release code, and MarkableEnumerators within MarkableEnumerators&amp;nbsp;with just a linked list that wrapped the enumerator.&amp;nbsp; If someone wanted to save the state of the enumerator and resume it&amp;nbsp;then all they need to do is keep a reference to the desired node.&amp;nbsp; To all of the clients, it&amp;nbsp;looked just like an immutable&amp;nbsp;linked list.&amp;nbsp; That is it.&amp;nbsp; So much simpler and guess what?&amp;nbsp; It was almost as fast.&amp;nbsp; But even more importantly, because of its simplicity we were able to make even more important code faster.&amp;nbsp; Our development time for new features rocketed again.  &lt;p&gt;There are several lessons from this story, but one of them is perhaps the most important considering our current discussion.&amp;nbsp; Reducing the&amp;nbsp;number and scope&amp;nbsp;of side-effects&amp;nbsp;simplifies the code. &lt;p&gt;&lt;strong&gt;Immutable Binary Trees&lt;/strong&gt; &lt;p&gt;Mutation often seems to just cause problems.  &lt;p&gt;&lt;img src="http://www.scienceclarified.com/images/uesc_07_img0388.jpg"&gt;&lt;/p&gt; &lt;p&gt;Suppose that we want to&amp;nbsp;create a BinaryTree class.&amp;nbsp; One straightforward&amp;nbsp;implementation is  &lt;blockquote&gt; &lt;p&gt;&lt;font face="Courier New"&gt;class BinaryTree&amp;lt;T&amp;gt;&lt;br&gt;{&lt;br&gt;&amp;nbsp; public T Value&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; { get; set; } // yes, we have autoimplemented&lt;br&gt;&amp;nbsp; public BinaryTree&amp;lt;T&amp;gt; Parent { get; set; } // properties in case you haven't&lt;/font&gt;&lt;font face="Courier New"&gt;&lt;br&gt;&amp;nbsp; public BinaryTree&amp;lt;T&amp;gt; Left&amp;nbsp;&amp;nbsp; { get; set; } // heard&lt;br&gt;&amp;nbsp; public BinaryTree&amp;lt;T&amp;gt; Right&amp;nbsp; { get; set; }&lt;br&gt;}&lt;/font&gt;&lt;/p&gt;&lt;/blockquote&gt; &lt;p&gt;I don't&amp;nbsp;like it very much.&amp;nbsp; Those sets&amp;nbsp;give me an uneasy feeling.&amp;nbsp; Of course it depends on how the&amp;nbsp;objects are used, but suppose that we intend to use the binary tree&amp;nbsp;in a multithreaded environment.&amp;nbsp; If someone changes&amp;nbsp;any of the members of a node there is a chance that some other thread&amp;nbsp;already has a reference to a node in the tree and will then have a tree in an inconsistent state.&amp;nbsp; Yes, we could&amp;nbsp;use a lock to fix the problem but I tend to like a different approach to this problem.&amp;nbsp;  &lt;blockquote&gt; &lt;p&gt;&lt;font face="Courier New"&gt;class BinaryTree&amp;lt;T&amp;gt;&lt;br&gt;{&lt;br&gt;&amp;nbsp; T value;&lt;br&gt;&amp;nbsp; BinaryTree&amp;lt;T&amp;gt; left;&lt;br&gt;&amp;nbsp; BinaryTree&amp;lt;T&amp;gt; right; &lt;/font&gt; &lt;p&gt;&lt;font face="Courier New"&gt;&amp;nbsp; public BinaryTree(T value, BinaryTree&amp;lt;T&amp;gt; left, BinaryTree&amp;lt;T&amp;gt; right)&lt;br&gt;&amp;nbsp; {&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; this.value = value;&lt;br&gt;&amp;nbsp; &amp;nbsp; this.left = left;&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; this.right = right;&lt;br&gt;&amp;nbsp; } &lt;/font&gt; &lt;p&gt;&lt;font face="Courier New"&gt;&amp;nbsp; public T Value { get { return value; } }&lt;br&gt;&amp;nbsp; public BinaryTree&amp;lt;T&amp;gt; Left { get { return left; } }&lt;br&gt;&amp;nbsp; public BinaryTree&amp;lt;T&amp;gt; Right { get { return right; } }&lt;br&gt;}&lt;/font&gt;&lt;/p&gt;&lt;/blockquote&gt; &lt;p&gt;This is essentially the same as the first BinaryTree except that it is immutable (no sets and no methods causing mutation).&amp;nbsp; This requires that we have a constructor that takes in the appropriate values.&amp;nbsp; Also, you may have noticed that there is no Parent property.&amp;nbsp; The reason is that if the node is immutable then it is hard to know what the parent is at the time of creation.&amp;nbsp; With an immutable tree, you generally can either create parents before children or children before parents.&amp;nbsp; I prefer the later (despite the biological conundrum posed by this).&amp;nbsp; Note that this doesn't mean that we can't know what the parent of a given node is.&amp;nbsp; Indeed we can, but we need to introduce a new concept before addressing this.&lt;/p&gt; &lt;p&gt;Nodes can really be parented by n nodes.&amp;nbsp; Since any node can be constructed with a given node as either the left or the right child.&amp;nbsp; But given a tree (a root), we can enforce (assuming that we don't want DAGs)&amp;nbsp;that a node has at most one parent.&amp;nbsp; We will call this a BinaryTreeVersion.&lt;/p&gt; &lt;blockquote&gt; &lt;p&gt;&lt;font face="Courier New"&gt;class BinaryTreeVersion&amp;lt;T&amp;gt;&lt;br&gt;{&lt;br&gt;&amp;nbsp; BinaryTree&amp;lt;T&amp;gt; tree;&lt;br&gt;&amp;nbsp; Dictionary&amp;lt;BinaryTree&amp;lt;T&amp;gt;, BinaryTree&amp;lt;T&amp;gt;&amp;gt; parentMap; &lt;/font&gt; &lt;p&gt;&lt;font face="Courier New"&gt;&amp;nbsp; public BinaryTreeVersion(BinaryTree&amp;lt;T&amp;gt; tree)&lt;br&gt;&amp;nbsp; {&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; this.tree = tree;&lt;br&gt;&amp;nbsp; } &lt;/font&gt; &lt;p&gt;&lt;font face="Courier New"&gt;&amp;nbsp; public BinaryTree&amp;lt;T&amp;gt; Tree { get { return tree; } }&lt;br&gt;&amp;nbsp; public BinaryTree&amp;lt;T&amp;gt; GetParentOf(BinaryTree&amp;lt;T&amp;gt; node)&lt;br&gt;&amp;nbsp; {&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; if (parentMap == null)&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; {&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; parentMap = new Dictionary&amp;lt;BinaryTree&amp;lt;T&amp;gt;, BinaryTree&amp;lt;T&amp;gt;&amp;gt;();&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; FillParentMap(tree, null);&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;}&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; return parentMap[node];&lt;br&gt;&amp;nbsp; } &lt;/font&gt; &lt;p&gt;&lt;font face="Courier New"&gt;&amp;nbsp; void FillParentMap(BinaryTree&amp;lt;T&amp;gt; tree, BinaryTree&amp;lt;T&amp;gt; parent)&lt;br&gt;&amp;nbsp; {&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; if (tree == null)&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; return;&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; parentMap.Add(tree, parent);&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; FillParentMap(tree.Left, tree);&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; FillParentMap(tree.Right, tree);&lt;br&gt;&amp;nbsp; } &lt;/font&gt;&lt;font face="Courier New"&gt;&lt;br&gt;}&lt;/font&gt;&lt;/p&gt;&lt;/blockquote&gt; &lt;p&gt;The parent operation is exposed on the BinaryTreeVersion.&amp;nbsp; The parent of a given node is stored in the parentMap which is filled with node-parent pairs.&amp;nbsp; So now we have a tree that is immutable and the ability to access a node's parent.&lt;/p&gt; &lt;p&gt;But we can take it one step further, we can create functions that will modify the tree.&amp;nbsp; Note that we will not actually modify the tree but&amp;nbsp;we will return a new BinaryTreeVersion.&amp;nbsp; The ChangeNodeValues function&amp;nbsp;takes two functions:&amp;nbsp; a function that determines whether to modify the given node's value and a function to compute the node's new value (there are better ways to do this for specific modifications and yes I could have used a visitor).&lt;/p&gt; &lt;blockquote&gt; &lt;p&gt;&lt;font face="Courier New"&gt;class BinaryTreeVersion&amp;lt;T&amp;gt;&lt;br&gt;{&lt;br&gt;&lt;/font&gt; &lt;p&gt;&lt;font face="Courier New"&gt;&amp;nbsp;...&amp;nbsp;&lt;/font&gt;  &lt;p&gt;&lt;font face="Courier New"&gt;&amp;nbsp; public BinaryTreeVersion&amp;lt;T&amp;gt; ChangeNodeValues(Func&amp;lt;BinaryTree&amp;lt;T&amp;gt;, bool&amp;gt; predicate, Func&amp;lt;BinaryTree&amp;lt;T&amp;gt;, T&amp;gt; newValue)&lt;br&gt;&amp;nbsp; {&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; return new BinaryTreeVersion&amp;lt;T&amp;gt;(ChangeNodeValue(tree, predicate, newValue));&lt;br&gt;&amp;nbsp; } &lt;/font&gt; &lt;p&gt;&lt;font face="Courier New"&gt;&amp;nbsp; BinaryTree&amp;lt;T&amp;gt; ChangeNodeValue(BinaryTree&amp;lt;T&amp;gt; node, Func&amp;lt;BinaryTree&amp;lt;T&amp;gt;, bool&amp;gt; predicate, Func&amp;lt;BinaryTree&amp;lt;T&amp;gt;, T&amp;gt; newValue)&lt;br&gt;&amp;nbsp; {&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; if (node == null)&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; return null;&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; var left = ChangeNodeValue(node.Left, predicate, newValue);&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; var right = ChangeNodeValue(node.Right, predicate, newValue);&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; var value = predicate(node) ? newValue(node) : node.Value;&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; if (value.Equals(node.Value) &amp;amp;&amp;amp; left == node.Left &amp;amp;&amp;amp; right == node.Right)&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; return node;&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; return new BinaryTree&amp;lt;T&amp;gt;(value, left, right);&lt;br&gt;&amp;nbsp; }&lt;br&gt;}&lt;/font&gt;&lt;/p&gt;&lt;/blockquote&gt; &lt;p&gt;The neat thing is that since we use immutable trees, we can share subtrees that are not changed.&amp;nbsp; Even so, if another thread has a reference to the first BinaryTreeVersion or a node in the first tree then things will just work because we are mucking around with the data.&lt;/p&gt; &lt;p&gt;&lt;strong&gt;The Benefits of Purity&lt;/strong&gt;&lt;/p&gt; &lt;p&gt;One of the most painful things in software development is integrating two or more&amp;nbsp;things (objects, assemblies, functions, ...) together.&amp;nbsp; Invariably something will go wrong and a programmer that worked on one or the other&amp;nbsp;things in question&amp;nbsp;will protest, "It worked on my machine!"&amp;nbsp; Yes, indeed it probably did and it probably even works by itself but when put together with other things&amp;nbsp;it doesn't play so nice.&lt;/p&gt; &lt;p&gt;One way to increase the reliability of a unit&amp;nbsp;is to eliminate the side-effects.&amp;nbsp; This makes composing and integrating&amp;nbsp;units together much easier and more robust.&amp;nbsp; Since they are side-effect free, they always work the same no matter the environment.&amp;nbsp; This is called &lt;a href="http://en.wikipedia.org/wiki/Referential_transparency"&gt;referential transparency&lt;/a&gt;.&lt;/p&gt; &lt;p&gt;Conversely, things that are side-effect free are also easier to divide.&amp;nbsp; For a good example of this take a look at PLinq which farms out querying work to the available threads.&amp;nbsp; It divides up the work and then integrates the results: map-reduce.&lt;/p&gt; &lt;p&gt;But that is a discussion for another day...&lt;/p&gt;&lt;img src="http://blogs.msdn.com/aggbug.aspx?PostID=1777705" width="1" height="1"&gt;</description><category domain="http://blogs.msdn.com/wesdyer/archive/tags/C_2300_/default.aspx">C#</category><category domain="http://blogs.msdn.com/wesdyer/archive/tags/Functional+Programming/default.aspx">Functional Programming</category></item><item><title>Linq to ASCII Art</title><link>http://blogs.msdn.com/wesdyer/archive/2007/02/23/linq-to-ascii-art.aspx</link><pubDate>Fri, 23 Feb 2007 09:02:00 GMT</pubDate><guid isPermaLink="false">91d46819-8472-40ad-a661-2c78acb4018c:1745602</guid><dc:creator>wesdyer</dc:creator><slash:comments>40</slash:comments><comments>http://blogs.msdn.com/wesdyer/comments/1745602.aspx</comments><wfw:commentRss>http://blogs.msdn.com/wesdyer/commentrss.aspx?PostID=1745602</wfw:commentRss><description>&lt;p&gt;Last night I was searching for an audio version of &lt;em&gt;&lt;a href="http://www.amazon.com/Hackers-Painters-Big-Ideas-Computer/dp/0596006624"&gt;Painters and Hackers&lt;/a&gt;&lt;/em&gt; by &lt;a href="http://www.paulgraham.com/"&gt;Paul Graham&lt;/a&gt;.&amp;nbsp; Pretty soon I had completely forgotten about the book and found myself reading the &lt;a href="http://en.wikipedia.org/wiki/Main_Page"&gt;Wikipedia&lt;/a&gt; article about &lt;a href="http://en.wikipedia.org/wiki/Hacker"&gt;Hackers&lt;/a&gt;.&amp;nbsp; Isn't Internet search great?&lt;/p&gt; &lt;p&gt;Of all of the things in the article, the one thing that captured my attention was the &lt;a href="http://en.wikipedia.org/wiki/Image:Lamoascii.png"&gt;ASCII picture&lt;/a&gt; of &lt;a href="http://en.wikipedia.org/wiki/Adrian_Lamo"&gt;Adrian Lamo&lt;/a&gt;.&amp;nbsp; I immediately thought, "How cool is that!?"&amp;nbsp; So instead of&amp;nbsp;popping off my current stack frame and returning to searching for &lt;em&gt;Painters and Hackers&lt;/em&gt;, I began thinking about how to create such a picture.&amp;nbsp; I certainly did not want to create it by hand.&amp;nbsp; I didn't even want to pick which characters or colors would be printed to the screen.&amp;nbsp; So accordingly, I began thinking of writing a program to do it for me.&lt;/p&gt; &lt;p&gt;I grabbed the latest bits and began writing code.&amp;nbsp; A few hours later, I had a working program with a few bells and whistles too.&lt;/p&gt; &lt;p&gt;&lt;strong&gt;ASCII Art&lt;/strong&gt;&lt;/p&gt; &lt;p&gt;Here is an example of converting &lt;a href="http://en.wikipedia.org/wiki/Gandalf"&gt;Gandalf&lt;/a&gt; from pixels to &lt;a href="http://www.asciitable.com/"&gt;ASCII&lt;/a&gt;:&lt;/p&gt; &lt;p&gt;&lt;a href="http://blogs.msdn.com/blogfiles/wesdyer/WindowsLiveWriter/LinqtoASCIIArt_12D96/image036.png" atomicselection="true"&gt;&lt;img style="border-top-width: 0px; border-left-width: 0px; border-bottom-width: 0px; border-right-width: 0px" height="424" src="http://blogs.msdn.com/blogfiles/wesdyer/WindowsLiveWriter/LinqtoASCIIArt_12D96/image0_thumb28.png" width="334" border="0"&gt;&lt;/a&gt;&lt;a href="http://blogs.msdn.com/blogfiles/wesdyer/WindowsLiveWriter/LinqtoASCIIArt_12D96/image%7B0%7D%5B3%5D.png" atomicselection="true"&gt;&lt;img style="border-top-width: 0px; border-left-width: 0px; border-bottom-width: 0px; border-right-width: 0px" height="424" src="http://blogs.msdn.com/blogfiles/wesdyer/WindowsLiveWriter/LinqtoASCIIArt_12D96/image%7B0%7D_thumb%5B1%5D.png" width="350" border="0"&gt; &lt;/a&gt;&lt;/p&gt; &lt;p&gt;&lt;strong&gt;How to Convert and Image to ASCII Art&lt;/strong&gt;&lt;/p&gt; &lt;p&gt;The process works like this:&lt;/p&gt; &lt;p&gt;Determine how big of an area will be used for displaying the ASCII art.&amp;nbsp; By default, the width of the image will be the width of the console's buffer and the height will be computed so as the preserve the ratio of width to height from the original image.&lt;/p&gt; &lt;p&gt;Now divide the original image into as many rectangles as will be used to display the ASCII.&amp;nbsp; For each rectangle in the original picture determine its grayscale value by averaging the&amp;nbsp;grayscale values&amp;nbsp;of each pixel.&amp;nbsp; The grayscale value of a pixel is:&lt;/p&gt; &lt;blockquote&gt; &lt;p&gt;&lt;font face="Courier New"&gt;GrayScale = .3 * Red + .59 * Green + .11 * Blue&lt;/font&gt;&lt;/p&gt;&lt;/blockquote&gt; &lt;p&gt;We then increase the contrast of each region by some amount (d is the luminosity of a region, contrast is any double but usually around 1.5):&lt;/p&gt; &lt;blockquote&gt; &lt;p&gt;&lt;font face="Courier New"&gt;public static double Contrast(this double d, double contrast)&lt;br&gt;{&lt;br&gt;&amp;nbsp; return (((d - .5) * contrast) + .5).Bound(0, 1);&lt;br&gt;}&lt;/font&gt;&lt;/p&gt;&lt;/blockquote&gt; &lt;p&gt;Finally, for each region in the ASCII art we choose from an array of possible ASCII figures (sorted) by the grayscale value for that region.&amp;nbsp; The ASCII figure with the closest luminosity is picked.&lt;/p&gt; &lt;p&gt;The only point that I haven't covered is how the array of ASCII figures was generated.&amp;nbsp; I could have done this by hand if I wanted to, but I didn't want to.&amp;nbsp; Instead, I generate the grayscale figures each time.&amp;nbsp; Each figure consists of a character and a console color either ConsoleColor.DarkGray, ConsoleColor.Gray, or ConsoleColor.White.&amp;nbsp; The characters are one of the alphanumeric characters or&amp;nbsp;the special symbols (things like %, $, @, ...).&amp;nbsp; The program generates all of the combinations and then measures their grayscale value by drawing them to a hidden bitmap and then computing their average grayscale value.&amp;nbsp; The figures are sorted by this value and a final grayscale is built.&lt;/p&gt; &lt;p&gt;&lt;strong&gt;A Few&amp;nbsp;Snippets&lt;/strong&gt;&lt;/p&gt; &lt;p&gt;If you take a look at the source, you will notice that it is written rather different than most C# code.&amp;nbsp; A lot of the code resides in extension methods and there are a number of lambdas and queries.&amp;nbsp; In fact, loops are kind of rare in the code.&amp;nbsp; For example, here is a function that returns all of the pixels in a rectangular region of a bitmap.&lt;/p&gt; &lt;blockquote&gt; &lt;p&gt;&lt;font face="Courier New"&gt;public static IEnumerable&amp;lt;Color&amp;gt; GetPixels(this Bitmap image, Rectangle rect)&lt;br&gt;{&lt;br&gt;&amp;nbsp; return from y in rect.Top.To(rect.Bottom)&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &amp;nbsp; from x in rect.Left.To(rect.Right)&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; select image.GetPixel(x, y);&lt;br&gt;}&lt;/font&gt;&lt;/p&gt;&lt;/blockquote&gt; &lt;p&gt;The To function is a helpful little function that I wrote.  &lt;blockquote&gt; &lt;p&gt;&lt;font face="Courier New"&gt;public static IEnumerable&amp;lt;int&amp;gt; To(this int start, int end)&lt;br&gt;{&lt;br&gt;&amp;nbsp; var diff = end - start &amp;gt; 0 ? 1 : -1;&lt;br&gt;&amp;nbsp; for (var current = start; current != end; current += diff)&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; yield return current;&lt;br&gt;}&lt;/font&gt;&lt;/p&gt;&lt;/blockquote&gt; &lt;p&gt;Of course, I also could have written Iterate and then written To in terms of that.  &lt;blockquote&gt; &lt;p&gt;&lt;font face="Courier New"&gt;public static IEnumerable&amp;lt;T&amp;gt; Iterate&amp;lt;T&amp;gt;(T initialValue, Func&amp;lt;T, bool&amp;gt; predicate, Func&amp;lt;T, T&amp;gt; next)&lt;br&gt;{&lt;br&gt;&amp;nbsp; for (var current = initialValue; predicate(current); current = next(current))&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; yield return current;&lt;br&gt;}&lt;/font&gt;&lt;/p&gt; &lt;p&gt;&lt;font face="Courier New"&gt;public static IEnumerable&amp;lt;int&amp;gt; To(this int start, int end)&lt;br&gt;{&lt;br&gt;&amp;nbsp; var diff = end - start &amp;gt; 0 ? 1 : -1;&lt;br&gt;&amp;nbsp; return Iterate(start, x =&amp;gt; x != end, x =&amp;gt; x + diff);&lt;br&gt;}&lt;/font&gt;&lt;/p&gt;&lt;/blockquote&gt; &lt;p&gt;Another interesting part is setting up the display and then restoring the original display properties of the console.  &lt;blockquote&gt; &lt;p&gt;&lt;font face="Courier New"&gt;using (SetupConsole())&lt;/font&gt;  &lt;p&gt;&lt;font face="Courier New"&gt;&amp;nbsp; ...&lt;/font&gt; &lt;/p&gt;&lt;/blockquote&gt; &lt;p&gt;Where SetupConsole is defined as:  &lt;blockquote&gt; &lt;p&gt;&lt;font face="Courier New"&gt;&lt;/font&gt;&lt;/p&gt; &lt;p&gt;&lt;font face="Courier New"&gt;static ActionDisposable SetupConsole()&lt;br&gt;{&lt;br&gt;&amp;nbsp; var originalBackgroundColor = Console.BackgroundColor;&lt;br&gt;&amp;nbsp; var originalForegroundColor = Console.ForegroundColor;&lt;br&gt;&amp;nbsp; return new ActionDisposable(() =&amp;gt;&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; {&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; Console.BackgroundColor = originalBackgroundColor;&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; Console.ForegroundColor = originalForegroundColor;&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; });&lt;br&gt;}&lt;/font&gt;&lt;/p&gt;&lt;/blockquote&gt; &lt;p&gt;Notice that the original state of the console is captured only in the SetupConsole method and does not clutter the rest of the code.&amp;nbsp; The&amp;nbsp;closure&amp;nbsp;that is&amp;nbsp;created contains all of the necessary information to restore the console to its original state.&amp;nbsp; This way we hide data &lt;em&gt;even from private members of the same class&lt;/em&gt;.&amp;nbsp; If they don't need to know, then they don't need to know.&amp;nbsp; Instead only a means for restoring the original state is provided.  &lt;p&gt;I'm sure that the program can be improved a lot.&amp;nbsp; So if you have any comments, suggestions, or bugs then just post a comment.&amp;nbsp; Enjoy!  &lt;p&gt;&lt;strong&gt;Update:&lt;/strong&gt;  &lt;p&gt;I took the comments as well as some of my own ideas and improved the ASCII art generator.&amp;nbsp; I also modified the &lt;em&gt;How to Convert an Image to ASCII Art &lt;/em&gt;section to reflect some changes.&amp;nbsp; Thank you to everyone that contributed.  &lt;p&gt;&lt;strong&gt;Download the Source&lt;/strong&gt;&lt;/p&gt; &lt;p&gt;&lt;a href="http://www.box.net/public/10oy0aodrk"&gt;&lt;img height="24" alt="File icon" src="http://www.box.net/thumbs/24x24/default_file.gif" width="24" align="absMiddle" border="0"&gt;AsciiPictureSource.zip&lt;/a&gt;&lt;/p&gt; &lt;p&gt;&lt;a href="http://www.box.net/public/8ofyrvmzho"&gt;&lt;img height="24" alt="File icon" src="http://www.box.net/thumbs/24x24/default_file.gif" width="24" align="absMiddle" border="0"&gt;AsciiPictureSourcev1.1.zip&lt;/a&gt;&lt;/p&gt;&lt;img src="http://blogs.msdn.com/aggbug.aspx?PostID=1745602" width="1" height="1"&gt;</description><category domain="http://blogs.msdn.com/wesdyer/archive/tags/Programming/default.aspx">Programming</category><category domain="http://blogs.msdn.com/wesdyer/archive/tags/C_2300_/default.aspx">C#</category></item><item><title>The Virtues of Laziness</title><link>http://blogs.msdn.com/wesdyer/archive/2007/02/13/the-virtues-of-laziness.aspx</link><pubDate>Wed, 14 Feb 2007 00:11:57 GMT</pubDate><guid isPermaLink="false">91d46819-8472-40ad-a661-2c78acb4018c:1671293</guid><dc:creator>wesdyer</dc:creator><slash:comments>22</slash:comments><comments>http://blogs.msdn.com/wesdyer/comments/1671293.aspx</comments><wfw:commentRss>http://blogs.msdn.com/wesdyer/commentrss.aspx?PostID=1671293</wfw:commentRss><description>&lt;p&gt;It seems that I riled some people up with my blog post yesterday.&amp;nbsp; After some thought, I think the primary reason that there was some backlash is because some people feel that I violated one of the sacred principles of FP:&amp;nbsp; lists are *the* data structure.&amp;nbsp; Well, let me set the matter straight.&amp;nbsp; I love lists.&amp;nbsp; Especially the singlely linked immutable kind that are found in many functional languages.&amp;nbsp; Furthermore, Microsoft is not trying to launch some massive marketing campaign to sell IEnumerable&amp;lt;T&amp;gt; as the *new* list.&amp;nbsp; So to be clear, I talked about IEnumerable&amp;lt;T&amp;gt; yesterday because people who have used functional languages will wonder where are the lists in C# 3.0.&amp;nbsp; IEnumerable&amp;lt;T&amp;gt; is not the same as a&amp;nbsp;list, but there are many similarities between IEnumerable&amp;lt;T&amp;gt; and&amp;nbsp;lazy lists&amp;nbsp;that I pointed out yesterday when I showed they are isomorphic by describing the bijective mapping between them.&lt;/p&gt; &lt;p&gt;Furthermore, it is the case that some data structures are generally better than others.&amp;nbsp; But there are tradeoffs between using the various data structures.&amp;nbsp;&amp;nbsp;Also, *not* all of the tradeoffs are captured by looking exclusively at their time complexity for some operation.&amp;nbsp; There is of course the space complexity and there is the complexity of implementation itself.&amp;nbsp; And don't forget that often they have different characteristics for different operations.&amp;nbsp; The key point here is that a given problem will have a number of constraints and each of the competing designs has a number of trade-offs.&amp;nbsp; As an interviewer, when I&amp;nbsp;notice a candidate is not aware of the trade-offs that he is making then I start to worry that they were not considered at all.&amp;nbsp; Furthermore, when I notice that a candidate seems to favor one data structure to the exclusion of others, I start to wonder how many tools are in the toolbox.&amp;nbsp; But after observing this behavior many times, I am convinced that it often is not the coding problem that is driving usage of some data structure&amp;nbsp;but the mode of thinking that the candidate employs.&lt;/p&gt; &lt;p&gt;One more thing before I continue on.&amp;nbsp; At least one reader wondered why I said the following:&lt;/p&gt; &lt;blockquote&gt; &lt;p&gt;"Where most programmers who are accustomed to imperative style would naturally use an array, &lt;strong&gt;a&amp;nbsp;variable&lt;/strong&gt;, or a mutable object, a functional programmer will often use a list."&lt;/p&gt;&lt;/blockquote&gt; &lt;p&gt;Yes, I meant to say exactly what I said.&amp;nbsp; In fact, when I wrote it, I paused before deciding to include it because I thought it might be misunderstood.&amp;nbsp; When I first read SICP, the most mind bending and rewarding topic was at the end of chapter 3.&amp;nbsp; The section on streams.&amp;nbsp; One of the motivations that was given for using a stream (infinite list) was that variables that change their value over time cause problems.&amp;nbsp; One way to address this was to have streams represent the state of the variable over time where each element of the stream represents a state of the variable at some point in time.&lt;/p&gt; &lt;p&gt;So without further ado, let's take a look at &lt;a href="http://en.wikipedia.org/wiki/Stream_%28computer%29"&gt;streams&lt;/a&gt;...&lt;/p&gt; &lt;p&gt;What we want is an infinite list.&amp;nbsp; The problem is that infinite list can never actually be fully realized because of&amp;nbsp;their infinite nature.&amp;nbsp; So if we attempt to realize an infinite list either the computer will enter an infinite loop or it will run out of resources (stack overflow, out of memory, etc.).&lt;/p&gt; &lt;p&gt;We can overcome this problem by having lazy lists.&amp;nbsp; Lists where the next element in the list is not realized until it is needed.&amp;nbsp; Yesterday, I presented one such lazy list which uses an enumerator to realize the next element.&amp;nbsp; Today, I present another which has a more intriguing definition.&lt;/p&gt; &lt;blockquote&gt; &lt;p&gt;&lt;font face="Courier New"&gt;class Stream&amp;lt;T&amp;gt; : IList&amp;lt;T&amp;gt;&lt;br&gt;{&lt;br&gt;&amp;nbsp; Func&amp;lt;IList&amp;lt;T&amp;gt;&amp;gt; next;&lt;br&gt;&amp;nbsp; T value; &lt;/font&gt; &lt;p&gt;&lt;font face="Courier New"&gt;&amp;nbsp; public Stream(T value, Func&amp;lt;IList&amp;lt;T&amp;gt;&amp;gt; next)&lt;br&gt;&amp;nbsp; {&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; this.value = value;&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; this.next = next;&lt;br&gt;&amp;nbsp; } &lt;/font&gt; &lt;p&gt;&lt;font face="Courier New"&gt;&amp;nbsp; public IList&amp;lt;T&amp;gt; Next { get { return next(); } }&lt;br&gt;&amp;nbsp; public T Value { get { return value; } }&lt;br&gt;}&lt;/font&gt;&lt;/p&gt;&lt;/blockquote&gt; &lt;p&gt;This lazy list is very similar to a normal list.&amp;nbsp; The only difference is that instead of taking a list as the value of the next node in the list, it takes a function which will evaluate to the next node in the list.&amp;nbsp; But this difference is critical.&lt;/p&gt; &lt;p&gt;The first difference can easily be seen by imaging a list type, ErrorList, that when constructed throws an exception.&lt;/p&gt; &lt;blockquote&gt; &lt;p&gt;&lt;font face="Courier New"&gt;class ErrorList&amp;lt;T&amp;gt; : IList&amp;lt;T&amp;gt;&lt;br&gt;{&lt;br&gt;&amp;nbsp; public ErrorList()&amp;nbsp;&amp;nbsp; { throw new Exception(); }&lt;br&gt;&amp;nbsp; public IList&amp;lt;T&amp;gt; Next { get { throw new Exception(); } }&lt;br&gt;&amp;nbsp; public T Value&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; { get { throw new Exception(); } }&lt;br&gt;}&lt;/font&gt;&lt;/p&gt;&lt;/blockquote&gt; &lt;p&gt;Now consider the following code:&lt;/p&gt; &lt;blockquote&gt; &lt;p&gt;&lt;font face="Courier New"&gt;var list = new List&amp;lt;int&amp;gt;(1, new ErrorList&amp;lt;int&amp;gt;());&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; // error, exception thrown&lt;br&gt;var stream = new Stream&amp;lt;int&amp;gt;(1, () =&amp;gt; new ErrorList&amp;lt;int&amp;gt;()); // no error&lt;/font&gt;&lt;/p&gt;&lt;/blockquote&gt; &lt;p&gt;An exception is thrown when the list is constructed but when the stream is constructed no exception is thrown.&amp;nbsp; Unless the Next property is evaluated on the stream, there will never be an exception.&lt;/p&gt; &lt;p&gt;The second difference can be seen in the following code:&lt;/p&gt; &lt;blockquote&gt; &lt;p&gt;&lt;font face="Courier New"&gt;IList&amp;lt;BigInteger&amp;gt; onesList = null;&lt;br&gt;onesList = new List&amp;lt;BigInteger&amp;gt;(1, onesList);&lt;br&gt;IList&amp;lt;BigInteger&amp;gt; onesStream = null;&lt;br&gt;onesStream = new Stream&amp;lt;BigInteger&amp;gt;(1, () =&amp;gt; onesStream);&lt;/font&gt;&lt;/p&gt;&lt;/blockquote&gt; &lt;p&gt;If you try to list all of the values in onesList, then you will notice that it only contains one value.&amp;nbsp; Whereas onesStream contains an infinite number of values.&amp;nbsp; The reason is that when we constructed onesList, we passed in onesList but onesList had the value null at the time so the next node was set to null.&amp;nbsp; But in the stream case we passed in a function that would be evaluated sometime in the future.&amp;nbsp; By the time that we evaluate it, it will return the proper value of onesStream.&lt;/p&gt; &lt;p&gt;A third difference is found in the performance of the two lists.&amp;nbsp; With the lazy lists, parts of the list that are never realized are never paid for.&amp;nbsp; So it is a pay as you go model as opposed to pay everything up front.&amp;nbsp; Furthermore, less space can be required since the whole list is not necessarily held in memory at once but only a process decription that can compute each element as it is required.&lt;/p&gt; &lt;p&gt;So now we have this infinite stream of ones, but can we do anything more interesting?&amp;nbsp; Sure.&amp;nbsp; First, let's define a zip function between lists.&lt;/p&gt; &lt;p&gt;&lt;font face="Courier New"&gt;&amp;nbsp; public static IList&amp;lt;V&amp;gt; Zip&amp;lt;T,U,V&amp;gt;(Func&amp;lt;T,U,V&amp;gt; f, IList&amp;lt;T&amp;gt; list1, IList&amp;lt;U&amp;gt; list2)&lt;br&gt;&amp;nbsp; {&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; if (list1 == null || list2 == null)&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; return null;&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; return new Stream&amp;lt;V&amp;gt;(f(list1.Value, list2.Value), () =&amp;gt; Zip&amp;lt;T,U,V&amp;gt;(f, list1.Next, list2.Next));&lt;br&gt;&amp;nbsp; }&lt;/font&gt; &lt;p&gt;Yes, that is somewhat of a mouthful.&amp;nbsp; Here is what it does.&amp;nbsp; It takes two lists where the lists may differ from each other in what kind of elements they contain.&amp;nbsp; It also takes a function from the type of the first list's elements and the type of the second list's elements and returns possibly a new type.&amp;nbsp; Then if either of the lists is empty we return an empty list (null).&amp;nbsp; But if both lists are non-empty then we return a stream where the first element is the application of the given function to the first element of both of the lists and the rest of the list will be the evaluation of Zip on the rest of the two lists.&amp;nbsp; It is important that Zip uses a stream because these lists may be infinite and if we try to immediately evaluate the entire list we will run out of resources.&lt;/p&gt; &lt;p&gt;Now that we have Zip, let's put it to use to define the natural numbers.&lt;/p&gt; &lt;blockquote&gt; &lt;p&gt;&lt;font face="Courier New"&gt;IList&amp;lt;BigInteger&amp;gt; ones = null;&lt;br&gt;ones = new Stream&amp;lt;BigInteger&amp;gt;(1, () =&amp;gt; ones);&lt;br&gt;IList&amp;lt;BigInteger&amp;gt; natural = null;&lt;br&gt;natural = new Stream&amp;lt;BigInteger&amp;gt;(0, () =&amp;gt; Zip((x, y) =&amp;gt; x + y, natural, ones));&lt;/font&gt;&lt;/p&gt;&lt;/blockquote&gt; &lt;p&gt;So what we are saying is that the natural numbers begin with zero and then are followed by the sum of the first natural number with the first element of ones (0 + 1).&amp;nbsp; The second natural number is the sum of the second element of natural numbers with the second element of ones (1 + 1) and so on.&amp;nbsp; This works because each element of natural numbers is defined only in terms of the elements of natural numbers that occur previous to it.&lt;/p&gt; &lt;p&gt;So now we can easily define the odd numbers (2k + 1)&amp;nbsp;and even numbers (2k).&amp;nbsp; But first we need a map function for lists.&lt;/p&gt; &lt;blockquote&gt; &lt;p&gt;&lt;font face="Courier New"&gt;public static IList&amp;lt;U&amp;gt; Map&amp;lt;T, U&amp;gt;(Func&amp;lt;T, U&amp;gt; f, IList&amp;lt;T&amp;gt; list)&lt;br&gt;{&lt;br&gt;&amp;nbsp; if (list == null)&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; return null;&lt;br&gt;&amp;nbsp; return new Stream&amp;lt;U&amp;gt;(f(list.Value), () =&amp;gt; Map(f, list.Next));&lt;br&gt;} &lt;/font&gt;&lt;/p&gt;&lt;/blockquote&gt; &lt;p&gt;Now here&amp;nbsp;are the definitions of odd and even numbers.&lt;/p&gt; &lt;blockquote&gt; &lt;p&gt;&lt;font face="Courier New"&gt;IList&amp;lt;BigInteger&amp;gt; odds = Map(x =&amp;gt; 2 * x + 1, natural);&lt;br&gt;IList&amp;lt;BigInteger&amp;gt; evens = Map(x =&amp;gt; 2 * x, natural);&lt;/font&gt;&lt;/p&gt;&lt;/blockquote&gt; &lt;p&gt;We can also define the fibonacci sequence as a stream.&lt;/p&gt; &lt;blockquote&gt; &lt;p&gt;&lt;font face="Courier New"&gt;IList&amp;lt;BigInteger&amp;gt; fibs = null;&lt;br&gt;fibs = new List&amp;lt;BigInteger&amp;gt;(0, new Stream&amp;lt;BigInteger&amp;gt;(1, () =&amp;gt; Zip(add, fibs, fibs.Next)));&lt;/font&gt;&lt;/p&gt;&lt;/blockquote&gt; &lt;p&gt;What we are saying here is that the first fibonacci number is zero and the second is one but then the next one is the sum of the first number and the second number and so on.&amp;nbsp; This is similar to the natural numbers definition which used itself to compute itself.&lt;/p&gt; &lt;p&gt;If you try it out, you will also notice that it isn't very efficient.&amp;nbsp; This is because we are back to our exponential time complexity.&amp;nbsp; But this can easily be remedied by memoizing the next function in the constructor to the stream:&lt;/p&gt;&lt;font face="Courier New"&gt;&amp;nbsp; public Stream(T value, Func&amp;lt;IList&amp;lt;T&amp;gt;&amp;gt; next)&lt;br&gt;&amp;nbsp; {&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; this.value = value;&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; this.next = next&lt;font color="#ff8040"&gt;.Memoize()&lt;/font&gt;;&lt;br&gt;&amp;nbsp; } &lt;/font&gt; &lt;p&gt;Now it has linear time complexity by trading off some space (linear as well).&lt;/p&gt; &lt;p&gt;Let's finish by solving the famous problem of producing the &lt;a href="http://en.wikipedia.org/wiki/Hamming_numbers"&gt;Hamming numbers&lt;/a&gt;.&amp;nbsp; The problem is to list all of the positive integers who have no prime factors other than 2, 3, or 5 in ascending order.&amp;nbsp; The first ten Hamming numbers are:&lt;/p&gt; &lt;blockquote&gt; &lt;p&gt;1, 2, 3, 4, 5, 6, 8, 9, 10, 12&lt;/p&gt;&lt;/blockquote&gt; &lt;p&gt;This problem is notoriously difficult without lazy evaluation and is used to demonstrate the power of laziness.&lt;/p&gt; &lt;p&gt;To solve this problem first note that the first hamming number is 1.&amp;nbsp; Then if h is a hamming number so is 2h, 3h, and 5h.&amp;nbsp; So we can define three streams which map the hamming numbers to 2h, 3h, and 5h respectively.&amp;nbsp; The only remaining requirement is that they must be in order.&amp;nbsp; We can maintain this invariant by defining a function named Merge:&lt;/p&gt; &lt;blockquote&gt; &lt;p&gt;&lt;font face="Courier New"&gt;public static IList&amp;lt;T&amp;gt; Merge&amp;lt;T&amp;gt;(IList&amp;lt;T&amp;gt; list1, IList&amp;lt;T&amp;gt; list2) where T : IComparable&amp;lt;T&amp;gt;&lt;br&gt;{&lt;br&gt;&amp;nbsp; if (list1 == null)&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; return list2;&lt;br&gt;&amp;nbsp; else if (list2 == null)&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; return list1;&lt;br&gt;&amp;nbsp; int c = list1.Value.CompareTo(list2.Value);&lt;br&gt;&amp;nbsp; if (c &amp;lt; 0)&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; return new Stream&amp;lt;T&amp;gt;(list1.Value, () =&amp;gt; Merge(list1.Next, list2));&lt;br&gt;&amp;nbsp; else if (c &amp;gt; 0)&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; return new Stream&amp;lt;T&amp;gt;(list2.Value, () =&amp;gt; Merge(list1, list2.Next));&lt;br&gt;&amp;nbsp; else&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; return new Stream&amp;lt;T&amp;gt;(list1.Value, () =&amp;gt; Merge(list1.Next, list2.Next));&lt;br&gt;}&lt;/font&gt;&lt;/p&gt;&lt;/blockquote&gt; &lt;p&gt;Now we are ready to define the Hamming numbers.&amp;nbsp; Notice how close the definition in the code is to our description:&lt;/p&gt; &lt;blockquote&gt; &lt;p&gt;&lt;font face="Courier New"&gt;IList&amp;lt;BigInteger&amp;gt; hamming = null;&lt;br&gt;hamming = new Stream&amp;lt;BigInteger&amp;gt;(1, () =&amp;gt; Merge(Map(x =&amp;gt; x * 2, hamming), Merge(Map(x =&amp;gt; x * 3, hamming), Map(x =&amp;gt; x * 5, hamming))));&lt;/font&gt;&lt;/p&gt;&lt;/blockquote&gt; &lt;p&gt;Now for fun, try to think of how to do it without lazy evaluation.&lt;/p&gt;&lt;img src="http://blogs.msdn.com/aggbug.aspx?PostID=1671293" width="1" height="1"&gt;</description><category domain="http://blogs.msdn.com/wesdyer/archive/tags/C_2300_/default.aspx">C#</category><category domain="http://blogs.msdn.com/wesdyer/archive/tags/Functional+Programming/default.aspx">Functional Programming</category></item><item><title>Why all the love for lists?</title><link>http://blogs.msdn.com/wesdyer/archive/2007/02/12/why-all-of-the-love-for-lists.aspx</link><pubDate>Mon, 12 Feb 2007 22:41:00 GMT</pubDate><guid isPermaLink="false">91d46819-8472-40ad-a661-2c78acb4018c:1663771</guid><dc:creator>wesdyer</dc:creator><slash:comments>15</slash:comments><comments>http://blogs.msdn.com/wesdyer/comments/1663771.aspx</comments><wfw:commentRss>http://blogs.msdn.com/wesdyer/commentrss.aspx?PostID=1663771</wfw:commentRss><description>&lt;P&gt;One of the things that I have noticed when&amp;nbsp;participating in&amp;nbsp;interviews&amp;nbsp;with potential candidates is that most candidates have a favorite data structure.&amp;nbsp; Presumably this is the data structure that they feel the most comfortable with.&amp;nbsp; The problem is that no matter what coding question I ask them, they see the answer through the lenses of their favorite data structure.&amp;nbsp; I have met programmers who are in love with hash tables, others who have a certain fondness for B-trees, and quite a few who adore arrays.&amp;nbsp; My feeling is that this happens not because they understand the data structure itself better than other data structures&amp;nbsp;(honestly, I can't believe that the guy who loves b-trees doesn't understand what arrays are), but it is because&amp;nbsp;each data structure encourages a certain way of&amp;nbsp;thinking about problems.&amp;nbsp; So really the candidates are just thinking about the question in a certain way that is expressed on the outside as using some particular data structure.&lt;/P&gt;
&lt;P&gt;One of the first things that a newcomer to functional programming will notice is that lists are all the rage.&amp;nbsp; Where most programmers who are accustomed to imperative style would naturally use an array, a&amp;nbsp;variable, or a mutable object, a functional programmer will often use a list.&amp;nbsp; Why is this?&lt;/P&gt;
&lt;P&gt;If we consider the insight that it is not the data structure itself but rather the mode of thinking that encourages the usage of the data structure then we can make some progress on understanding this.&amp;nbsp; Lists are the simplest recursive data structure.&amp;nbsp; A list is just a node consisting of a value and the next node in the list.&amp;nbsp; The definition of a list is defined in terms of itself.&lt;/P&gt;
&lt;BLOCKQUOTE&gt;
&lt;P&gt;&lt;FONT face="Courier New"&gt;&lt;/FONT&gt;
&lt;P&gt;&lt;FONT face="Courier New"&gt;interface IList&amp;lt;T&amp;gt;&lt;BR&gt;{&lt;BR&gt;&amp;nbsp; IList&amp;lt;T&amp;gt; Next { get; }&lt;BR&gt;&amp;nbsp; T Value { get; }&lt;BR&gt;}&lt;/FONT&gt;&lt;/P&gt;&lt;/BLOCKQUOTE&gt;
&lt;P&gt;But notice how similar this way of thinking is to recursive functions.&amp;nbsp; For example a very common function defined over lists is Length.&amp;nbsp; This function computes the length of a given list.&lt;/P&gt;
&lt;BLOCKQUOTE&gt;
&lt;P&gt;&lt;FONT face="Courier New"&gt;public static int Length&amp;lt;T&amp;gt;(this IList&amp;lt;T&amp;gt; list)&lt;BR&gt;{&lt;BR&gt;&amp;nbsp; if (list == null)&lt;BR&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; return 0;&lt;BR&gt;&amp;nbsp; return 1 + Length(list.Next);&lt;BR&gt;}&lt;/FONT&gt;&lt;/P&gt;&lt;/BLOCKQUOTE&gt;
&lt;P&gt;Length is a function that is defined in terms of itself.&amp;nbsp; Like the definition of list, Length has a value (either the 0 or the 1 +) and it has a next (the recursive call to Length(list.Next)).&amp;nbsp; So one reason why lists are so popular in functional programming is that they encourage a recursive way of thinking about problems.&lt;/P&gt;
&lt;P&gt;In C# 3.0, lists are not so commonly used as IEnumerable&amp;lt;T&amp;gt;.&amp;nbsp; In fact, IEnumerable&amp;lt;T&amp;gt; is used so much that it sticks out in the same way the usage of lists in functional programming languages sticks out.&amp;nbsp; The primary Linq provider that will be shipped is Linq to Objects which requires that the source of a query implement IEnumerable&amp;lt;T&amp;gt;.&lt;/P&gt;
&lt;P&gt;In some senses, IEnumerable&amp;lt;T&amp;gt; is not so very different from the definition of IList&amp;lt;T&amp;gt; shown above.&amp;nbsp; Both of them represent sequences of elements where only the current value and the next element are available at a given time.&amp;nbsp; In fact, it is relatively easy to define one in terms of the other.&lt;/P&gt;
&lt;P&gt;Here is a definition of IEnumerable&amp;lt;T&amp;gt; in terms of IList&amp;lt;T&amp;gt;.&lt;/P&gt;
&lt;BLOCKQUOTE&gt;
&lt;P&gt;&lt;FONT face="Courier New"&gt;public static IEnumerable&amp;lt;T&amp;gt; GetEnumerator&amp;lt;T&amp;gt;(this IList&amp;lt;T&amp;gt; list)&lt;BR&gt;{&lt;BR&gt;&amp;nbsp; for (var current = list; current != null; current = current.Next)&lt;BR&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; yield return current.Value;&lt;BR&gt;}&lt;/FONT&gt;&lt;/P&gt;&lt;/BLOCKQUOTE&gt;
&lt;P&gt;And here is a corresponding definition of IList&amp;lt;T&amp;gt; in terms of IEnumerable&amp;lt;T&amp;gt; (take from &lt;A href="http://blogs.msdn.com/wesdyer/archive/2006/01/13/saving-the-state-of-enumerators.aspx" mce_href="http://blogs.msdn.com/wesdyer/archive/2006/01/13/saving-the-state-of-enumerators.aspx"&gt;this post&lt;/A&gt;).&lt;/P&gt;
&lt;BLOCKQUOTE&gt;
&lt;P&gt;&lt;FONT face="Courier New"&gt;class LazyList&amp;lt;T&amp;gt; : IList&amp;lt;T&amp;gt;&lt;BR&gt;{&lt;BR&gt;&amp;nbsp; IList&amp;lt;T&amp;gt; next;&lt;BR&gt;&amp;nbsp; T value;&lt;BR&gt;&amp;nbsp; IEnumerator&amp;lt;T&amp;gt; enumerator; &lt;/FONT&gt;
&lt;P&gt;&lt;FONT face="Courier New"&gt;&amp;nbsp;&amp;nbsp;LazyList(T value, IEnumerator&amp;lt;T&amp;gt; enumerator)&lt;BR&gt;&amp;nbsp; {&lt;BR&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; this.value = value;&lt;BR&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;this.enumerator = enumerator;&lt;BR&gt;&amp;nbsp; } &lt;/FONT&gt;
&lt;P&gt;&lt;FONT face="Courier New"&gt;&amp;nbsp; public static IList&amp;lt;T&amp;gt; Create(IEnumerable&amp;lt;T&amp;gt; enumerable)&lt;BR&gt;&amp;nbsp; {&lt;BR&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; return Create(enumerable.GetEnumerator());&lt;BR&gt;&amp;nbsp; } &lt;/FONT&gt;
&lt;P&gt;&lt;FONT face="Courier New"&gt;&amp;nbsp; public static IList&amp;lt;T&amp;gt; Create(IEnumerator&amp;lt;T&amp;gt; enumerator)&lt;BR&gt;&amp;nbsp; {&lt;BR&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; if (enumerator.MoveNext())&lt;BR&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; return new LazyList&amp;lt;T&amp;gt;(enumerator.Current, enumerator);&lt;BR&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; return null;&lt;BR&gt;&amp;nbsp; } &lt;/FONT&gt;
&lt;P&gt;&lt;FONT face="Courier New"&gt;&amp;nbsp; public IList&amp;lt;T&amp;gt; Next&lt;BR&gt;&amp;nbsp; {&lt;BR&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; get&lt;BR&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; {&lt;BR&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; if (enumerator != null)&lt;BR&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; {&lt;BR&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; next = Create(enumerator);&lt;BR&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; enumerator = null;&lt;BR&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; }&lt;BR&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; return next;&lt;BR&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;}&lt;BR&gt;&amp;nbsp; } &lt;/FONT&gt;
&lt;P&gt;&lt;FONT face="Courier New"&gt;&amp;nbsp; public T Value { get { return value; } }&lt;BR&gt;}&lt;/FONT&gt;&lt;/P&gt;&lt;/BLOCKQUOTE&gt;
&lt;P&gt;But it should be noted that there is a critical difference between both of these definitions and the following definition of List&amp;lt;T&amp;gt;.&lt;/P&gt;
&lt;BLOCKQUOTE&gt;
&lt;P&gt;&lt;FONT face="Courier New"&gt;class List&amp;lt;T&amp;gt; : IList&amp;lt;T&amp;gt;&lt;BR&gt;{&lt;BR&gt;&amp;nbsp; T value;&lt;BR&gt;&amp;nbsp; IList&amp;lt;T&amp;gt; next; &lt;/FONT&gt;
&lt;P&gt;&lt;FONT face="Courier New"&gt;&amp;nbsp; public List(T value, IList&amp;lt;T&amp;gt; next)&lt;BR&gt;&amp;nbsp; {&lt;BR&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; this.value = value;&lt;BR&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; this.next = next;&lt;BR&gt;&amp;nbsp; } &lt;/FONT&gt;
&lt;P&gt;&lt;FONT face="Courier New"&gt;&amp;nbsp; public IList&amp;lt;T&amp;gt; Next { get { return next; } }&lt;BR&gt;&amp;nbsp; public T Value { get { return value; } } &lt;/FONT&gt;
&lt;P&gt;&lt;FONT face="Courier New"&gt;&amp;nbsp; public static IList&amp;lt;T&amp;gt; Empty { get { return null; } }&lt;BR&gt;}&lt;/FONT&gt;&lt;/P&gt;&lt;/BLOCKQUOTE&gt;
&lt;P&gt;Did you notice what it is?&amp;nbsp; The previous definitions were lazy but this definition is not.&amp;nbsp; The iterator did not describe the data itself but rather a process for sequencing data that will be executed possibly sometime in the future.&amp;nbsp; The LazyList also does not actually realize an entire list.&amp;nbsp; It describes a way to construct the next element of a list on demand.&amp;nbsp; But the definition of List does not defer anything to the future.&amp;nbsp; Now the question is, does it matter?&lt;/P&gt;&lt;img src="http://blogs.msdn.com/aggbug.aspx?PostID=1663771" width="1" height="1"&gt;</description><category domain="http://blogs.msdn.com/wesdyer/archive/tags/C_2300_/default.aspx">C#</category><category domain="http://blogs.msdn.com/wesdyer/archive/tags/Functional+Programming/default.aspx">Functional Programming</category></item><item><title>Baby Names, Nameless Keys, and Mumbling</title><link>http://blogs.msdn.com/wesdyer/archive/2007/02/11/baby-names-nameless-keys-and-mumbling.aspx</link><pubDate>Sun, 11 Feb 2007 09:49:34 GMT</pubDate><guid isPermaLink="false">91d46819-8472-40ad-a661-2c78acb4018c:1648800</guid><dc:creator>wesdyer</dc:creator><slash:comments>20</slash:comments><comments>http://blogs.msdn.com/wesdyer/comments/1648800.aspx</comments><wfw:commentRss>http://blogs.msdn.com/wesdyer/commentrss.aspx?PostID=1648800</wfw:commentRss><description>&lt;p&gt;&lt;strong&gt;Baby Names&lt;/strong&gt;&lt;/p&gt; &lt;p&gt;I recently finished reading &lt;a href="http://www.amazon.com/Freakonomics-Revised-Expanded-Economist-Everything/dp/0061234001/sr=8-1/qid=1171154450/ref=pd_bbs_sr_1/002-3886557-6494420?ie=UTF8&amp;amp;s=books"&gt;Freakonomics&lt;/a&gt;.&amp;nbsp; It is a fascinating book about a number of strange phenomena.&amp;nbsp; Its topics range from the economics of dealing crack to cheating in sumo wrestling.&amp;nbsp; Among the sundry topics is a discussion&amp;nbsp;concerning the psychology and sociology underlying&amp;nbsp;babies names.&lt;/p&gt; &lt;p&gt;This topic&amp;nbsp;has interested me ever since I found out that my wife and I gave our first two children some of the most popular names for their birth year.&amp;nbsp; We did not intentionally look for popular names, but we picked them any way.&amp;nbsp; I always wondered how it was that I picked with the crowd.&amp;nbsp; I had theories but I didn't have any data.&lt;/p&gt; &lt;p&gt;So when I heard &lt;a href="http://en.wikipedia.org/wiki/Steven_Levitt"&gt;Levitt&lt;/a&gt; and &lt;a href="http://en.wikipedia.org/wiki/Stephen_Dubner"&gt;Dubner's&lt;/a&gt; &lt;a href="http://www.slate.com/id/2116505/"&gt;theory&lt;/a&gt; about why some baby names are so popular, I was naturally very curious.&amp;nbsp; Their hypothesis is that affluent and successful families set the trend (&lt;a href="http://www.infoplease.com/spot/celebrity-baby-names.html"&gt;not celebrities&lt;/a&gt;).&amp;nbsp; Some baby names begin to take hold in affluent circles.&amp;nbsp; Then when less successful parents are looking for a baby name, they choose the names of children of privilege and opportunity.&amp;nbsp; Thus the&amp;nbsp;name continues to extend its influence from one family to another.&amp;nbsp; Eventually, everyone is giving their child&amp;nbsp;the name (&lt;a href="http://orangetangerine.blogspot.com/2007/01/let-us-now-mock-baby-names.html"&gt;often misspelling it&lt;/a&gt;).&amp;nbsp; Finally as more and more&amp;nbsp;of the common folk&amp;nbsp;use the name, the elitists stop using the name.&lt;/p&gt; &lt;p&gt;Their theory seemed probable enough and they had some good data to back it up, but I had my doubts.&amp;nbsp; I certainly didn't feel like I picked my son's name because I thought some other child's opportunities would rub off on&amp;nbsp;him.&lt;/p&gt; &lt;p&gt;Later on, I was in need of an app to test&amp;nbsp;Linq to Objects query&amp;nbsp;performance over a large dataset.&amp;nbsp; Unfortunately, we didn't have a suitable app and I didn't have a lot of time.&amp;nbsp; Furthermore, I didn't have a large easily accessible in-memory dataset to work with.&amp;nbsp; So I decided to write a quick little app to screen scrape the Social Security Administration's &lt;em&gt;&lt;a href="http://www.ssa.gov/OACT/babynames/"&gt;Popular Baby Names&lt;/a&gt;&lt;/em&gt; site.&amp;nbsp; The app pulled down the top one hundred most popular names for every year in every state by gender since the year 1960.&amp;nbsp; I ended up with 40 megabytes of XML where each element looked something like this:&lt;/p&gt; &lt;blockquote&gt; &lt;p&gt;&lt;font face="Courier New"&gt;&amp;lt;PopularName state="Alaska" year="1960" rank="5" gender="Female" name="Susan" count="50" /&amp;gt;&lt;/font&gt;&lt;/p&gt;&lt;/blockquote&gt; &lt;p&gt;I then wrote an app that loaded all of the data into memory.&amp;nbsp; Each XML element became a&lt;font face="Courier New"&gt; PopularName&lt;/font&gt; object which has a property for each attribute in the XML.&amp;nbsp; These names were stored in a local variable called &lt;font face="Courier New"&gt;names&lt;/font&gt; of type &lt;font face="Courier New"&gt;List&amp;lt;PopularName&amp;gt;&lt;/font&gt;.&lt;/p&gt; &lt;p&gt;I then wrote a number of queries against the baby name dataset.&amp;nbsp; One of the queries shows the number of children named that name by year.&amp;nbsp; This query is run by calling &lt;font face="Courier New"&gt;NameUsage&lt;/font&gt; and passing in &lt;font face="Courier New"&gt;names&lt;/font&gt; and the name to use in the query.&lt;/p&gt; &lt;blockquote&gt; &lt;p&gt;&lt;font face="Courier New"&gt;&lt;/font&gt; &lt;p&gt;&lt;font face="Courier New"&gt;NameUsage(names, "Wesley");&lt;/font&gt;&lt;/p&gt;&lt;/blockquote&gt; &lt;p&gt;Where the body of the method looks like: &lt;blockquote&gt; &lt;p&gt;&lt;font face="Courier New"&gt;static void NameUsage(IEnumerable&amp;lt;PopularName&amp;gt; names, string searchName)&lt;br&gt;{&lt;br&gt;&amp;nbsp; Console.WriteLine("{0} Usage", searchName);&lt;br&gt;&amp;nbsp; var q = from name in names&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; where name.Name == searchName&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; group new { name.Name, name.Count } by name.Year&lt;br&gt;&amp;nbsp;&amp;nbsp; &amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; into g&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; orderby g.Key ascending&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; select new { Year = g.Key, TotalCount = g.Sum(x =&amp;gt; x.Count) }; &lt;/font&gt; &lt;p&gt;&lt;font face="Courier New"&gt;&amp;nbsp; foreach (var item in q) Console.WriteLine(item);&lt;br&gt;}&lt;/font&gt;&lt;/p&gt;&lt;/blockquote&gt; &lt;p&gt;This particular query displays: &lt;blockquote&gt; &lt;p&gt;&lt;font face="Courier New"&gt;&lt;/font&gt; &lt;p&gt;&lt;font face="Courier New"&gt;Wesley Usage&lt;br&gt;{ Year = 1960, TotalCount = 107 }&lt;br&gt;...&lt;br&gt;{ Year = 2005, TotalCount = 159 }&lt;/font&gt;&lt;/p&gt;&lt;/blockquote&gt; &lt;p&gt;Here is a graph of the data for the usage of the name "Wesley". &lt;p&gt;&lt;a href="http://blogs.msdn.com/blogfiles/wesdyer/WindowsLiveWriter/BabyNamesNamelessKeysandMumbling_D277/image%7B0%7D%5B9%5D.png" atomicselection="true"&gt;&lt;img style="border-right: 0px; border-top: 0px; border-left: 0px; border-bottom: 0px" height="240" src="http://blogs.msdn.com/blogfiles/wesdyer/WindowsLiveWriter/BabyNamesNamelessKeysandMumbling_D277/image%7B0%7D_thumb%5B7%5D.png" width="400" border="0"&gt;&lt;/a&gt;  &lt;p&gt;So it seems that my parents were victims of their time as well.&amp;nbsp; But is it only me and my children? &lt;p&gt;Apparently not.&amp;nbsp; My wife was also given her name during its period of popularity.&amp;nbsp; Note that these names are not necessarily really popular names.&amp;nbsp; Even so, the giving of various names seems to ebb and flow.&amp;nbsp; It is fascinating to think about how this behavior emerges from the vast array of parents seeking the best name for their child. &lt;p&gt;&lt;a href="http://blogs.msdn.com/blogfiles/wesdyer/WindowsLiveWriter/BabyNamesNamelessKeysandMumbling_D277/image%7B0%7D%5B12%5D.png" atomicselection="true"&gt;&lt;img style="border-right: 0px; border-top: 0px; border-left: 0px; border-bottom: 0px" height="240" src="http://blogs.msdn.com/blogfiles/wesdyer/WindowsLiveWriter/BabyNamesNamelessKeysandMumbling_D277/image%7B0%7D_thumb%5B8%5D.png" width="400" border="0"&gt;&lt;/a&gt;&amp;nbsp; &lt;p&gt;&lt;strong&gt;Nameless Keys&lt;/strong&gt;&lt;/p&gt; &lt;p&gt;Another one of queries that I wrote listed the most popular names overall.&amp;nbsp; I wanted to distinguish names by gender usage (Terry, Pam, ...) but how can we do that with queries?&lt;/p&gt; &lt;p&gt;What I really want is to make the equality of the names based on the name itself and the gender usage.&amp;nbsp; In C# 3.0, we added anonymous types.&amp;nbsp; These neat little guys are very useful and one of the ways that they are the most useful is as composite keys.&lt;/p&gt; &lt;p&gt;Anonymous types have structural equality semantics within an assembly.&amp;nbsp; This means that if two anonymous types are created with the same property names in the same order and of the same type then they will be the same type and if the values are the same then the two instances will be equal and have the same hashcode.&lt;/p&gt; &lt;p&gt;We can use these facts to write queries which define equality between objects on several values.&amp;nbsp; In this case equality depends on the name and the gender.&amp;nbsp; So in the group...by clause we will group not on the name but on an anonymous type with members corresponding to the name and to the gender of the item.&lt;/p&gt; &lt;blockquote&gt; &lt;p&gt;&lt;font face="Courier New"&gt;&lt;/font&gt; &lt;p&gt;&lt;font face="Courier New"&gt;static void TopNames(List&amp;lt;PopularName&amp;gt; names, int count)&lt;br&gt;{&lt;br&gt;&amp;nbsp; Console.WriteLine("Top {0} Names", count);&lt;br&gt;&amp;nbsp; var q = (from name in names&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; group name.Count by &lt;font color="#ff8040"&gt;new { name.Name, name.Gender }&lt;/font&gt;&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; into g&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; let TotalCount = g.Sum()&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; orderby TotalCount descending&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; select new { g.Key.Name, g.Key.Gender, TotalCount })&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; .Take(count)&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; .Select((x, rank) =&amp;gt; new { Rank = rank + 1, x.Name, x.Gender, x.TotalCount }); &lt;/font&gt; &lt;p&gt;&lt;font face="Courier New"&gt;&amp;nbsp; foreach (var item in q) Console.WriteLine(item);&lt;br&gt;}&lt;/font&gt;&lt;/p&gt;&lt;/blockquote&gt; &lt;p&gt;Anonymous types can be used as composite keys in other&amp;nbsp;query clauses&amp;nbsp;such as join and orderby.&amp;nbsp; We can also use them to add multi-argument support to our &lt;a href="http://blogs.msdn.com/wesdyer/archive/2007/01/26/function-memoization.aspx"&gt;memoize&lt;/a&gt; function.&amp;nbsp; We will use them as multi-argument keys in the map contained in the memoization function.&lt;/p&gt; &lt;blockquote&gt; &lt;p&gt;&lt;font face="Courier New"&gt;public static Func&amp;lt;A, B, R&amp;gt; Memoize&amp;lt;A, B, R&amp;gt;(this Func&amp;lt;A, B, R&amp;gt; f)&lt;br&gt;{&lt;br&gt;&amp;nbsp; var map =&amp;nbsp;new Dictionary&amp;lt;???,R&amp;gt;();&lt;br&gt;&amp;nbsp; return (a, b) =&amp;gt;&lt;br&gt;&amp;nbsp; {&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; var tuple = new { a, b };&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; R value;&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; if (map.TryGetValue(tuple, out value))&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; return value;&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; value = f(a, b);&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; map.Add(tuple, value);&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; return value;&lt;br&gt;&amp;nbsp; };&lt;br&gt;}&lt;/font&gt;&lt;/p&gt;&lt;/blockquote&gt; &lt;p&gt;&lt;font face="Courier New"&gt;Memoize&lt;/font&gt; takes a function of two arguments of types &lt;font face="Courier New"&gt;A&lt;/font&gt; and &lt;font face="Courier New"&gt;B&lt;/font&gt; respectively.&amp;nbsp; It also returns a function of two arguments of types &lt;font face="Courier New"&gt;A&lt;/font&gt; and &lt;font face="Courier New"&gt;B&lt;/font&gt;.&amp;nbsp; What is different is that when the two arguments are passed into the lambda then they are put in a tuple and then it checks the map to see if that tuple is already in the map.&amp;nbsp; Essentially, we are using the anonymous type to form a composite key of the two arguments passed to the lambda. &lt;p&gt;&lt;strong&gt;Mumbling&lt;/strong&gt;&lt;/p&gt; &lt;p&gt;But how can we create a &lt;font face="Courier New"&gt;Dictionary&lt;/font&gt; from an anonymous type to type &lt;font face="Courier New"&gt;R&lt;/font&gt;?&amp;nbsp; While it is easy to specify the type of map using the &lt;a href="http://blogs.msdn.com/wesdyer/archive/2006/12/20/types-of-confusion.aspx"&gt;contextual keyword var&lt;/a&gt; even though&amp;nbsp;the type&amp;nbsp;doesn't have a speakable name, it isn't obvious how to specify the type parameters to the Dictionary constructor when we want to instantiate the type to an anonymous type.&lt;/p&gt; &lt;p&gt;We can get around this problem by introducing a new helper class.&lt;/p&gt; &lt;blockquote&gt; &lt;p&gt;&lt;font face="Courier New"&gt;static class DictionaryHelper&amp;lt;Value&amp;gt;&lt;br&gt;{&lt;br&gt;&amp;nbsp; public static Dictionary&amp;lt;Key, Value&amp;gt; Create&amp;lt;Key&amp;gt;(Key prototype)&lt;br&gt;&amp;nbsp; {&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; return new Dictionary&amp;lt;Key, Value&amp;gt;();&lt;br&gt;&amp;nbsp; }&lt;br&gt;}&lt;/font&gt;&lt;/p&gt;&lt;/blockquote&gt; &lt;p&gt;Here we put the type parameters that we can name (Value in this case) on the helper class.&amp;nbsp; Then we create a static method in the helper class that takes the remaining type parameters (Key in this case)&amp;nbsp; &lt;em&gt;but also takes one parameter of the same type for each type parameter&lt;/em&gt;.&amp;nbsp; This is so we can pass in parameters that will be used by type inference to infer the unspeakable type parameters.&amp;nbsp;&amp;nbsp;we therefore do not need to specify these types.&lt;/p&gt; &lt;p&gt;This means that we can replace the map creation in Memoize with the following code.&lt;/p&gt; &lt;blockquote&gt; &lt;p&gt;&lt;font face="Courier New"&gt;var map =&amp;nbsp;DictionaryHelper&amp;lt;R&amp;gt;.Create(new { a = default(A), b = default(B) });&lt;/font&gt;&lt;/p&gt;&lt;/blockquote&gt; &lt;p&gt;We specify one of the type parameters (R) of the Dictionary explicitly, but we specify the other (an anonymous type) implicitly by providing an example of the type.&lt;/p&gt; &lt;p&gt;I love using anonymous types as composite keys because they define equality and hashing semantics in terms of their members.&amp;nbsp; So next time you need a composite key, try using anonymous types.&lt;/p&gt; &lt;p&gt;In any case,&amp;nbsp;now that my wife and I are expecting our third child, I have been writing a number of queries against this dataset to understand the ebb and flow of baby names.&lt;/p&gt;&lt;img src="http://blogs.msdn.com/aggbug.aspx?PostID=1648800" width="1" height="1"&gt;</description><category domain="http://blogs.msdn.com/wesdyer/archive/tags/C_2300_/default.aspx">C#</category><category domain="http://blogs.msdn.com/wesdyer/archive/tags/Personal/default.aspx">Personal</category><category domain="http://blogs.msdn.com/wesdyer/archive/tags/Anonymous+Types/default.aspx">Anonymous Types</category></item><item><title>Memoization and Anonymous Recursion</title><link>http://blogs.msdn.com/wesdyer/archive/2007/02/05/memoization-and-anonymous-recursion.aspx</link><pubDate>Mon, 05 Feb 2007 21:12:19 GMT</pubDate><guid isPermaLink="false">91d46819-8472-40ad-a661-2c78acb4018c:1605582</guid><dc:creator>wesdyer</dc:creator><slash:comments>11</slash:comments><comments>http://blogs.msdn.com/wesdyer/comments/1605582.aspx</comments><wfw:commentRss>http://blogs.msdn.com/wesdyer/commentrss.aspx?PostID=1605582</wfw:commentRss><description>&lt;p&gt;&lt;a href="http://forums.microsoft.com/MSDN/Search/Search.aspx?words=keith+farmer&amp;amp;localechoice=9&amp;amp;SiteID=1&amp;amp;searchscope=forumscope&amp;amp;ForumID=123"&gt;Keith Farmer&lt;/a&gt; brought it to my attention that there&amp;nbsp;is at least &lt;a href="http://forums.microsoft.com/MSDN/ShowPost.aspx?PostID=1158525&amp;amp;SiteID=1"&gt;a little confusion&lt;/a&gt; about how &lt;a href="http://en.wikipedia.org/wiki/Closure_%28computer_science%29"&gt;closures&lt;/a&gt; work.&amp;nbsp; Hopefully, I can help shed a little light on the subject.&amp;nbsp; The question is why doesn't the following code actually memoize fib in the call to Test?&lt;/p&gt; &lt;blockquote&gt; &lt;p&gt;&lt;font face="Courier New"&gt;Func&amp;lt;int, int&amp;gt; fib = null;&lt;br&gt;fib = n =&amp;gt; n &amp;gt; 1 ? fib(n - 1) + fib(n - 2) : n;&lt;br&gt;Test(fib.Memoize());&lt;/font&gt;&lt;/p&gt;&lt;/blockquote&gt; &lt;p&gt;Before I explain why this code doesn't work, I want to return to the example that I used in my last post.&lt;/p&gt; &lt;blockquote&gt; &lt;p&gt;&lt;font face="Courier New"&gt;Func&amp;lt;int, int&amp;gt; fib = null;&lt;br&gt;fib = n =&amp;gt; n &amp;gt; 1 ? fib(n - 1) + fib(n - 2) : n;&lt;br&gt;Func&amp;lt;int, int&amp;gt; fibCopy = fib;&lt;br&gt;Console.WriteLine(fib(6));&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; // displays 8&lt;br&gt;Console.WriteLine(fibCopy(6));&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; // displays 8&lt;br&gt;fib = n =&amp;gt; n * 2;&lt;br&gt;Console.WriteLine(fib(6));&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; // displays 12&lt;br&gt;Console.WriteLine(fibCopy(6));&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; // displays 18&lt;/font&gt;&lt;/p&gt;&lt;/blockquote&gt; &lt;p&gt;Probably the easiest way to see why this code behaves so strangely is to show what code the C# compiler generates.&amp;nbsp; This can easily be done with&amp;nbsp;&lt;a href="http://msdn2.microsoft.com/en-us/library/f7dy01k1(VS.80).aspx"&gt;ildasm.exe&lt;/a&gt; or &lt;a href="http://www.aisto.com/roeder/dotnet/"&gt;reflector&lt;/a&gt;.&amp;nbsp; There are two lambdas defined in the code.&amp;nbsp; The first one captures the local variable named fib and the second does not capture any locals.&amp;nbsp; Because fib is capture by a lambda, it must be hoisted on to the heap.&amp;nbsp; So a class is declared that contains the captured local.&lt;/p&gt; &lt;blockquote&gt; &lt;p&gt;&lt;font face="Courier New"&gt;class DisplayClass&lt;br&gt;{&lt;br&gt;&amp;nbsp; public Func&amp;lt;int, int&amp;gt; fib;&lt;br&gt;}&lt;/font&gt;&lt;/p&gt;&lt;/blockquote&gt; &lt;p&gt;Now the compiler must emit a method that corresponds to the first lambda.&amp;nbsp; This method will need access to the members of DisplayClass and must also be convertible to a Func&amp;lt;int,int&amp;gt; delegate.&amp;nbsp; Today the compiler achieves this by emitting the method on the display class as an instance method (we could also have used currying but that is a story for another day).&lt;/p&gt; &lt;blockquote&gt; &lt;p&gt;&lt;font face="Courier New"&gt;class DisplayClass&lt;br&gt;{&lt;br&gt;&amp;nbsp; public Func&amp;lt;int, int&amp;gt; fib;&lt;br&gt;&amp;nbsp; public int M1(int n)&lt;br&gt;&amp;nbsp; {&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; return n &amp;gt; 1 ? fib(n - 1) + fib(n - 2) : n; //&amp;nbsp;&amp;lt;-- 1st lambda body&lt;br&gt;&amp;nbsp; }&lt;br&gt;}&lt;/font&gt;&lt;/p&gt;&lt;/blockquote&gt; &lt;p&gt;The second lambda does not capture&amp;nbsp;any local variables.&amp;nbsp; So this method can be emitted as a static method.&lt;/p&gt; &lt;blockquote&gt; &lt;p&gt;&lt;font face="Courier New"&gt;static int M2(int n)&lt;br&gt;{&lt;br&gt;&amp;nbsp; return n * 2;&lt;br&gt;}&lt;/font&gt;&lt;/p&gt;&lt;/blockquote&gt; &lt;p&gt;Finally, we are ready to show the emitted code for the original code fragment.&lt;/p&gt; &lt;blockquote&gt; &lt;p&gt;&lt;font face="Courier New"&gt;DisplayClass locals = new DisplayClass();&lt;br&gt;locals.fib = null;&lt;br&gt;locals.fib = locals.M1;&lt;br&gt;Func&amp;lt;int, int&amp;gt; fibCopy = locals.fib;&lt;br&gt;Console.WriteLine(locals.fib(6));&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; // displays 8&lt;br&gt;Console.WriteLine(fibCopy(6));&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; // displays 8&lt;br&gt;locals.fib = M2;&lt;br&gt;Console.WriteLine(locals.fib(6));&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; // displays 12&lt;br&gt;Console.WriteLine(fibCopy(6));&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; // displays 18&lt;/font&gt;&lt;/p&gt;&lt;/blockquote&gt; &lt;p&gt;Notice how the first call to fib is really just a call to M1 and when M1 "recurses" on fib it just ends up calling M1 again because that is what is assigned to fib.&amp;nbsp; The call to fibCopy is a little trickier because the original call is really a call to M1&amp;nbsp;as well but when it "recurses" it invokes fib instead of fibCopy which also &lt;em&gt;happens&lt;/em&gt; to be M1 at the time.&amp;nbsp; So the first two calls behave as expected.&lt;/p&gt; &lt;p&gt;Now it starts to get a little strange.&amp;nbsp; First we assign M2 to fib.&amp;nbsp; Then when we invoke fib on the next line it doesn't invoke our original "fib" function M1&amp;nbsp;anymore but it not invokes M2.&amp;nbsp; This of course displays the result of multiplying 6 by 2.&lt;/p&gt; &lt;p&gt;Now for the strangest part, we invoke fibCopy.&amp;nbsp; But fibCopy actually still references M1 and &lt;em&gt;not&lt;/em&gt; M2 and since 6 &amp;gt; 1 then it "recurses" by invoking fib twice&amp;nbsp;with 5 and 4 respectively and then summing the results.&amp;nbsp; But the calls to fib actually invoke M2 now.&amp;nbsp; So the results of the calls to fib are 10 and 8 which then are summed to produce 18.&lt;/p&gt; &lt;p&gt;Now let's return to our original problem.&lt;/p&gt; &lt;blockquote&gt; &lt;p&gt;&lt;font face="Courier New"&gt;Func&amp;lt;int, int&amp;gt; fib = null;&lt;br&gt;fib = n =&amp;gt; n &amp;gt; 1 ? fib(n - 1) + fib(n - 2) : n;&lt;br&gt;Test(fib.Memoize());&lt;/font&gt;&lt;/p&gt;&lt;/blockquote&gt; &lt;p&gt;Notice&amp;nbsp;that the function passed to Test&amp;nbsp;is memoized &lt;em&gt;but the body of the function still calls the unmemoized fib&lt;/em&gt;.&amp;nbsp; The function itself is memoized by all of the "recursive" calls are not.&amp;nbsp; So it probably will not behave as intended.&amp;nbsp; This can be corrected by doing the following.&lt;/p&gt; &lt;blockquote&gt; &lt;p&gt;&lt;font face="Courier New"&gt;Func&amp;lt;int, int&amp;gt; fib = null;&lt;br&gt;fib = Memoize(n =&amp;gt; n &amp;gt; 1 ? fib(n - 1) + fib(n - 2) : n);&lt;br&gt;Test(fib);&lt;/font&gt;&lt;/p&gt;&lt;/blockquote&gt; &lt;p&gt;Now the calls to fib when n &amp;gt; 1 are made to the memoized fib delegate.&lt;/p&gt; &lt;p&gt;If you read my &lt;a href="http://blogs.msdn.com/wesdyer/archive/2007/02/02/anonymous-recursion-in-c.aspx"&gt;last post&lt;/a&gt; on &lt;a href="http://en.wikipedia.org/wiki/Anonymous_recursion"&gt;anonymous recursion&lt;/a&gt; in C# which introduces the &lt;a href="http://en.wikipedia.org/wiki/Y_combinator"&gt;Y combinator&lt;/a&gt; then you may have tried the following.&lt;/p&gt; &lt;blockquote&gt; &lt;p&gt;&lt;font face="Courier New"&gt;Func&amp;lt;int, int&amp;gt; fib = Y&amp;lt;int, int&amp;gt;(f =&amp;gt; n =&amp;gt; n &amp;gt; 1 ? f(n - 1) + f(n - 2) : n).Memoize();&lt;/font&gt;&lt;/p&gt;&lt;/blockquote&gt; &lt;p&gt;This behaves very similarly to the&amp;nbsp;incorrectly written fib&amp;nbsp;above.&amp;nbsp; Calls to the function itself are memoized but all of the recursive calls are not.&amp;nbsp; This is because fib is memoized but f is not.&amp;nbsp; &lt;a href="http://research.microsoft.com/~emeijer/"&gt;Erik&lt;/a&gt; &lt;a href="http://en.wikipedia.org/wiki/Erik_Meijer_%28computer_scientist%29"&gt;Meijer&lt;/a&gt; pointed me to &lt;a href="http://citeseer.ist.psu.edu/47853.html"&gt;a fantastic paper&lt;/a&gt; that discusses how to memoize functions that are the fixed point of functionals.&amp;nbsp; In this paper, Cook and Launchbury present a function written in &lt;a href="http://www.haskell.org/haskellwiki/Haskell"&gt;Haskell&lt;/a&gt; that enables memoized anonymous recursive functions.&lt;/p&gt; &lt;blockquote&gt; &lt;p&gt;&lt;font face="Courier New"&gt;memoFix f = let g = f h&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; h = memo g&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; in h&lt;/font&gt;&lt;/p&gt;&lt;/blockquote&gt; &lt;p&gt;Using the MemoizeFix function in C#&amp;nbsp;looks very similar to using the Y combinator, but instead of just returning a recursive function, it would also memoize the function and all the recursive calls.&lt;/p&gt; &lt;blockquote&gt; &lt;p&gt;&lt;font face="Courier New"&gt;Func&amp;lt;int, int&amp;gt; memoFib = MemoizeFix&amp;lt;int, int&amp;gt;(f =&amp;gt; n =&amp;gt; n &amp;gt; 1 ? f(n - 1) + f(n - 2) : n);&lt;/font&gt;&lt;/p&gt;&lt;/blockquote&gt; &lt;p&gt;But there are two problems with implementing the function in C#.&amp;nbsp; First, Haskell lets programmers write mutually recursive definitions (g is defined in terms of h and h is defined in terms g).&amp;nbsp; Second, Haskell is a &lt;a href="http://en.wikipedia.org/wiki/Lazy_evaluation"&gt;lazy&lt;/a&gt; language.&amp;nbsp; A straightforward implementation in C# will either produce a null reference exception or a stack-overflow because of the eager evaluation and mutually recursive definitions.&amp;nbsp; Fortunately, lambdas can be used to solve both problems.&lt;/p&gt; &lt;blockquote&gt; &lt;p&gt;&lt;font face="Courier New"&gt;static Func&amp;lt;A, R&amp;gt; MemoizeFix&amp;lt;A, R&amp;gt;(this Func&amp;lt;Func&amp;lt;A, R&amp;gt;, Func&amp;lt;A, R&amp;gt;&amp;gt; f)&lt;br&gt;{&lt;br&gt;&amp;nbsp; Func&amp;lt;A, R&amp;gt; g = null;&lt;br&gt;&amp;nbsp; Func&amp;lt;A, R&amp;gt; h = null;&lt;br&gt;&amp;nbsp; g = a =&amp;gt; f(h)(a);&lt;br&gt;&amp;nbsp; h = g.Memoize();&lt;br&gt;&amp;nbsp; return h;&lt;br&gt;}&lt;/font&gt;&lt;/p&gt;&lt;/blockquote&gt; &lt;p&gt;Here we define both g and h before they are assigned their final values.&amp;nbsp; Then instead of assigning f(h) to g which would immediately&amp;nbsp;invoke f&amp;nbsp;causing a Null Reference exception, we assign a lambda to g which will be evaluated sometime in the future when h has a non-null value.&amp;nbsp; The rest of the function is very similar to the Haskell version.&lt;/p&gt; &lt;p&gt;Notice what happens when memoFib is invoked.&amp;nbsp; This will actually invoke h which was defined in MemoizeFix, but h is really just a memoized version of g.&amp;nbsp; Since this is the first invocation of h and there will be no precomputed value&amp;nbsp;and so g&amp;nbsp;will be invoked.&amp;nbsp; But when g is invoked then it actually invokes f passing h (memoized g) as the function to use for recursion.&amp;nbsp; This is exactly what we want.&amp;nbsp; Beautiful isn't it?&lt;/p&gt;&lt;img src="http://blogs.msdn.com/aggbug.aspx?PostID=1605582" width="1" height="1"&gt;</description><category domain="http://blogs.msdn.com/wesdyer/archive/tags/C_2300_/default.aspx">C#</category><category domain="http://blogs.msdn.com/wesdyer/archive/tags/Functional+Programming/default.aspx">Functional Programming</category></item><item><title>Anonymous Recursion in C#</title><link>http://blogs.msdn.com/wesdyer/archive/2007/02/02/anonymous-recursion-in-c.aspx</link><pubDate>Fri, 02 Feb 2007 22:17:00 GMT</pubDate><guid isPermaLink="false">91d46819-8472-40ad-a661-2c78acb4018c:1584397</guid><dc:creator>wesdyer</dc:creator><slash:comments>34</slash:comments><comments>http://blogs.msdn.com/wesdyer/comments/1584397.aspx</comments><wfw:commentRss>http://blogs.msdn.com/wesdyer/commentrss.aspx?PostID=1584397</wfw:commentRss><description>&lt;P&gt;&lt;A href="http://en.wikipedia.org/wiki/Recursion" mce_href="http://en.wikipedia.org/wiki/Recursion"&gt;Recursion&lt;/A&gt; is beautiful and &lt;A href="http://en.wikipedia.org/wiki/Lambda_calculus" mce_href="http://en.wikipedia.org/wiki/Lambda_calculus"&gt;lambdas&lt;/A&gt; are the ultimate abstraction.&amp;nbsp; But how can they be used together?&amp;nbsp; Lambdas are anonymous functions and recursion requires names.&amp;nbsp; Let's try to define a lambda that computes the nth fibonacci number.&lt;/P&gt;
&lt;BLOCKQUOTE&gt;
&lt;P&gt;&lt;FONT face="Courier New" color=#000080&gt;Func&amp;lt;int, int&amp;gt; fib = n =&amp;gt; n &amp;gt; 1 ? fib(n - 1) + fib(n - 2) : n;&lt;/FONT&gt;&lt;/P&gt;&lt;/BLOCKQUOTE&gt;
&lt;P&gt;But this doesn't work.&amp;nbsp; The compiler will complain&amp;nbsp;about the use of fib in the lambda. 
&lt;BLOCKQUOTE&gt;
&lt;P&gt;&lt;FONT face="Courier New" color=#000080&gt;Use of unassigned local variable 'fib'&lt;/FONT&gt;&lt;/P&gt;&lt;/BLOCKQUOTE&gt;
&lt;P&gt;&lt;A href="http://blogs.msdn.com/ericlippert/" mce_href="http://blogs.msdn.com/ericlippert/"&gt;Eric Lippert&lt;/A&gt; has a &lt;A href="http://blogs.msdn.com/ericlippert/archive/2006/08/18/706398.aspx" mce_href="http://blogs.msdn.com/ericlippert/archive/2006/08/18/706398.aspx"&gt;great blog post&lt;/A&gt; on this issue.&amp;nbsp; The problem is that the right hand side is evaluated before fib is &lt;A href="http://msdn2.microsoft.com/en-us/library/aa691172(VS.71).aspx" mce_href="http://msdn2.microsoft.com/en-us/library/aa691172(VS.71).aspx"&gt;definitely assigned&lt;/A&gt;.&amp;nbsp; In this case, the compiler could potentially deduce (if the language spec&amp;nbsp;allowed it) that fib is not used before it is definitely assigned, but in other cases it might need to be used before fib is assigned. 
&lt;P&gt;A quick workaround is to assign the value null to fib and then assign the lambda to fib.&amp;nbsp; This causes fib to be definitely assigned before it is used. 
&lt;BLOCKQUOTE&gt;
&lt;P&gt;&lt;FONT face="Courier New" color=#000080&gt;Func&amp;lt;int, int&amp;gt; fib = null;&lt;BR&gt;fib = n =&amp;gt; n &amp;gt; 1 ? fib(n - 1) + fib(n - 2) : n;&lt;BR&gt;Console.WriteLine(fib(6));&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; // displays 8&lt;/FONT&gt;&lt;/P&gt;&lt;/BLOCKQUOTE&gt;
&lt;P&gt;In fact, &lt;A href="http://www.federated.com/~jim/schintro-v14/schintro_66.html" mce_href="http://www.federated.com/~jim/schintro-v14/schintro_66.html"&gt;letrec&lt;/A&gt; in Scheme does something very similar. 
&lt;P&gt;But our C# workaround doesn't &lt;EM&gt;really&lt;/EM&gt; use recursion.&amp;nbsp; Recursion requires that a function calls itself.&amp;nbsp; The fib function &lt;EM&gt;really &lt;/EM&gt;just invokes the delegate that the local variable fib references.&amp;nbsp; It may seem that this is just nit picking about words, but there is a difference.&amp;nbsp; For example, consider the following code: 
&lt;BLOCKQUOTE&gt;
&lt;P&gt;&lt;FONT face="Courier New" color=#000080&gt;Func&amp;lt;int, int&amp;gt; fib = null;&lt;BR&gt;fib = n =&amp;gt; n &amp;gt; 1 ? fib(n - 1) + fib(n - 2) : n;&lt;BR&gt;Func&amp;lt;int, int&amp;gt;&amp;nbsp;fibCopy = fib;&lt;BR&gt;Console.WriteLine(fib(6));&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; // displays 8&lt;BR&gt;Console.WriteLine(fibCopy(6));&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; // displays 8&lt;BR&gt;fib = n =&amp;gt; n * 2;&lt;BR&gt;Console.WriteLine(fib(6));&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; // displays 12&lt;BR&gt;Console.WriteLine(fibCopy(6));&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; // displays 18&lt;/FONT&gt;&lt;/P&gt;&lt;/BLOCKQUOTE&gt;
&lt;P&gt;Huh!?&amp;nbsp; Notice how the result of calling fib changes and that the result of calling fibCopy differs even from the result of calling fib!&amp;nbsp; (See if you can figure out why)&lt;/P&gt;
&lt;P&gt;We can stop this kind of craziness by passing in the function that will be used for the recursive call.&amp;nbsp; So the lambda looks the same except that it takes an extra parameter f that is called instead of fib.&amp;nbsp; When a call to f is made, we need to pass f to itself as the first argument.&lt;/P&gt;
&lt;BLOCKQUOTE&gt;
&lt;P&gt;&lt;FONT face="Courier New" color=#000080&gt;(f, n) =&amp;gt; n &amp;gt; 1 ? f(f,n - 1) + f(f,n - 2) : n&lt;/FONT&gt;&lt;/P&gt;&lt;/BLOCKQUOTE&gt;
&lt;P&gt;Unfortunately, not all is done yet.&amp;nbsp; In order to convert the lambda to a delegate, we need a delegate type.&amp;nbsp; Although it is clear what type fib should be, it may not be apparent what should be the type of our new delegate.&amp;nbsp; So let's start with the type of fib, Func&amp;lt;int,int&amp;gt;.&amp;nbsp; We do know that the return type of the delegate should be the same, so it must be int.&amp;nbsp; We also know that the second argument's type should be the same which is also int.&amp;nbsp; As for the type of the first argument, we will be passing in a delegate which will then be called with the same arguments as the delegate we are defining.&amp;nbsp; But wait!&amp;nbsp; That is recursion.&amp;nbsp; We are defining the delegate type in terms of itself.&amp;nbsp; Therefore, the first parameter will be of the same type that the delegate we are defining is.&lt;/P&gt;
&lt;BLOCKQUOTE&gt;
&lt;P&gt;&lt;FONT face="Courier New" color=#000080&gt;delegate&amp;nbsp;int Recursive(Recursive r,&amp;nbsp;int n);&lt;/FONT&gt;&lt;/P&gt;&lt;/BLOCKQUOTE&gt;
&lt;P&gt;The delegate can be generalized by parameterizing&amp;nbsp;the type of the first argument and the return type.&lt;/P&gt;
&lt;BLOCKQUOTE&gt;
&lt;P&gt;&lt;FONT face="Courier New" color=#000080&gt;delegate R Recursive&amp;lt;A,R&amp;gt;(Recursive&amp;lt;A,R&amp;gt; r, A a);&lt;/FONT&gt;&lt;/P&gt;&lt;/BLOCKQUOTE&gt;
&lt;P&gt;Now we&amp;nbsp;can use the lambda that we defined.&lt;/P&gt;
&lt;BLOCKQUOTE&gt;
&lt;P&gt;&lt;FONT face="Courier New" color=#000080&gt;Recursive&amp;lt;int, int&amp;gt; fib = (f, n) =&amp;gt; n &amp;gt; 1 ? f(f,n - 1) + f(f,n - 2) : n;&lt;BR&gt;Console.WriteLine(fib(fib,6));&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; // displays 8&lt;/FONT&gt;&lt;/P&gt;&lt;/BLOCKQUOTE&gt;
&lt;P&gt;While this is an improvement, neither the lambda nor&amp;nbsp;its application&amp;nbsp;look as nice as the original code.&amp;nbsp; The fact that the first argument should be the delegate itself seems a little strange.&amp;nbsp; The lambda can be &lt;A href="http://blogs.msdn.com/wesdyer/archive/2007/01/29/currying-and-partial-function-application.aspx" mce_href="http://blogs.msdn.com/wesdyer/archive/2007/01/29/currying-and-partial-function-application.aspx"&gt;curried&lt;/A&gt; in order to separate the passing of f to f from the mechanics of the fib function.&amp;nbsp; The innermost lambda will have the same signature as the original fib function.&lt;/P&gt;
&lt;BLOCKQUOTE&gt;
&lt;P&gt;&lt;FONT face="Courier New" color=#000080&gt;f =&amp;gt; n =&amp;gt; n &amp;gt; 1 ? f(f)(n - 1) + f(f)(n - 2) : n&lt;/FONT&gt;&lt;/P&gt;&lt;/BLOCKQUOTE&gt;
&lt;P&gt;Now that the lambda has been curried, a new definition for the Recursive delegate is required.&amp;nbsp; It now only takes one argument which is the first argument of the previous definition, but the return type changes.&amp;nbsp; Recursive returns a function (the effect of currying it) which takes the second parameter of the original definition and returns the original return type.&lt;/P&gt;
&lt;BLOCKQUOTE&gt;
&lt;P&gt;&lt;FONT face="Courier New" color=#000080&gt;delegate Func&amp;lt;A,R&amp;gt; Recursive&amp;lt;A,R&amp;gt;(Recursive&amp;lt;A,R&amp;gt; r);&lt;/FONT&gt;&lt;/P&gt;&lt;/BLOCKQUOTE&gt;
&lt;P&gt;Once the lambda is assigned to a Recursive delegate then we can apply the delegate to itself to get the underlying function.&amp;nbsp; Furthermore, if we made a copy of the delegate and then changed the original then none of the strange effects that happened early would occur.&lt;/P&gt;
&lt;BLOCKQUOTE&gt;
&lt;P&gt;&lt;FONT face="Courier New"&gt;&lt;/FONT&gt;
&lt;P&gt;&lt;FONT face="Courier New" color=#000080&gt;Recursive&amp;lt;int, int&amp;gt; fibRec = f =&amp;gt; n =&amp;gt; n &amp;gt; 1 ? f(f)(n - 1) + f(f)(n - 2) : n;&lt;BR&gt;Func&amp;lt;int, int&amp;gt; fib = fibRec(fibRec);&lt;BR&gt;Console.WriteLine(fib(6));&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; // displays 8&lt;/FONT&gt;&lt;/P&gt;&lt;/BLOCKQUOTE&gt;
&lt;P&gt;It is now possible to clean-up&amp;nbsp;the duplicated self-application of f.&amp;nbsp; We can get rid of it by creating a lambda inside of the fibRec lambda which contains the essential fibonacci definition but which takes an argument that references what function should be called for recursion.&amp;nbsp; Then, inside of fibRec, we can do the self-application of f.&lt;/P&gt;
&lt;BLOCKQUOTE&gt;
&lt;P&gt;&lt;FONT face="Courier New" color=#000080&gt;Recursive&amp;lt;int, int&amp;gt; fibRec = f =&amp;gt; n =&amp;gt;&lt;BR&gt;&amp;nbsp; {&lt;BR&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; Func&amp;lt;Func&amp;lt;int, int&amp;gt;, int, int&amp;gt; g = (h, m) =&amp;gt; m &amp;gt; 1 ? h(m - 1) + h(m - 2) : m;&lt;BR&gt;&amp;nbsp; &amp;nbsp; return g(f(f), n);&lt;BR&gt;&amp;nbsp; };&lt;BR&gt;Func&amp;lt;int, int&amp;gt; fib = fibRec(fibRec);&lt;BR&gt;Console.WriteLine(fib(6));&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; // displays 8&lt;/FONT&gt;&lt;/P&gt;&lt;/BLOCKQUOTE&gt;
&lt;P&gt;This inner lambda looks very similar to our original lambda which took two parameters.&amp;nbsp; In fact, it appears that the whole process of construction and self-application that initially happened at the top level is now happening inside of the lambda.&amp;nbsp; The only difference is that the inner lambda does not pass a reference to itself around.&amp;nbsp; This has now be abstracted out in the call to g.&lt;/P&gt;
&lt;P&gt;We can simplify the fibRec definition by currying the inner lambda.&lt;/P&gt;
&lt;BLOCKQUOTE&gt;
&lt;P&gt;&lt;FONT face="Courier New" color=#000080&gt;Recursive&amp;lt;int, int&amp;gt; fibRec = f =&amp;gt; n =&amp;gt;&lt;BR&gt;{&lt;BR&gt;&amp;nbsp; Func&amp;lt;Func&amp;lt;int, int&amp;gt;, Func&amp;lt;int, int&amp;gt;&amp;gt; g = h =&amp;gt; m =&amp;gt; m &amp;gt; 1 ? h(m - 1) + h(m - 2) : m;&lt;BR&gt;&amp;nbsp; return g(f(f))(n);&lt;BR&gt;};&lt;BR&gt;Func&amp;lt;int, int&amp;gt; fib = fibRec(fibRec);&lt;BR&gt;Console.WriteLine(fib(6));&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; // displays 8&lt;/FONT&gt;&lt;/P&gt;&lt;/BLOCKQUOTE&gt;
&lt;P&gt;Note that the definition of g does not depend on f or n at all.&amp;nbsp; Therefore, we can move it outside of the outer lambda.&lt;/P&gt;
&lt;BLOCKQUOTE&gt;
&lt;P&gt;&lt;FONT face="Courier New" color=#000080&gt;Func&amp;lt;Func&amp;lt;int, int&amp;gt;, Func&amp;lt;int, int&amp;gt;&amp;gt; g = h =&amp;gt; m =&amp;gt; m &amp;gt; 1 ? h(m - 1) + h(m - 2) : m;&lt;BR&gt;Recursive&amp;lt;int, int&amp;gt; fibRec = f =&amp;gt; n =&amp;gt; g(f(f))(n);&lt;BR&gt;Func&amp;lt;int, int&amp;gt; fib = fibRec(fibRec);&lt;BR&gt;Console.WriteLine(fib(6));&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; // displays 8&lt;/FONT&gt;&lt;/P&gt;&lt;/BLOCKQUOTE&gt;
&lt;P&gt;Notice in the above code that g now represents our original concept of the fibonacci function while fibRec does all of the handy work to enable anonymous recursion.&amp;nbsp; The whole process of building of fibRec and then applying it to itself only requires a reference to g.&amp;nbsp; So let's move the definition of fibRec and fib to a different function named CreateFib.&lt;/P&gt;
&lt;BLOCKQUOTE&gt;
&lt;P&gt;&lt;FONT face="Courier New"&gt;&lt;FONT color=#000080&gt;static Func&amp;lt;int, int&amp;gt; CreateFib(Func&amp;lt;Func&amp;lt;int, int&amp;gt;, Func&amp;lt;int, int&amp;gt;&amp;gt; g)&lt;BR&gt;{&lt;BR&gt;&amp;nbsp; Recursive&amp;lt;A, R&amp;gt;&amp;nbsp;fibRec =&amp;nbsp;f =&amp;gt;&amp;nbsp;n =&amp;gt; g(f(f))(n);&lt;BR&gt;&amp;nbsp; return fibRec(fibRec);&lt;BR&gt;}&lt;/FONT&gt; &lt;/FONT&gt;&lt;/P&gt;&lt;/BLOCKQUOTE&gt;
&lt;P&gt;We can now call CreateFib instead of creating fibRec.&lt;/P&gt;
&lt;BLOCKQUOTE&gt;&lt;FONT face="Courier New" color=#000080&gt;Func&amp;lt;Func&amp;lt;int, int&amp;gt;, Func&amp;lt;int, int&amp;gt;&amp;gt; g = h =&amp;gt; m =&amp;gt; m &amp;gt; 1 ? h(m - 1) + h(m - 2) : m;&lt;BR&gt;Func&amp;lt;int, int&amp;gt; fib =CreateFib(g);&lt;BR&gt;Console.WriteLine(fib(6));&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; // displays 8&lt;/FONT&gt;&lt;/BLOCKQUOTE&gt;
&lt;P&gt;But really our CreateFib function is useful for more than just creating fibonacci functions.&amp;nbsp; It can create any recursive function which takes one argument.&amp;nbsp; Parameterizing the types used by CreateFib leads to what is known as the &lt;A href="http://www.dreamsongs.com/NewFiles/WhyOfY.pdf" mce_href="http://www.dreamsongs.com/NewFiles/WhyOfY.pdf"&gt;Y&lt;/A&gt; &lt;A href="http://en.wikipedia.org/wiki/Fixed_point_combinator" mce_href="http://en.wikipedia.org/wiki/Fixed_point_combinator"&gt;fixed-point combinator&lt;/A&gt;.&lt;/P&gt;
&lt;BLOCKQUOTE&gt;
&lt;P&gt;&lt;FONT face="Courier New" color=#000080&gt;static Func&amp;lt;A, R&amp;gt; Y&amp;lt;A, R&amp;gt;(Func&amp;lt;Func&amp;lt;A, R&amp;gt;, Func&amp;lt;A, R&amp;gt;&amp;gt; f)&lt;BR&gt;{&lt;BR&gt;&amp;nbsp; Recursive&amp;lt;A, R&amp;gt; rec = r =&amp;gt; a =&amp;gt; f(r(r))(a);&lt;BR&gt;&amp;nbsp; return rec(rec);&lt;BR&gt;} &lt;/FONT&gt;&lt;/P&gt;&lt;/BLOCKQUOTE&gt;
&lt;P&gt;We can now create any recursive lambda of one parameter that we want. 
&lt;BLOCKQUOTE&gt;
&lt;P&gt;&lt;FONT face="Courier New"&gt;&lt;/FONT&gt;&lt;/P&gt;&lt;FONT face="Courier New"&gt;
&lt;P&gt;&lt;FONT color=#000080&gt;Func&amp;lt;int,int&amp;gt; fib = Y&amp;lt;int,int&amp;gt;(f =&amp;gt; n =&amp;gt; n &amp;gt; 1 ? f(n - 1) + f(n - 2) : n);&lt;BR&gt;Func&amp;lt;int, int&amp;gt; fact = Y&amp;lt;int, int&amp;gt;(f =&amp;gt; n =&amp;gt; n &amp;gt; 1 ? n * f(n - 1) : 1);&lt;BR&gt;Console.WriteLine(fib(6));&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; // displays 8&lt;BR&gt;Console.WriteLine(fact(6));&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;// displays 720&lt;/FONT&gt;&lt;/FONT&gt;&lt;/P&gt;&lt;/BLOCKQUOTE&gt;
&lt;P&gt;Finally, the goal of anonymous recursion has been reached. &lt;/P&gt;&lt;img src="http://blogs.msdn.com/aggbug.aspx?PostID=1584397" width="1" height="1"&gt;</description><category domain="http://blogs.msdn.com/wesdyer/archive/tags/C_2300_/default.aspx">C#</category><category domain="http://blogs.msdn.com/wesdyer/archive/tags/Functional+Programming/default.aspx">Functional Programming</category></item><item><title>Currying and Partial Function Application</title><link>http://blogs.msdn.com/wesdyer/archive/2007/01/29/currying-and-partial-function-application.aspx</link><pubDate>Mon, 29 Jan 2007 23:36:53 GMT</pubDate><guid isPermaLink="false">91d46819-8472-40ad-a661-2c78acb4018c:1552802</guid><dc:creator>wesdyer</dc:creator><slash:comments>6</slash:comments><comments>http://blogs.msdn.com/wesdyer/comments/1552802.aspx</comments><wfw:commentRss>http://blogs.msdn.com/wesdyer/commentrss.aspx?PostID=1552802</wfw:commentRss><description>&lt;p&gt;When I first heard the term &lt;a href="http://en.wikipedia.org/wiki/Currying"&gt;Currying&lt;/a&gt;, I thought immediately of tasty Thai and Indian food.&amp;nbsp; To my dismay, I found that the conversation was not about wonderful spices but rather about transforming a function that takes n arguments into a function that takes only one argument and returns a curried function of n - 1 arguments.&amp;nbsp; Why in the world would that be useful?&lt;/p&gt; &lt;p&gt;From a theoretical standpoint, it is interesting because it simplifies the &lt;a href="http://en.wikipedia.org/wiki/Lambda_calculus"&gt;lambda calculus&lt;/a&gt; to include only those functions which have at most one argument.&amp;nbsp; From a practical perspective, it allows a programmer to generate families of functions from a base function by fixing the first&amp;nbsp;k arguments.&amp;nbsp; It is akin to pinning up something on the wall that requires two pins.&amp;nbsp; Before being pinned, the object is free to move anywhere on the surface; however, when&amp;nbsp;when first pin is put in then&amp;nbsp;the movement is constrained.&amp;nbsp; Finally, when the second pin is put in then there is no longer any freedom of movement.&amp;nbsp; Similarly, when a programmer curries a function of two arguments and applies it to the first argument then the functionality is limited by one dimension.&amp;nbsp; Finally, when he applies the new function to the second argument then a particular value is computed.&lt;/p&gt; &lt;p&gt;What this means&amp;nbsp;in C# is if I have a delegate which is of type Func&amp;lt;A,B,R&amp;gt; (delegate with two arguments of type A and B respectively and returns type R)&amp;nbsp;then I can create a delegate which is of type Func&amp;lt;A,Func&amp;lt;B,R&amp;gt;&amp;gt;.&amp;nbsp; Notice how the curried delegate only has one argument but it returns a delegate which takes the original function's second argument and finally returns a value.&lt;/p&gt; &lt;p&gt;Consider generating functions from the add function.&lt;/p&gt; &lt;blockquote&gt; &lt;p&gt;&lt;font face="Courier New"&gt;Func&amp;lt;int,int,int&amp;gt; add = (x,y) =&amp;gt; x + y;&lt;/p&gt;&lt;/blockquote&gt;&lt;/font&gt; &lt;p&gt;We can curry add by applying the Curry function to add.&lt;/p&gt; &lt;blockquote&gt;&lt;font face="Courier New"&gt;&lt;font face="Courier New"&gt;Func&amp;lt;int,Func&amp;lt;int,int&amp;gt;&amp;gt; curriedAdd = add.Curry();&lt;/font&gt;&lt;/font&gt;&lt;/blockquote&gt; &lt;p&gt;This curried add function is really a function that creates functions that add n where n is the argument to the curried add function.&amp;nbsp; For example, we can create an increment function by applying the curried add function to the value one.&lt;/p&gt; &lt;blockquote&gt; &lt;p&gt;&lt;font face="Courier New"&gt;Func&amp;lt;int,int&amp;gt; inc = curriedAdd(1);&lt;/font&gt;&lt;/p&gt;&lt;/blockquote&gt; &lt;p&gt;The increment function will now return one plus the value of its argument when invoked.&amp;nbsp; We can now use our three functions to do various forms of addition.&lt;/p&gt; &lt;blockquote&gt; &lt;p&gt;&lt;font face="Courier New"&gt;Console.WriteLine(add(3,4));&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;// 7&lt;br&gt;Console.WriteLine(curriedAdd(3)(5));&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;// 8&lt;br&gt;Console.WriteLine(inc(2));&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;// 3&lt;/font&gt;&lt;/p&gt;&lt;/blockquote&gt; &lt;p&gt;So how would this function Curry look?&amp;nbsp; It's really pretty simple.&lt;/p&gt; &lt;p&gt; &lt;blockquote&gt; &lt;p&gt;&lt;font face="Courier New"&gt;public static Func&amp;lt;A, Func&amp;lt;B, R&amp;gt;&amp;gt; Curry&amp;lt;A, B, R&amp;gt;(this Func&amp;lt;A, B, R&amp;gt; f)&lt;br&gt;{&lt;br&gt;&amp;nbsp; return a =&amp;gt; b =&amp;gt; f(a, b);&lt;br&gt;}&lt;/font&gt;&lt;/p&gt;&lt;/blockquote&gt; &lt;p&gt;It just takes a function of two arguments and then returns a lambda which fixes the first argument and then the second argument.&amp;nbsp; Once both arguments have been provided it evaluates the original function with the arguments.&amp;nbsp; It is easy to follow the same pattern and create a function Curry which curries a functions of other arities.&lt;/p&gt; &lt;p&gt;Let's examine what went on when we created each of the functions.&amp;nbsp; First we created a function called add which looked like:&lt;/p&gt; &lt;blockquote&gt; &lt;p&gt;&lt;font face="Courier New"&gt;(x, y) =&amp;gt; x + y&lt;/font&gt;&lt;/p&gt;&lt;/blockquote&gt; &lt;p&gt;&amp;nbsp;Once we curried add, the function became:&lt;/p&gt; &lt;blockquote&gt; &lt;p&gt;&lt;font face="Courier New"&gt;x =&amp;gt; y =&amp;gt; x + y&lt;/font&gt;&lt;/p&gt;&lt;/blockquote&gt; &lt;p&gt;We created inc by calling curried add with the value 1.&amp;nbsp; This essentially created the following function:&lt;/p&gt; &lt;blockquote&gt; &lt;p&gt;&lt;font face="Courier New"&gt;y&amp;nbsp;=&amp;gt; 1 + y&lt;/font&gt;&lt;/p&gt;&lt;/blockquote&gt; &lt;p&gt;The idea of currying a function and then fixing the first n arguments of the original function&amp;nbsp;can be generalized into an concept called partial function application.&amp;nbsp; For instance, if we consider our add function from the previous example then we can directly create the increment from add without having to create curriedAdd first.&lt;/p&gt; &lt;blockquote&gt; &lt;p&gt;&lt;font face="Courier New"&gt;Func&amp;lt;int,int&amp;gt; inc = add.Partial(1);&lt;/font&gt;&lt;/p&gt;&lt;/blockquote&gt; &lt;p&gt;Where the Partial function is written as:&lt;/p&gt; &lt;blockquote&gt; &lt;p&gt;&lt;font face="Courier New"&gt;public static Func&amp;lt;B, R&amp;gt; Partial&amp;lt;A, B, R&amp;gt;(this Func&amp;lt;A, B, R&amp;gt; f, A a)&lt;br&gt;{&lt;br&gt;&amp;nbsp; return b =&amp;gt; f(a, b);&lt;br&gt;}&lt;/font&gt;&lt;/p&gt;&lt;/blockquote&gt; &lt;p&gt;Notice how the function takes a function and a value which has the same type as the first argument of the function.&amp;nbsp; It then returns a function which takes the remaining arguments and then applies all of the arguments to the original function.&amp;nbsp; This can be generalized into a set of functions that produce partially applied&amp;nbsp;functions.&lt;/p&gt;&lt;img src="http://blogs.msdn.com/aggbug.aspx?PostID=1552802" width="1" height="1"&gt;</description><category domain="http://blogs.msdn.com/wesdyer/archive/tags/C_2300_/default.aspx">C#</category><category domain="http://blogs.msdn.com/wesdyer/archive/tags/Functional+Programming/default.aspx">Functional Programming</category></item><item><title>Function Memoization</title><link>http://blogs.msdn.com/wesdyer/archive/2007/01/26/function-memoization.aspx</link><pubDate>Fri, 26 Jan 2007 04:44:00 GMT</pubDate><guid isPermaLink="false">91d46819-8472-40ad-a661-2c78acb4018c:1533238</guid><dc:creator>wesdyer</dc:creator><slash:comments>17</slash:comments><comments>http://blogs.msdn.com/wesdyer/comments/1533238.aspx</comments><wfw:commentRss>http://blogs.msdn.com/wesdyer/commentrss.aspx?PostID=1533238</wfw:commentRss><description>&lt;P&gt;One of my favorite pastimes is playing games.&amp;nbsp; No not XBox 360, PS3, or Wii games nor other computer games, but board games, card games, and other such games.&amp;nbsp; It's probably because I'm from a large family - I have 8 siblings - and we would often spend time together playing games.&amp;nbsp; It is a good way to accommodate a wide variety of interests, skills, and aptitudes.&amp;nbsp; Some of my favorite games&amp;nbsp;are &lt;A href="http://en.wikipedia.org/wiki/Settlers_of_Catan" mce_href="http://en.wikipedia.org/wiki/Settlers_of_Catan"&gt;Settlers of Catan&lt;/A&gt;, &lt;A href="http://en.wikipedia.org/wiki/Carcassonne_%28board_game%29" mce_href="http://en.wikipedia.org/wiki/Carcassonne_%28board_game%29"&gt;Carcassonne&lt;/A&gt;, &lt;A href="http://en.wikipedia.org/wiki/Spades_%28card_game%29" mce_href="http://en.wikipedia.org/wiki/Spades_%28card_game%29"&gt;Spades&lt;/A&gt;, &lt;A href="http://en.wikipedia.org/wiki/Rook_%28card_game%29" mce_href="http://en.wikipedia.org/wiki/Rook_%28card_game%29"&gt;Rook&lt;/A&gt;, &lt;A href="http://en.wikipedia.org/wiki/Mafia_(game)" mce_href="http://en.wikipedia.org/wiki/Mafia_(game)"&gt;Mafia&lt;/A&gt;, &lt;A href="http://en.wikipedia.org/wiki/Scrabble_variants#Take_Two" mce_href="http://en.wikipedia.org/wiki/Scrabble_variants#Take_Two"&gt;Take Two&lt;/A&gt;, &lt;A href="http://en.wikipedia.org/wiki/Stratego" mce_href="http://en.wikipedia.org/wiki/Stratego"&gt;Stratego&lt;/A&gt;, &lt;A href="http://en.wikipedia.org/wiki/Ticket_to_Ride_%28board_game%29" mce_href="http://en.wikipedia.org/wiki/Ticket_to_Ride_%28board_game%29"&gt;Ticket to Ride&lt;/A&gt;,&amp;nbsp;and of course &lt;A href="http://en.wikipedia.org/wiki/Axis_and_allies" mce_href="http://en.wikipedia.org/wiki/Axis_and_allies"&gt;Axis and Allies&lt;/A&gt;.&lt;/P&gt;
&lt;P&gt;For my birthday this past year, I received an interesting&amp;nbsp;board game titled &lt;A href="http://en.wikipedia.org/wiki/Roborally" mce_href="http://en.wikipedia.org/wiki/Roborally"&gt;RoboRally&lt;/A&gt;.&amp;nbsp;&amp;nbsp;The premise of the game is there are a number of robots in a factory and they are bored, so they begin to indulge themselves by competing in races around the factory floor.&amp;nbsp; Each player takes command of a robot and seeks to win these competitions by controlling the robot.&amp;nbsp; The players are dealt a number of &lt;EM&gt;instruction&lt;/EM&gt; cards whereupon each player elects five cards to load into his &lt;EM&gt;program registers&lt;/EM&gt;.&amp;nbsp; After all the players have programmed their robots, their programs are executed somewhat simultaneously.&amp;nbsp; The robots can interact with each other by shooting, pushing, or otherwise hampering each other's progress.&amp;nbsp; But the real catch is that the board also interacts with the robots by way of conveyer belts, lasers, pushers, gears, pits, etc.&amp;nbsp; The uncertainty caused by the sheer number of interactions coupled with the deterministic behavior of programmed robots creates pandemonium.&lt;/P&gt;
&lt;P&gt;One day I was just itching to write some code so I thought why not implement a &lt;A href="http://botsnscouts.sourceforge.net/" mce_href="http://botsnscouts.sourceforge.net/"&gt;computer version&lt;/A&gt; of RoboRally.&amp;nbsp;&amp;nbsp;I thought that it&amp;nbsp;would be particularly fun because of the number of interacting objects&amp;nbsp;and the amount of state that is involved.&amp;nbsp; So I began to code away on a board editor.&amp;nbsp; This took a little bit of time mostly because I'm not very skilled at graphic art.&amp;nbsp; &lt;EM&gt;Here is a screenshot from an early version of the board editor.&lt;/EM&gt;&lt;/P&gt;
&lt;P&gt;&lt;A href="http://blogs.msdn.com/blogfiles/wesdyer/WindowsLiveWriter/MemoizationandImprovingtheSingletonPatte_A66F/image%7B0%7D%5B1%5D.png" mce_href="http://blogs.msdn.com/blogfiles/wesdyer/WindowsLiveWriter/MemoizationandImprovingtheSingletonPatte_A66F/image%7B0%7D%5B1%5D.png" atomicselection="true"&gt;&lt;/A&gt;&lt;A href="http://blogs.msdn.com/blogfiles/wesdyer/WindowsLiveWriter/MemoizationandImprovingtheSingletonPatte_A66F/image%7B0%7D%5B3%5D.png" mce_href="http://blogs.msdn.com/blogfiles/wesdyer/WindowsLiveWriter/MemoizationandImprovingtheSingletonPatte_A66F/image%7B0%7D%5B3%5D.png" atomicselection="true"&gt;&lt;IMG style="BORDER-RIGHT: 0px; BORDER-TOP: 0px; BORDER-LEFT: 0px; BORDER-BOTTOM: 0px" height=191 src="http://blogs.msdn.com/blogfiles/wesdyer/WindowsLiveWriter/MemoizationandImprovingtheSingletonPatte_A66F/image%7B0%7D%5B2%5D.png" width=240 border=0 mce_src="http://blogs.msdn.com/blogfiles/wesdyer/WindowsLiveWriter/MemoizationandImprovingtheSingletonPatte_A66F/image%7B0%7D%5B2%5D.png"&gt;&lt;/A&gt; &lt;/P&gt;
&lt;P&gt;The code for the editor consists of three assemblies: the windows application, a game engine, and a functional programming library.&amp;nbsp; This was one of the first non-trivial apps that I wrote using C# 3.0 and it was very fun to use the new language features.&amp;nbsp; In fact, it was incredible because I found that many &lt;A href="http://en.wikipedia.org/wiki/Design_patterns" mce_href="http://en.wikipedia.org/wiki/Design_patterns"&gt;design patterns&lt;/A&gt; that I commonly used changed drastically or were no longer needed.&amp;nbsp; Furthermore, I found that entirely new designs were possible.&amp;nbsp; Today, I will touch on just one of these design patterns and the underlying principle used in it.&lt;/P&gt;
&lt;P&gt;The game engine has an class called &lt;EM&gt;Board&lt;/EM&gt; and these boards&amp;nbsp;are composed of many &lt;EM&gt;Tiles &lt;/EM&gt;which are each associated with a &lt;EM&gt;Location&lt;/EM&gt;.&amp;nbsp; Tiles can be simple or rather complex.&amp;nbsp; For instance, there are blank tiles and there are move left express conveyer belt tiles.&amp;nbsp; But there are also gear tiles with a normal wall on the top side and a laser wall on the left side which also have a flag on the tile.&amp;nbsp; I made a design decision early on to have basic tiles and decorator tiles.&amp;nbsp; So complex tiles are formed from&amp;nbsp;the composition of a basic tile and any number of &lt;A href="http://en.wikipedia.org/wiki/Decorator_pattern" mce_href="http://en.wikipedia.org/wiki/Decorator_pattern"&gt;decorator&lt;/A&gt; tiles.&amp;nbsp; I&amp;nbsp;wrote a&amp;nbsp;factory which creates either some basic tile or some decorator tile.&amp;nbsp; For a first cut, I didn't worry that I created an overabundance of blank tiles even if they are all identical.&amp;nbsp; Nor did I worry about the fact that all move right conveyer tiles are the same.&amp;nbsp; However, later as I was refining the design I came back to the factory and wanted to improve it by reducing the number of tiles that were created to the bare minimum.&amp;nbsp; A typical solution to this problem for the blank tiles would look like this:&lt;/P&gt;
&lt;BLOCKQUOTE&gt;
&lt;P&gt;&lt;FONT face="Courier New"&gt;IBlankTile blankTile;&lt;BR&gt;public IBlankTile CreateBlankTile()&lt;BR&gt;{&lt;BR&gt;&amp;nbsp; if (blankTile == null)&lt;BR&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; blankTile = new BlankTile();&lt;BR&gt;&amp;nbsp; return blankTile;&lt;BR&gt;}&lt;/FONT&gt;&lt;/P&gt;&lt;/BLOCKQUOTE&gt;
&lt;P&gt;But how do we do this for conveyer tiles? 
&lt;BLOCKQUOTE&gt;
&lt;P&gt;&lt;FONT face="Courier New"&gt;Dictionary&amp;lt;Direction, IConveyerTile&amp;gt; conveyerTiles = new Dictionary&amp;lt;Direction, IConveyerTile&amp;gt;();&lt;BR&gt;public IConveyerTile CreateConveyerTile(Direction direction)&lt;BR&gt;{&lt;BR&gt;&amp;nbsp; IConveyerTile result;&lt;BR&gt;&amp;nbsp; if (!conveyerTiles.TryGetValue(direction, out result))&lt;BR&gt;&amp;nbsp; {&lt;BR&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; result = new ConveyerTile(direction);&lt;BR&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; conveyerTiles.Add(direction, result);&lt;BR&gt;&amp;nbsp; }&lt;BR&gt;&amp;nbsp; return result;&lt;BR&gt;}&lt;/FONT&gt;&lt;/P&gt;&lt;/BLOCKQUOTE&gt;
&lt;P&gt;Ick!&amp;nbsp; It only gets even more complicated for tiles that are parameterized on more items.&amp;nbsp; Furthermore, it seems that there is a lot of repetition going on.&amp;nbsp; Specifically, all of the machinery to track instance existence and creation is being duplicated for each tile type.&amp;nbsp; To some extent the &lt;A href="http://en.wikipedia.org/wiki/Singleton_pattern" mce_href="http://en.wikipedia.org/wiki/Singleton_pattern"&gt;Singleton&lt;/A&gt; and &lt;A href="http://en.wikipedia.org/wiki/Multiton" mce_href="http://en.wikipedia.org/wiki/Multiton"&gt;Multiton&lt;/A&gt; patterns also suffer from the same problem.&amp;nbsp; There must be a better way. 
&lt;P&gt;In fact, there is a better way.&amp;nbsp; What we really want here is a function that returns the same value each time it is applied to the same parameter values.&amp;nbsp; Functional programmers will instantly recognize this as &lt;A href="http://en.wikipedia.org/wiki/Memoization" mce_href="http://en.wikipedia.org/wiki/Memoization"&gt;function memoization&lt;/A&gt;. 
&lt;P&gt;Memoization can be implemented as a function which takes a function as a parameter and returns a new function which when invoked the first time on some set of parameters will compute the result and when invoked with the same values will not recompute the result but will instead return the previously computed result. 
&lt;P&gt;Now let's see how our code would have looked if we had a static method called &lt;EM&gt;Memoize&lt;/EM&gt; is a functional library called &lt;EM&gt;Fun &lt;/EM&gt;(why not? functional programming is fun isn't it?). 
&lt;BLOCKQUOTE&gt;
&lt;P&gt;&lt;FONT face="Courier New"&gt;public readonly Func&amp;lt;IBlankTile&amp;gt; CreateBlankTile = Fun.Memoize(() =&amp;gt; new BlankTile());&lt;BR&gt;public readonly Func&amp;lt;Direction,IConveyerTile&amp;gt; CreateConveyerTile = Fun.Memoize(dir =&amp;gt; new ConveyerTile(dir));&lt;/FONT&gt;&lt;/P&gt;&lt;/BLOCKQUOTE&gt;
&lt;P&gt;The new code is beautiful and doesn't have all of the redundancy and complexity of the old code.&amp;nbsp; This is a very practical example of the modularity of functional style code that &lt;A href="http://blogs.msdn.com/wesdyer/archive/2007/01/18/why-functional-programming-is-important-in-a-mixed-environment.aspx" mce_href="http://blogs.msdn.com/wesdyer/archive/2007/01/18/why-functional-programming-is-important-in-a-mixed-environment.aspx"&gt;I referred to previously&lt;/A&gt;. 
&lt;P&gt;"But wait", you say, "how exactly does the magic happen?"&amp;nbsp; Well, let's take a look.&amp;nbsp; First, let's examine a memoize function which takes a function of no arguments and returns a memoized version of that function. 
&lt;BLOCKQUOTE&gt;
&lt;P&gt;&lt;FONT face="Courier New"&gt;&lt;FONT color=#0000ff&gt;&lt;/FONT&gt;&lt;/FONT&gt;
&lt;P&gt;&lt;FONT face="Courier New"&gt;public static Func&amp;lt;R&amp;gt; Memoize&amp;lt;R&amp;gt;(this Func&amp;lt;R&amp;gt; f)&lt;BR&gt;{&lt;BR&gt;&amp;nbsp; R value = default(R);&lt;BR&gt;&amp;nbsp; bool hasValue = false;&lt;BR&gt;&amp;nbsp; return () =&amp;gt;&lt;BR&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; {&lt;BR&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; if (!hasValue)&lt;BR&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; {&lt;BR&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; hasValue = true;&lt;BR&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; value = f();&lt;BR&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; }&lt;BR&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; return value;&lt;BR&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; };&lt;BR&gt;}&lt;/FONT&gt;&lt;/P&gt;&lt;/BLOCKQUOTE&gt;
&lt;P&gt;Memoize takes a function which has no arguments and a return type of R and returns a function with the same signature.&amp;nbsp; When Memoize is called it creates two local variables &lt;EM&gt;value &lt;/EM&gt;and &lt;EM&gt;hasValue&lt;/EM&gt;. Memoize then returns a new function that returns &lt;EM&gt;value&lt;/EM&gt; if &lt;EM&gt;hasValue &lt;/EM&gt;is true otherwise it computes &lt;EM&gt;value&lt;/EM&gt; by evaluating the&amp;nbsp;parameter &lt;EM&gt;f&lt;/EM&gt;, sets &lt;EM&gt;hasValue&lt;/EM&gt; to true,&amp;nbsp;and then returns &lt;EM&gt;value&lt;/EM&gt;.&amp;nbsp; Notice that the function that is returned from Memoize accesses &lt;EM&gt;hasValue, value, &lt;/EM&gt;and &lt;EM&gt;f&lt;/EM&gt;.&amp;nbsp; These three variables are local to Memoize.&amp;nbsp; The three variables together with a reference to the function that is created by Memoize form a &lt;A href="http://en.wikipedia.org/wiki/Closure_%28computer_science%29" mce_href="http://en.wikipedia.org/wiki/Closure_%28computer_science%29"&gt;closure&lt;/A&gt;. 
&lt;P&gt;So what happens when we invoke the function returned from Memoize for the first time?&amp;nbsp; The variable &lt;EM&gt;hasValue&lt;/EM&gt; will be set to false, so we will set &lt;EM&gt;hasValue &lt;/EM&gt;to true and then apply &lt;EM&gt;f&lt;/EM&gt; saving the result to &lt;EM&gt;value&lt;/EM&gt;.&amp;nbsp; Finally, we will return the &lt;EM&gt;value&lt;/EM&gt; which is the result of &lt;EM&gt;f&lt;/EM&gt;.&amp;nbsp; So the memoized function will return the same thing that &lt;EM&gt;f&lt;/EM&gt; would have returned on its first invocation. 
&lt;P&gt;But what about on subsequent invocations?&amp;nbsp; When we call memoized function&amp;nbsp;again, &lt;EM&gt;hasValue&lt;/EM&gt; will be true so we will simply return &lt;EM&gt;value&lt;/EM&gt; without recomputing it.&amp;nbsp; So the memoized function will always return the same value as it did on the first invocation without recomputing the result through &lt;EM&gt;f&lt;/EM&gt;. 
&lt;P&gt;This has subtle implications such as if &lt;EM&gt;f&lt;/EM&gt; has side effects then those side effects will only occur when we apply the memoized function the first time.&amp;nbsp; So we need to be careful about using it.&amp;nbsp; But consider how CreateBlankTile used Memoize.&amp;nbsp; When CreateBlankTile is run the first time, it will create a blank tile and then return the result, but on subsequent invocations it will continue to return the same blank tile.&amp;nbsp; This is exactly the behavior that we want. 
&lt;P&gt;Can we do the same thing for functions that have arguments?&amp;nbsp; Absolutely, let's take a look at how to Memoize functions of one argument. 
&lt;BLOCKQUOTE&gt;
&lt;P&gt;&lt;FONT face="Courier New"&gt;public static Func&amp;lt;A, R&amp;gt; Memoize&amp;lt;A, R&amp;gt;(this Func&amp;lt;A, R&amp;gt; f)&lt;BR&gt;{&lt;BR&gt;&amp;nbsp; var map = new Dictionary&amp;lt;A, R&amp;gt;();&lt;BR&gt;&amp;nbsp; return a =&amp;gt;&lt;BR&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; {&lt;BR&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; R value;&lt;BR&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; if (map.TryGetValue(a, out value))&lt;BR&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; return value;&lt;BR&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; value = f(a);&lt;BR&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; map.Add(a, value);&lt;BR&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; return value;&lt;BR&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; };&lt;BR&gt;}&lt;/FONT&gt;&lt;/P&gt;&lt;/BLOCKQUOTE&gt;
&lt;P&gt;This time instead of storing the computed values in a local variable directly, we store them in a dictionary and instead of marking that we have computed the value we just check for existence in the dictionary.&amp;nbsp; This can be generalized to functions of n arguments by creating composite keys of n fields that are used in the dictionary. 
&lt;P&gt;Consider how this Memoize function works with CreateConveyerTile.&amp;nbsp; When we invoke it with some direction for the first time then it will not find that direction in the dictionary and so it will create a new conveyer tile parameterized on that direction and then store it in the dictionary.&amp;nbsp; Subsequent calls with the same direction will not create new tiles but instead grab out the existing one from the dictionary.&amp;nbsp; Again this is the behavior that we want.&amp;nbsp; Furthermore, all of the mechanics of storing and fetching tiles are located in Memoize instead of CreateBlankTile or CreateConveyerTile. 
&lt;P&gt;Memoize is also useful for the improving performance of &lt;A href="http://en.wikipedia.org/wiki/Recursion" mce_href="http://en.wikipedia.org/wiki/Recursion"&gt;recursive functions&lt;/A&gt;.&amp;nbsp; Eric Lippert has a &lt;A href="http://blogs.msdn.com/ericlippert/archive/2004/05/19/135392.aspx" mce_href="http://blogs.msdn.com/ericlippert/archive/2004/05/19/135392.aspx"&gt;great post&lt;/A&gt; about how not to teach recursion where he specifically mentions not to use fibonacci numbers.&amp;nbsp; However, I'm going to use &lt;A href="http://en.wikipedia.org/wiki/Fibonacci_numbers" mce_href="http://en.wikipedia.org/wiki/Fibonacci_numbers"&gt;fibonacci numbers&lt;/A&gt; not to teach recursion but to show how to improve the performance of recursive functions.&amp;nbsp; Recall, that the definition of the nth fibonacci number where n &amp;gt;= 0 is: 
&lt;BLOCKQUOTE&gt;
&lt;P&gt;&lt;FONT face="Courier New"&gt;fib(0) = 0&lt;/FONT&gt; 
&lt;P&gt;&lt;FONT face="Courier New"&gt;fib(1) = 1&lt;/FONT&gt; 
&lt;P&gt;&lt;FONT face="Courier New"&gt;fib(n) = fib(n - 1) + fib(n - 2) if n &amp;gt; 1&lt;/FONT&gt;&lt;/P&gt;&lt;/BLOCKQUOTE&gt;
&lt;P&gt;We can easily write a little function to do this: 
&lt;BLOCKQUOTE&gt;
&lt;P&gt;&lt;FONT face="Courier New"&gt;Func&amp;lt;int, int&amp;gt; fib = null;&lt;BR&gt;fib = n =&amp;gt; n &amp;gt; 1 ? fib(n - 1) + fib(n - 2) : n;&lt;/FONT&gt;&lt;/P&gt;&lt;/BLOCKQUOTE&gt;
&lt;P&gt;The problem is this function is very inefficient.&amp;nbsp; Consider calculating the 5th fibonacci number. 
&lt;BLOCKQUOTE&gt;
&lt;P&gt;&lt;FONT face="Courier New"&gt;fib(5)&lt;/FONT&gt; 
&lt;P&gt;&lt;FONT face="Courier New"&gt;&amp;nbsp; = fib(4) + fib(3)&lt;/FONT&gt; 
&lt;P&gt;&lt;FONT face="Courier New"&gt;&amp;nbsp; = fib(3) + fib(2) + fib(2) + fib(1)&lt;/FONT&gt; 
&lt;P&gt;&lt;FONT face="Courier New"&gt;&amp;nbsp; = fib(2) + fib(1) + fib(1) + fib(0) + fib(1) + fib(0) + 1&lt;/FONT&gt; 
&lt;P&gt;&lt;FONT face="Courier New"&gt;&amp;nbsp; = fib(1) + fib(0) + 1 + 1 + 0 + 1 + 0 + 1&lt;/FONT&gt; 
&lt;P&gt;&lt;FONT face="Courier New"&gt;&amp;nbsp; = 1 + 0 + 1 + 1 + 0 + 1 + 0&amp;nbsp;+ 1&lt;/FONT&gt; 
&lt;P&gt;&lt;FONT face="Courier New"&gt;&amp;nbsp; = 5&lt;/FONT&gt;&lt;/P&gt;&lt;/BLOCKQUOTE&gt;
&lt;P&gt;Notice how the computation branches out forming a &lt;A href="http://en.wikipedia.org/wiki/Tree_%28data_structure%29" mce_href="http://en.wikipedia.org/wiki/Tree_%28data_structure%29"&gt;tree&lt;/A&gt; of expansions.&amp;nbsp; In fact, the number of leaves in a tree for the computation of the nth fibonacci number is fib(n + 1) where the number of ones is fib(n) and the number of zeros is fib(n - 1). 
&lt;P&gt;So calculating fib(5) will cause fib to evaluated&amp;nbsp;twelve times (the sum of the fibonacci numbers from 0 to 5) but only six distinct calls will be made (fib(0), fib(1), ..., fib(5)).&amp;nbsp; The problem only gets worse because the fibonacci numbers grow very quickly.&amp;nbsp; Here are the first&amp;nbsp;20 fibonacci numbers: 
&lt;BLOCKQUOTE&gt;
&lt;P&gt;0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, 987, 1597, 2584, 4181&lt;/P&gt;&lt;/BLOCKQUOTE&gt;
&lt;P&gt;So&amp;nbsp;our straightforward recursive function for computing fibonacci numbers will be exponential in n.&amp;nbsp; Ouch!&amp;nbsp; But wait, we can Memoize fib so that if it calls fib again with the same argument then it will not recalculate but instead use the previous result.&amp;nbsp; This will move our exponential function to a linear one at the cost of linear space to store the previous results (we could possibly use a weak reference hash map instead to solve problems with space if they existed).&amp;nbsp; In fact, subsequent calls to fib with previously computed values will be evaluated in constant time.&lt;/P&gt;
&lt;BLOCKQUOTE&gt;
&lt;P&gt;&lt;FONT face="Courier New"&gt;Func&amp;lt;int, int&amp;gt; fib = null;&lt;BR&gt;fib = n =&amp;gt; n &amp;gt; 1 ? fib(n - 1) + fib(n - 2) : n;&lt;BR&gt;fib = fib.Memoize();&lt;/FONT&gt;&lt;/P&gt;&lt;/BLOCKQUOTE&gt;
&lt;P&gt;If you want, you can add a Console.WriteLine to show when the evaluations happen to both versions and compare.&amp;nbsp; It is very enlightening.&lt;/P&gt;
&lt;P&gt;Memoize is turning into quite the useful function.&amp;nbsp; We have used it to solve parameterized identity creation problems and performance issues.&amp;nbsp; Later, we will see other ways we can use Memoize to solve design problems.&lt;/P&gt;&lt;img src="http://blogs.msdn.com/aggbug.aspx?PostID=1533238" width="1" height="1"&gt;</description><category domain="http://blogs.msdn.com/wesdyer/archive/tags/C_2300_/default.aspx">C#</category><category domain="http://blogs.msdn.com/wesdyer/archive/tags/Functional+Programming/default.aspx">Functional Programming</category></item><item><title>Video on Linq Queries and Delayed Evaluation</title><link>http://blogs.msdn.com/wesdyer/archive/2007/01/25/video-on-linq-queries-and-delayed-evaluation.aspx</link><pubDate>Thu, 25 Jan 2007 22:32:00 GMT</pubDate><guid isPermaLink="false">91d46819-8472-40ad-a661-2c78acb4018c:1531234</guid><dc:creator>wesdyer</dc:creator><slash:comments>11</slash:comments><comments>http://blogs.msdn.com/wesdyer/comments/1531234.aspx</comments><wfw:commentRss>http://blogs.msdn.com/wesdyer/commentrss.aspx?PostID=1531234</wfw:commentRss><description>&lt;P&gt;I recently recorded a video with &lt;A href="http://blogs.msdn.com/charlie/" mce_href="http://blogs.msdn.com/charlie/"&gt;Charlie Calvert&lt;/A&gt; about &lt;A href="http://blogs.msdn.com/wesdyer/archive/2007/01/09/about-queries.aspx" mce_href="http://blogs.msdn.com/wesdyer/archive/2007/01/09/about-queries.aspx"&gt;Linq queries&lt;/A&gt; and &lt;A href="http://blogs.msdn.com/wesdyer/archive/2007/01/03/how-linq-to-objects-queries-work.aspx" mce_href="http://blogs.msdn.com/wesdyer/archive/2007/01/03/how-linq-to-objects-queries-work.aspx"&gt;delayed evaluation&lt;/A&gt;.&amp;nbsp; You can find it &lt;A href="http://wm.microsoft.com/ms/msdn/visualcsharp/wes_dyer_2007_01/WesDyer_0002.wmv" mce_href="http://wm.microsoft.com/ms/msdn/visualcsharp/wes_dyer_2007_01/WesDyer_0002.wmv"&gt;here&lt;/A&gt;&amp;nbsp;(streaming video).&lt;/P&gt;
&lt;P&gt;&amp;nbsp;&lt;A class="" title="Download it here." href="http://download.microsoft.com/download/4/c/a/4cafaeb6-30aa-42f4-bae9-cd1a92e9789d/WesDyer_0002.zip" mce_href="http://download.microsoft.com/download/4/c/a/4cafaeb6-30aa-42f4-bae9-cd1a92e9789d/WesDyer_0002.zip"&gt;Download it here.&lt;/A&gt;&lt;/P&gt;&lt;img src="http://blogs.msdn.com/aggbug.aspx?PostID=1531234" width="1" height="1"&gt;</description><category domain="http://blogs.msdn.com/wesdyer/archive/tags/C_2300_/default.aspx">C#</category><category domain="http://blogs.msdn.com/wesdyer/archive/tags/Queries/default.aspx">Queries</category></item><item><title>About Queries</title><link>http://blogs.msdn.com/wesdyer/archive/2007/01/09/about-queries.aspx</link><pubDate>Wed, 10 Jan 2007 00:14:33 GMT</pubDate><guid isPermaLink="false">91d46819-8472-40ad-a661-2c78acb4018c:1440355</guid><dc:creator>wesdyer</dc:creator><slash:comments>5</slash:comments><comments>http://blogs.msdn.com/wesdyer/comments/1440355.aspx</comments><wfw:commentRss>http://blogs.msdn.com/wesdyer/commentrss.aspx?PostID=1440355</wfw:commentRss><description>&lt;p&gt;This&amp;nbsp;concludes my series of posts about queries.&amp;nbsp; I will still discuss them occassionally and if anyone has any specific questions then I would be very glad to address them.&lt;/p&gt; &lt;p&gt;&lt;strong&gt;Query Expression Posts&lt;/strong&gt;&lt;/p&gt; &lt;p&gt;1. &lt;a href="http://blogs.msdn.com/wesdyer/archive/2006/12/21/comprehending-comprehensions.aspx"&gt;Comprehending Comprehensions&lt;/a&gt;&lt;/p&gt; &lt;blockquote&gt; &lt;p&gt;What are queries?&amp;nbsp; How are queries treated by the compiler?&amp;nbsp; &lt;/p&gt;&lt;/blockquote&gt; &lt;p&gt;2.&amp;nbsp;&lt;a href="http://blogs.msdn.com/wesdyer/archive/2006/12/22/transparent-identifiers.aspx"&gt;Transparent Identifiers&lt;/a&gt;&lt;/p&gt; &lt;blockquote&gt; &lt;p&gt;How are local variables introduced by queries?&lt;/p&gt;&lt;/blockquote&gt; &lt;p&gt;3.&amp;nbsp; &lt;a href="http://blogs.msdn.com/wesdyer/archive/2006/12/22/thus-quoth-the-humble-programmer.aspx"&gt;Thus Quoth the Humble Programmer&lt;/a&gt;&lt;/p&gt; &lt;blockquote&gt; &lt;p&gt;What are expression trees?&amp;nbsp; What are lambdas translated into?&lt;/p&gt;&lt;/blockquote&gt; &lt;p&gt;4. &amp;nbsp;&lt;a href="http://blogs.msdn.com/wesdyer/archive/2006/12/26/reading-and-writing-queries.aspx"&gt;Reading and Writing Queries&lt;/a&gt;s&lt;/p&gt; &lt;blockquote&gt; &lt;p&gt;What mental models are useful in reading and writing query expressions?&amp;nbsp; What are the scoping rules for queries?&lt;/p&gt;&lt;/blockquote&gt; &lt;p&gt;5. &amp;nbsp;&lt;a href="http://blogs.msdn.com/wesdyer/archive/2006/12/26/a-model-for-query-interpretation.aspx"&gt;A Model for Query Interpretation&lt;/a&gt;&lt;/p&gt; &lt;blockquote&gt; &lt;p&gt;How can we think about query evaluation?&amp;nbsp; Is it possible to think of queries in terms of the queries and&amp;nbsp;not&amp;nbsp;the rewrites?&amp;nbsp; What is the conceptual model for Linq to Objects queries?&lt;/p&gt;&lt;/blockquote&gt; &lt;p&gt;6.&amp;nbsp; &lt;a href="http://blogs.msdn.com/wesdyer/archive/2007/01/03/how-linq-to-objects-queries-work.aspx"&gt;How Linq to Objects Queries Work&lt;/a&gt;&lt;/p&gt; &lt;blockquote&gt; &lt;p&gt;What causes Linq to Objects queries to be lazily evaluated?&amp;nbsp; How are the results computed?&amp;nbsp; What underlies the conceptual model for Linq to Objects?&amp;nbsp; Why do queries exhibit their debugging behavior?&lt;/p&gt;&lt;/blockquote&gt; &lt;p&gt;7.&amp;nbsp; &lt;a href="http://blogs.msdn.com/wesdyer/archive/2007/01/04/having-trouble-with-queries.aspx"&gt;Having Trouble with Queries&lt;/a&gt;&lt;/p&gt; &lt;blockquote&gt; &lt;p&gt;What constitutes good error messages?&amp;nbsp; How are effective error messages for queries generated in the face of type inference and significant syntactic sugar?&lt;/p&gt;&lt;/blockquote&gt; &lt;p&gt;8.&amp;nbsp; &lt;a href="http://blogs.msdn.com/wesdyer/archive/2007/01/08/another-model-for-query-interpretation.aspx"&gt;Another Model for Query Interpretation&lt;/a&gt;&lt;/p&gt; &lt;blockquote&gt; &lt;p&gt;Are there other models for query interpretation besides an imperative one?&amp;nbsp; Why are some queries declarative and others not?&lt;/p&gt;&lt;/blockquote&gt;&lt;img src="http://blogs.msdn.com/aggbug.aspx?PostID=1440355" width="1" height="1"&gt;</description><category domain="http://blogs.msdn.com/wesdyer/archive/tags/C_2300_/default.aspx">C#</category><category domain="http://blogs.msdn.com/wesdyer/archive/tags/Queries/default.aspx">Queries</category></item></channel></rss>