<?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 : Functional Programming</title><link>http://blogs.msdn.com/wesdyer/archive/tags/Functional+Programming/default.aspx</link><description>Tags: Functional Programming</description><dc:language>en-US</dc:language><generator>CommunityServer 2.1 SP1 (Build: 61025.2)</generator><item><title>The Marvels of Monads</title><link>http://blogs.msdn.com/wesdyer/archive/2008/01/11/the-marvels-of-monads.aspx</link><pubDate>Fri, 11 Jan 2008 03:06:13 GMT</pubDate><guid isPermaLink="false">91d46819-8472-40ad-a661-2c78acb4018c:7064392</guid><dc:creator>wesdyer</dc:creator><slash:comments>35</slash:comments><comments>http://blogs.msdn.com/wesdyer/comments/7064392.aspx</comments><wfw:commentRss>http://blogs.msdn.com/wesdyer/commentrss.aspx?PostID=7064392</wfw:commentRss><description>&lt;p&gt;If the word &lt;a href="http://blogs.msdn.com/wesdyer/archive/2007/12/22/continuation-passing-style.aspx"&gt;&amp;quot;continuation&amp;quot;&lt;/a&gt; causes eyes to glaze over, then the word &amp;quot;monad&amp;quot; induces mental paralysis.&amp;#160; Perhaps, this is why some have begun inventing more benign names for monads.&lt;/p&gt;  &lt;p&gt;These days, monads are the celebrities of programming language theory.&amp;#160; They gloss the cover of blogs and have been &lt;a href="http://www.loria.fr/~kow/monads/index.html"&gt;compared to everything&lt;/a&gt; from &lt;a href="http://www.haskell.org/haskellwiki/Monads_as_containers"&gt;boxes of fruit&lt;/a&gt; to &lt;a href="http://www.haskell.org/haskellwiki/Meet_Bob_The_Monadic_Lover"&gt;love affairs&lt;/a&gt;.&amp;#160; Nerds everywhere are exclaiming that the experience of understanding monads causes a &lt;a href="http://groups.google.com/group/comp.lang.functional/browse_thread/thread/346dd6767ecb3851"&gt;pleasantly&lt;/a&gt; &lt;a href="http://koweycode.blogspot.com/2006/08/does-haskell-hurt-your-brain.html"&gt;painful&lt;/a&gt; &lt;a href="http://lambda-the-ultimate.org/node/724"&gt;mental sensation&lt;/a&gt;.&lt;/p&gt;  &lt;p&gt;Like continuations, monads are simpler than they sound and are very useful in many situations.&amp;#160; In fact, programmers write code in a variety of languages that implicitly use common monads without even breaking a sweat.&lt;/p&gt;  &lt;p&gt;&lt;a href="http://lambda-the-ultimate.org/node/92"&gt;With&lt;/a&gt; &lt;a href="http://james-iry.blogspot.com/2007/09/monads-are-elephants-part-1.html"&gt;all&lt;/a&gt; &lt;a href="http://www.haskell.org/tutorial/monads.html"&gt;of&lt;/a&gt; &lt;a href="http://moonbase.rydia.net/mental/writings/programming/monads-in-ruby/00introduction.html"&gt;the&lt;/a&gt; &lt;a href="http://sigfpe.blogspot.com/2006/08/you-could-have-invented-monads-and.html"&gt;attention&lt;/a&gt; &lt;a href="http://www.alpheccar.org/en/posts/show/60"&gt;that&lt;/a&gt; &lt;a href="http://patryshev.com/monad/m-intro.html"&gt;monads&lt;/a&gt; &lt;a href="http://www.engr.mun.ca/~theo/Misc/haskell_and_monads.htm"&gt;get&lt;/a&gt;, why am I writing yet another explanation of monads?&amp;#160; Not to compare them to some everyday occurrence or to chronicle my journey to understanding.&amp;#160; I explain monads because I need monads.&amp;#160; They elegantly solve programming problems in a number of languages and contexts.&lt;/p&gt;  &lt;p&gt;&lt;strong&gt;Introducing Monads&lt;/strong&gt;&lt;/p&gt;  &lt;p&gt;&lt;a href="http://en.wikipedia.org/wiki/Monad_%28category_theory%29"&gt;Monads&lt;/a&gt; come from &lt;a href="http://en.wikipedia.org/wiki/Category_theory"&gt;category theory&lt;/a&gt;.&amp;#160; &lt;a href="http://www.disi.unige.it/person/MoggiE/ftp/ic91.pdf"&gt;Moggi introduced them&lt;/a&gt; to computer scientists to aid in the analysis of the semantics of computations.&amp;#160; In an excellent paper, &lt;em&gt;&lt;a href="http://coblitz.codeen.org:3125/citeseer.ist.psu.edu/cache/papers/cs/4583/http:zSzzSzcm.bell-labs.comzSzwhozSzwadlerzSztopicszSz..zSzpaperszSzessencezSzessence.pdf/wadler92essence.pdf"&gt;The Essence of Functional Programming&lt;/a&gt;&lt;/em&gt;, Wadler showed that monads are generally useful in computer programs to compose together functions which operate on amplified values rather than values.&amp;#160; &lt;a href="http://en.wikipedia.org/wiki/Monads_in_functional_programming"&gt;Monads&lt;/a&gt; became &lt;a href="http://www.haskell.org/all_about_monads/html/index.html"&gt;an important part&lt;/a&gt; of the programming language Haskell where they tackle &lt;a href="http://research.microsoft.com/~simonpj/papers/marktoberdorf/mark.pdf"&gt;the awkward squad&lt;/a&gt;: IO, concurrency, exceptions, and foreign-function calls.&lt;/p&gt;  &lt;p&gt;Monads enjoy tremendous success in Haskell, but like an actor who does well in a particular role, monads are now stereotyped in the minds of most programmers as useful only in pure lazy functional languages.&amp;#160; This is unfortunate, because monads are more broadly applicable.&lt;/p&gt;  &lt;p&gt;&lt;strong&gt;Controlling Complexity&lt;/strong&gt;&lt;/p&gt;  &lt;p&gt;Composition is the key to controlling complexity in software.&amp;#160; In &lt;em&gt;&lt;a href="http://mitpress.mit.edu/sicp/"&gt;The Structure and Interpretation of Computer Programs&lt;/a&gt;&lt;/em&gt;, Abelson and Sussman argue that composition beautifully expresses complex systems from simple patterns.&lt;/p&gt;  &lt;blockquote&gt;   &lt;p&gt;In our study of program design, we have seen that expert programmers control the complexity of their designs with the same general techniques used by designers of all complex systems. They combine primitive elements to form compound objects, they abstract compound objects to form higher-level building blocks, and they preserve modularity by adopting appropriate large-scale views of system structure.&lt;/p&gt; &lt;/blockquote&gt;  &lt;p&gt;One form of composition, function composition, succinctly describes the dependencies between function calls.&amp;#160; Function composition takes two functions and plumbs the result from the second function into the input of the first function, thereby forming one function.&lt;/p&gt;  &lt;blockquote&gt;   &lt;pre class="code"&gt;&lt;span style="color: blue"&gt;public static &lt;/span&gt;&lt;span style="color: #2b91af"&gt;Func&lt;/span&gt;&amp;lt;T, V&amp;gt; Compose&amp;lt;T, U, V&amp;gt;(&lt;span style="color: blue"&gt;this &lt;/span&gt;&lt;span style="color: #2b91af"&gt;Func&lt;/span&gt;&amp;lt;U, V&amp;gt; f, &lt;span style="color: #2b91af"&gt;Func&lt;/span&gt;&amp;lt;T, U&amp;gt; g)
{
    &lt;span style="color: blue"&gt;return &lt;/span&gt;x =&amp;gt; f(g(x));
}&lt;/pre&gt;
&lt;/blockquote&gt;
&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;

&lt;p&gt;For example, instead of applying &lt;em&gt;g&lt;/em&gt; to the value &lt;em&gt;x&lt;/em&gt; and then applying &lt;em&gt;f&lt;/em&gt; to the result, compose &lt;em&gt;f&lt;/em&gt; with &lt;em&gt;g&lt;/em&gt; and then apply the result to the value &lt;em&gt;x&lt;/em&gt;.&amp;#160; The key difference is the abstraction of the dependency between &lt;em&gt;f&lt;/em&gt; and &lt;em&gt;g&lt;/em&gt;.&lt;/p&gt;

&lt;blockquote&gt;
  &lt;pre class="code"&gt;&lt;span style="color: blue"&gt;var &lt;/span&gt;r = f(g(x));         &lt;font color="#008000"&gt;// without function composition&lt;/font&gt;
&lt;span style="color: blue"&gt;var &lt;/span&gt;r = f.Compose(g)(x); &lt;font color="#008000"&gt;// with function composition&lt;/font&gt;&lt;/pre&gt;
&lt;/blockquote&gt;
&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;

&lt;p&gt;Given the function &lt;em&gt;Identity&lt;/em&gt;, function composition must obey three laws.&lt;/p&gt;

&lt;blockquote&gt;
  &lt;pre class="code"&gt;&lt;span style="color: blue"&gt;public static &lt;/span&gt;T Identity&amp;lt;T&amp;gt;(&lt;span style="color: blue"&gt;this &lt;/span&gt;T value)
{
    &lt;span style="color: blue"&gt;return &lt;/span&gt;value;
}&lt;/pre&gt;
&lt;/blockquote&gt;

&lt;blockquote&gt;
  &lt;p&gt;&lt;strong&gt;1.&amp;#160; Left identity&lt;/strong&gt;&lt;/p&gt;

  &lt;p&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160; Identity.Compose(f) = f&lt;/p&gt;

  &lt;p&gt;&lt;strong&gt;2.&amp;#160; Right identity&lt;/strong&gt;&lt;/p&gt;

  &lt;p&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160; f.Compose(Identity) = f&lt;/p&gt;

  &lt;p&gt;&lt;strong&gt;3.&amp;#160; Associative&lt;/strong&gt;&lt;/p&gt;

  &lt;p&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160; f.Compose(g.Compose(h)) = (f.Compose(g)).Compose(h)&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;Often, values are not enough.&amp;#160; Constructed types amplify values.&amp;#160; The type &lt;em&gt;IEnumerable&amp;lt;T&amp;gt;&lt;/em&gt; represents a lazily computed list of values of type &lt;em&gt;T&lt;/em&gt;.&amp;#160; The type &lt;em&gt;Nullable&amp;lt;T&amp;gt;&lt;/em&gt; represents a possibly missing value of type &lt;em&gt;T&lt;/em&gt;.&amp;#160; The type &lt;em&gt;Func&amp;lt;Func&amp;lt;T, Answer&amp;gt;, Answer&amp;gt; &lt;/em&gt;represents a function, which returns an &lt;em&gt;Answer&lt;/em&gt; given a continuation, which takes a &lt;em&gt;T &lt;/em&gt;and returns an &lt;em&gt;Answer&lt;/em&gt;.&amp;#160; Each of these types amplifies the type &lt;em&gt;T&lt;/em&gt;.&lt;/p&gt;

&lt;p&gt;Suppose that instead of composing functions which return values, we compose functions which take values and return amplified values.&amp;#160; Let &lt;em&gt;M&amp;lt;T&amp;gt;&lt;/em&gt; denote the type of the amplified values.&lt;/p&gt;

&lt;blockquote&gt;
  &lt;pre class="code"&gt;&lt;span style="color: blue"&gt;public static &lt;/span&gt;&lt;span style="color: #2b91af"&gt;Func&lt;/span&gt;&amp;lt;T, &lt;span style="color: #2b91af"&gt;M&lt;/span&gt;&amp;lt;V&amp;gt;&amp;gt; Compose&amp;lt;T, U, V&amp;gt;(&lt;span style="color: blue"&gt;this &lt;/span&gt;&lt;span style="color: #2b91af"&gt;Func&lt;/span&gt;&amp;lt;U, &lt;span style="color: #2b91af"&gt;M&lt;/span&gt;&amp;lt;V&amp;gt;&amp;gt; f, &lt;span style="color: #2b91af"&gt;Func&lt;/span&gt;&amp;lt;T, &lt;span style="color: #2b91af"&gt;M&lt;/span&gt;&amp;lt;U&amp;gt;&amp;gt; g)
{
    &lt;span style="color: blue"&gt;return &lt;/span&gt;x =&amp;gt; f(g(x)); &lt;span style="color: green"&gt;// error, g(x) returns M&amp;lt;U&amp;gt; and f takes U
&lt;/span&gt;}&lt;/pre&gt;
&lt;/blockquote&gt;
&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;

&lt;p&gt;Function composition fails, because the return and input types do not match.&amp;#160; Composition with amplified values requires a function that accesses the underlying value and feeds it to the next function.&amp;#160; Call that function &amp;quot;Bind&amp;quot; and use it to define function composition.&lt;/p&gt;

&lt;blockquote&gt;
  &lt;pre class="code"&gt;&lt;span style="color: blue"&gt;public static &lt;/span&gt;&lt;span style="color: #2b91af"&gt;Func&lt;/span&gt;&amp;lt;T, &lt;span style="color: #2b91af"&gt;M&lt;/span&gt;&amp;lt;V&amp;gt;&amp;gt; Compose&amp;lt;T, U, V&amp;gt;(&lt;span style="color: blue"&gt;this &lt;/span&gt;&lt;span style="color: #2b91af"&gt;Func&lt;/span&gt;&amp;lt;U, &lt;span style="color: #2b91af"&gt;M&lt;/span&gt;&amp;lt;V&amp;gt;&amp;gt; f, &lt;span style="color: #2b91af"&gt;Func&lt;/span&gt;&amp;lt;T, &lt;span style="color: #2b91af"&gt;M&lt;/span&gt;&amp;lt;U&amp;gt;&amp;gt; g)
{
    &lt;span style="color: blue"&gt;return &lt;/span&gt;x =&amp;gt; Bind(g(x), f);
}&lt;/pre&gt;
&lt;/blockquote&gt;
&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;

&lt;p&gt;The input and output types determine the signature of &lt;em&gt;Bind.&lt;/em&gt;&amp;#160; Therefore, &lt;em&gt;Bind&lt;/em&gt; takes an amplified value, M&amp;lt;&lt;em&gt;U&amp;gt;,&lt;/em&gt; and a function from &lt;em&gt;U&lt;/em&gt;&amp;#160; to &lt;em&gt;M&amp;lt;V&amp;gt;&lt;/em&gt;, and returns an amplified value, &lt;em&gt;M&amp;lt;V&amp;gt;&lt;/em&gt;.&lt;/p&gt;

&lt;blockquote&gt;
  &lt;pre class="code"&gt;&lt;span style="color: blue"&gt;public static &lt;/span&gt;&lt;span style="color: #2b91af"&gt;M&lt;/span&gt;&amp;lt;V&amp;gt; Bind&amp;lt;U, V&amp;gt;(&lt;span style="color: blue"&gt;this &lt;/span&gt;&lt;span style="color: #2b91af"&gt;M&lt;/span&gt;&amp;lt;U&amp;gt; m, &lt;span style="color: #2b91af"&gt;Func&lt;/span&gt;&amp;lt;U, &lt;span style="color: #2b91af"&gt;M&lt;/span&gt;&amp;lt;V&amp;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;The body of &lt;em&gt;Bind&lt;/em&gt; depends on the mechanics of the amplified values, &lt;em&gt;M&amp;lt;T&amp;gt;&lt;/em&gt;.&amp;#160; Each amplified type will need a distinct definition of &lt;em&gt;Bind&lt;/em&gt;.&lt;/p&gt;

&lt;p&gt;In addition to &lt;em&gt;Bind&lt;/em&gt;, define a function which takes an unamplified value and amplifies it.&amp;#160; Call this function &amp;quot;Unit&amp;quot;.&lt;/p&gt;

&lt;blockquote&gt;
  &lt;pre class="code"&gt;&lt;span style="color: blue"&gt;public static &lt;/span&gt;&lt;span style="color: #2b91af"&gt;M&lt;/span&gt;&amp;lt;T&amp;gt; Unit&amp;lt;T&amp;gt;(&lt;span style="color: blue"&gt;this &lt;/span&gt;T value)&lt;/pre&gt;
&lt;/blockquote&gt;

&lt;p&gt;Together the amplified type, &lt;em&gt;M&amp;lt;T&amp;gt;&lt;/em&gt;, the function &lt;em&gt;Bind&lt;/em&gt;, and the function &lt;em&gt;Unit&lt;/em&gt; enable function composition with amplified values.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Meet the Monads&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Viola, we have invented monads.&lt;/p&gt;

&lt;p&gt;Monads are a triple consisting of a type, a &lt;em&gt;Unit&lt;/em&gt; function, and a &lt;em&gt;Bind&lt;/em&gt; function.&amp;#160; Furthermore, to be a monad, the triple must satisfy three laws:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;&lt;strong&gt;1.&amp;#160; Left Identity&lt;/strong&gt;&lt;/p&gt;

  &lt;p&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160; Bind(Unit(e), k) = k(e)&lt;/p&gt;

  &lt;p&gt;&lt;strong&gt;2.&amp;#160; Right Identity&lt;/strong&gt;&lt;/p&gt;

  &lt;p&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160; Bind(m, Unit) = m&lt;/p&gt;

  &lt;p&gt;&lt;strong&gt;3.&amp;#160; Associative&lt;/strong&gt;&lt;/p&gt;

  &lt;p&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160; Bind(m, x =&amp;gt; Bind(k(x), y =&amp;gt; h(y)) = Bind(Bind(m, x =&amp;gt; k(x)), y =&amp;gt; h(y))&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;The laws are similar to those of function composition.&amp;#160; This is not a coincidence.&amp;#160; They guarantee that the monad is well behaved and composition works properly.&lt;/p&gt;

&lt;p&gt;To define a particular monad, the writer supplies the triple, thereby specifying the mechanics of the amplified values.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;The Identity Monad&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;The simplest monad is the &lt;em&gt;Identity&lt;/em&gt; monad.&amp;#160; The type represents a wrapper containing a value.&lt;/p&gt;

&lt;blockquote&gt;
  &lt;pre class="code"&gt;&lt;span style="color: blue"&gt;class &lt;/span&gt;&lt;span style="color: #2b91af"&gt;Identity&lt;/span&gt;&amp;lt;T&amp;gt;
{
    &lt;span style="color: blue"&gt;public &lt;/span&gt;T Value { &lt;span style="color: blue"&gt;get&lt;/span&gt;; &lt;span style="color: blue"&gt;private set&lt;/span&gt;; }
    &lt;span style="color: blue"&gt;public &lt;/span&gt;Identity(T value) { &lt;span style="color: blue"&gt;this&lt;/span&gt;.Value = 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;The &lt;em&gt;Unit&lt;/em&gt; function takes a value and returns a new instance of &lt;em&gt;Identity&lt;/em&gt;, which wraps the value.&lt;/p&gt;

&lt;blockquote&gt;
  &lt;pre class="code"&gt;&lt;span style="color: blue"&gt;static &lt;/span&gt;&lt;span style="color: #2b91af"&gt;Identity&lt;/span&gt;&amp;lt;T&amp;gt; Unit&amp;lt;T&amp;gt;(T value)
{
    &lt;span style="color: blue"&gt;return new &lt;/span&gt;&lt;span style="color: #2b91af"&gt;Identity&lt;/span&gt;&amp;lt;T&amp;gt;(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;The bind function takes an instance of &lt;em&gt;Identity&lt;/em&gt;, unwraps the value, and invokes the delegate, &lt;em&gt;k&lt;/em&gt;, with the&lt;em&gt; &lt;/em&gt;unwrapped value.&amp;#160; The result is a new instance of &lt;em&gt;Identity&lt;/em&gt;. &lt;/p&gt;

&lt;blockquote&gt;
  &lt;pre class="code"&gt;&lt;span style="color: blue"&gt;static &lt;/span&gt;&lt;span style="color: #2b91af"&gt;Identity&lt;/span&gt;&amp;lt;U&amp;gt; Bind&amp;lt;T,U&amp;gt;(&lt;span style="color: #2b91af"&gt;Identity&lt;/span&gt;&amp;lt;T&amp;gt; id, &lt;span style="color: #2b91af"&gt;Func&lt;/span&gt;&amp;lt;T,&lt;span style="color: #2b91af"&gt;Identity&lt;/span&gt;&amp;lt;U&amp;gt;&amp;gt; k)
{
    &lt;span style="color: blue"&gt;return &lt;/span&gt;k(id.Value);
}&lt;/pre&gt;
&lt;/blockquote&gt;
&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;

&lt;p&gt;Consider a simple program that creates two &lt;em&gt;Identity &lt;/em&gt;wrappers and performs an operation on the wrapped values.&amp;#160; First, bind &lt;em&gt;x&lt;/em&gt; to the value within the wrapper containing the value five.&amp;#160; Then, bind &lt;em&gt;y &lt;/em&gt;to the value within the wrapper containing the value six.&amp;#160; Finally, add the values,&lt;em&gt; x&lt;/em&gt; and &lt;em&gt;y,&lt;/em&gt; together.&amp;#160; The result is an instance of &lt;em&gt;Identity&lt;/em&gt; wrapping the value eleven.&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;&lt;font face="Courier New"&gt;&lt;span style="color: blue"&gt;var &lt;/span&gt;r = Bind(Unit(5), x =&amp;gt; 

      &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; Bind(Unit(6), y =&amp;gt; 

      &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; Unit(x + y))); 

      &lt;br /&gt;

      &lt;br /&gt;&lt;span style="color: #2b91af"&gt;Console&lt;/span&gt;.WriteLine(r.Value);&lt;/font&gt;&lt;/p&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;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;

&lt;p&gt;While this works, it is rather clumsy.&amp;#160; It would be nice to have syntax for dealing with the monad.&amp;#160; Fortunately, we do.&lt;/p&gt;

&lt;p&gt;C# 3.0 introduced query comprehensions which are actually monad comprehensions in disguise.&amp;#160; We can rewrite the identity monad to use LINQ.&amp;#160; Perhaps, it should have been called LINM (Language INtegrated Monads), but it just doesn't have the same ring to it.&lt;/p&gt;

&lt;p&gt;Rename the method &lt;em&gt;Unit&lt;/em&gt; to &lt;em&gt;ToIdentity &lt;/em&gt;and &lt;em&gt;Bind&lt;/em&gt; to &lt;em&gt;SelectMany&lt;/em&gt;.&amp;#160; Then, make them both extension methods.&lt;/p&gt;

&lt;blockquote&gt;
  &lt;pre class="code"&gt;&lt;span style="color: blue"&gt;public static &lt;/span&gt;&lt;span style="color: #2b91af"&gt;Identity&lt;/span&gt;&amp;lt;T&amp;gt; ToIdentity&amp;lt;T&amp;gt;(&lt;span style="color: blue"&gt;this &lt;/span&gt;T value)
{
    &lt;span style="color: blue"&gt;return new &lt;/span&gt;&lt;span style="color: #2b91af"&gt;Identity&lt;/span&gt;&amp;lt;T&amp;gt;(value);
}

&lt;span style="color: blue"&gt;public static &lt;/span&gt;&lt;span style="color: #2b91af"&gt;Identity&lt;/span&gt;&amp;lt;U&amp;gt; SelectMany&amp;lt;T, U&amp;gt;(&lt;span style="color: blue"&gt;this &lt;/span&gt;&lt;span style="color: #2b91af"&gt;Identity&lt;/span&gt;&amp;lt;T&amp;gt; id, &lt;span style="color: #2b91af"&gt;Func&lt;/span&gt;&amp;lt;T, &lt;span style="color: #2b91af"&gt;Identity&lt;/span&gt;&amp;lt;U&amp;gt;&amp;gt; k)
{
    &lt;span style="color: blue"&gt;return &lt;/span&gt;k(id.Value);
}&lt;/pre&gt;
&lt;/blockquote&gt;
&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;

&lt;p&gt;The changes impact the calling code.&lt;/p&gt;

&lt;blockquote&gt;
  &lt;pre class="code"&gt;&lt;span style="color: blue"&gt;var &lt;/span&gt;r = 5.ToIdentity().SelectMany(
            x =&amp;gt; 6.ToIdentity().SelectMany(
                y =&amp;gt; (x + y).ToIdentity()));

&lt;span style="color: #2b91af"&gt;Console&lt;/span&gt;.WriteLine(r.Value);&lt;/pre&gt;
&lt;/blockquote&gt;
&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;

&lt;p&gt;Equivalent methods are part of the standard query operators defined for LINQ.&amp;#160; However, the standard query operators also include a slightly different version of &lt;em&gt;SelectMany&lt;/em&gt; for performance reasons.&amp;#160; It combines &lt;em&gt;Bind&lt;/em&gt; with &lt;em&gt;Unit&lt;/em&gt;, so that lambdas are not deeply nested.&amp;#160; The signature is the same except for an extra argument that is a delegate which takes two arguments and returns a value.&amp;#160; The delegate combines the two values together.&amp;#160; This version of &lt;em&gt;SelectMany&lt;/em&gt; binds &lt;em&gt;x &lt;/em&gt;to the wrapped value, applies &lt;em&gt;k&lt;/em&gt; to &lt;em&gt;x&lt;/em&gt;, binds the result to &lt;em&gt;y&lt;/em&gt;, and then applies the combining function, &lt;em&gt;s,&lt;/em&gt; to &lt;em&gt;x&lt;/em&gt; and &lt;em&gt;y.&amp;#160; &lt;/em&gt;The resultant value is wrapped and returned.&lt;/p&gt;

&lt;blockquote&gt;
  &lt;pre class="code"&gt;&lt;span style="color: blue"&gt;public static &lt;/span&gt;&lt;span style="color: #2b91af"&gt;Identity&lt;/span&gt;&amp;lt;V&amp;gt; SelectMany&amp;lt;T, U, V&amp;gt;(&lt;span style="color: blue"&gt;this &lt;/span&gt;&lt;span style="color: #2b91af"&gt;Identity&lt;/span&gt;&amp;lt;T&amp;gt; id, &lt;span style="color: #2b91af"&gt;Func&lt;/span&gt;&amp;lt;T, &lt;span style="color: #2b91af"&gt;Identity&lt;/span&gt;&amp;lt;U&amp;gt;&amp;gt; k, &lt;span style="color: #2b91af"&gt;Func&lt;/span&gt;&amp;lt;T,U,V&amp;gt; s)
{
    &lt;span style="color: blue"&gt;return &lt;/span&gt;id.SelectMany(x =&amp;gt; k(x).SelectMany(y =&amp;gt; s(x, y).ToIdentity()));
}&lt;/pre&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;/blockquote&gt;
&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;

&lt;p&gt;Of course, we can remove some of the code from the generalized solution by using our knowledge of the &lt;em&gt;Identity&lt;/em&gt; monad.&lt;/p&gt;

&lt;blockquote&gt;
  &lt;pre class="code"&gt;&lt;span style="color: blue"&gt;public static &lt;/span&gt;&lt;span style="color: #2b91af"&gt;Identity&lt;/span&gt;&amp;lt;V&amp;gt; SelectMany&amp;lt;T, U, V&amp;gt;(&lt;span style="color: blue"&gt;this &lt;/span&gt;&lt;span style="color: #2b91af"&gt;Identity&lt;/span&gt;&amp;lt;T&amp;gt; id, &lt;span style="color: #2b91af"&gt;Func&lt;/span&gt;&amp;lt;T, &lt;span style="color: #2b91af"&gt;Identity&lt;/span&gt;&amp;lt;U&amp;gt;&amp;gt; k, &lt;span style="color: #2b91af"&gt;Func&lt;/span&gt;&amp;lt;T,U,V&amp;gt; s)
{
    &lt;span style="color: blue"&gt;return &lt;/span&gt;s(id.Value, k(id.Value).Value).ToIdentity();
}&lt;/pre&gt;
&lt;/blockquote&gt;
&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;

&lt;p&gt;The call-site does not need to nest lambdas.&lt;/p&gt;

&lt;blockquote&gt;
  &lt;pre class="code"&gt;&lt;span style="color: blue"&gt;var &lt;/span&gt;r = 5.ToIdentity()
         .SelectMany(x =&amp;gt; 6.ToIdentity(), (x, y) =&amp;gt; x + y);

&lt;span style="color: #2b91af"&gt;Console&lt;/span&gt;.WriteLine(r.Value);&lt;/pre&gt;
&lt;/blockquote&gt;
&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;

&lt;p&gt;With the new definition of &lt;em&gt;SelectMany&lt;/em&gt;, programmers can use C#'s query comprehension syntax.&amp;#160; The &lt;em&gt;from &lt;/em&gt;notation binds the introduced variable to the value wrapped by the expression on the right.&amp;#160; This allows subsequent expressions to use the wrapped values without directly calling &lt;em&gt;SelectMany&lt;/em&gt;.&lt;/p&gt;

&lt;blockquote&gt;
  &lt;pre class="code"&gt;&lt;span style="color: blue"&gt;var &lt;/span&gt;r = &lt;span style="color: blue"&gt;from &lt;/span&gt;x &lt;span style="color: blue"&gt;in &lt;/span&gt;5.ToIdentity()
        &lt;span style="color: blue"&gt;from &lt;/span&gt;y &lt;span style="color: blue"&gt;in &lt;/span&gt;6.ToIdentity()
        &lt;span style="color: blue"&gt;select &lt;/span&gt;x + y;&lt;/pre&gt;
&lt;/blockquote&gt;
&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;

&lt;p&gt;Since the original &lt;em&gt;SelectMany&lt;/em&gt; definition corresponds directly to the monadic &lt;em&gt;Bind&lt;/em&gt; function and because the existence of a generalized transformation has been demonstrated, the remainder of the post will use the original signature.&amp;#160; But, keep in mind that the second definition is the one used by the query syntax.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;The Maybe Monad&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;The &lt;em&gt;Identity&lt;/em&gt; monad is an example of a monadic container type where the &lt;em&gt;Identity&lt;/em&gt; monad wrapped a value.&amp;#160; If we change the definition to contain either a value or a missing value then we have the &lt;em&gt;Maybe&lt;/em&gt; monad.&lt;/p&gt;

&lt;p&gt;Again, we need a type definition.&amp;#160; The &lt;em&gt;Maybe&lt;/em&gt; type is similar to the &lt;em&gt;Identity&lt;/em&gt; type but adds a property denoting whether a value is missing.&amp;#160; It also has a predefined instance, &lt;em&gt;Nothing&lt;/em&gt;, representing all instances lacking a value.&lt;/p&gt;

&lt;blockquote&gt;
  &lt;pre class="code"&gt;&lt;span style="color: blue"&gt;class &lt;/span&gt;&lt;span style="color: #2b91af"&gt;Maybe&lt;/span&gt;&amp;lt;T&amp;gt;
{
    &lt;span style="color: blue"&gt;public readonly static &lt;/span&gt;&lt;span style="color: #2b91af"&gt;Maybe&lt;/span&gt;&amp;lt;T&amp;gt; Nothing = &lt;span style="color: blue"&gt;new &lt;/span&gt;&lt;span style="color: #2b91af"&gt;Maybe&lt;/span&gt;&amp;lt;T&amp;gt;();
    &lt;span style="color: blue"&gt;public &lt;/span&gt;T Value { &lt;span style="color: blue"&gt;get&lt;/span&gt;; &lt;span style="color: blue"&gt;private set&lt;/span&gt;; }
    &lt;span style="color: blue"&gt;public bool &lt;/span&gt;HasValue { &lt;span style="color: blue"&gt;get&lt;/span&gt;; &lt;span style="color: blue"&gt;private set&lt;/span&gt;; }
    Maybe()
    {
        HasValue = &lt;span style="color: blue"&gt;false&lt;/span&gt;;
    }
    &lt;span style="color: blue"&gt;public &lt;/span&gt;Maybe(T value)
    {
        Value = value;
        HasValue = &lt;span style="color: blue"&gt;true&lt;/span&gt;;
    }
}&lt;/pre&gt;
&lt;/blockquote&gt;

&lt;p&gt;The &lt;em&gt;Unit&lt;/em&gt; function takes a value and constructs a &lt;em&gt;Maybe&lt;/em&gt; instance, which wraps the value.&lt;/p&gt;

&lt;blockquote&gt;
  &lt;pre class="code"&gt;&lt;span style="color: blue"&gt;public static &lt;/span&gt;&lt;span style="color: #2b91af"&gt;Maybe&lt;/span&gt;&amp;lt;T&amp;gt; ToMaybe&amp;lt;T&amp;gt;(&lt;span style="color: blue"&gt;this &lt;/span&gt;T value)
{
    &lt;span style="color: blue"&gt;return new &lt;/span&gt;&lt;span style="color: #2b91af"&gt;Maybe&lt;/span&gt;&amp;lt;T&amp;gt;(value);
}&lt;/pre&gt;
&lt;/blockquote&gt;
&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;

&lt;p&gt;The &lt;em&gt;Bind&lt;/em&gt; function takes a &lt;em&gt;Maybe&lt;/em&gt; instance and if there is a value then it applies the delegate to the contained value.&amp;#160; Otherwise, it returns &lt;em&gt;Nothing&lt;/em&gt;.&lt;/p&gt;

&lt;blockquote&gt;
  &lt;pre class="code"&gt;&lt;span style="color: blue"&gt;public static &lt;/span&gt;&lt;span style="color: #2b91af"&gt;Maybe&lt;/span&gt;&amp;lt;U&amp;gt; SelectMany&amp;lt;T, U&amp;gt;(&lt;span style="color: blue"&gt;this &lt;/span&gt;&lt;span style="color: #2b91af"&gt;Maybe&lt;/span&gt;&amp;lt;T&amp;gt; m, &lt;span style="color: #2b91af"&gt;Func&lt;/span&gt;&amp;lt;T, &lt;span style="color: #2b91af"&gt;Maybe&lt;/span&gt;&amp;lt;U&amp;gt;&amp;gt; k)
{
    &lt;span style="color: blue"&gt;if &lt;/span&gt;(!m.HasValue)
        &lt;span style="color: blue"&gt;return &lt;/span&gt;&lt;span style="color: #2b91af"&gt;Maybe&lt;/span&gt;&amp;lt;U&amp;gt;.Nothing;
    &lt;span style="color: blue"&gt;return &lt;/span&gt;k(m.Value);
}&lt;/pre&gt;
&lt;/blockquote&gt;
&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;

&lt;p&gt;The programmer can use the comprehension syntax to work with the &lt;em&gt;Maybe&lt;/em&gt; monad.&amp;#160; For example, create an instance of &lt;em&gt;Maybe&lt;/em&gt; containing the value five and add it to &lt;em&gt;Nothing&lt;/em&gt;.&lt;/p&gt;

&lt;blockquote&gt;
  &lt;pre class="code"&gt;&lt;span style="color: blue"&gt;var &lt;/span&gt;r = &lt;span style="color: blue"&gt;from &lt;/span&gt;x &lt;span style="color: blue"&gt;in &lt;/span&gt;5.ToMaybe()
        &lt;span style="color: blue"&gt;from &lt;/span&gt;y &lt;span style="color: blue"&gt;in &lt;/span&gt;&lt;span style="color: #2b91af"&gt;Maybe&lt;/span&gt;&amp;lt;&lt;span style="color: blue"&gt;int&lt;/span&gt;&amp;gt;.Nothing
        &lt;span style="color: blue"&gt;select &lt;/span&gt;x + y;

&lt;span style="color: #2b91af"&gt;Console&lt;/span&gt;.WriteLine(r.HasValue ? r.Value.ToString() : &lt;span style="color: #a31515"&gt;&amp;quot;Nothing&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;The result is &amp;quot;Nothing&amp;quot;.&amp;#160; We have implemented the null propagation of nullables without explicit language support.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;The List Monad&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Another important container type is the list type.&amp;#160; In fact, the list monad is at the heart of LINQ.&amp;#160; The type &lt;em&gt;IEnumerable&amp;lt;T&amp;gt; &lt;/em&gt;denotes a lazily computed list.&lt;/p&gt;

&lt;p&gt;The &lt;em&gt;Unit&lt;/em&gt; function takes a value and returns a list, which contains only that value.&lt;/p&gt;

&lt;blockquote&gt;
  &lt;pre class="code"&gt;&lt;span style="color: blue"&gt;public static &lt;/span&gt;&lt;span style="color: #2b91af"&gt;IEnumerable&lt;/span&gt;&amp;lt;T&amp;gt; ToList&amp;lt;T&amp;gt;(&lt;span style="color: blue"&gt;this &lt;/span&gt;T value)
{
    &lt;span style="color: blue"&gt;yield return &lt;/span&gt;value;
}&lt;/pre&gt;
&lt;/blockquote&gt;
&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;

&lt;p&gt;The &lt;em&gt;Bind&lt;/em&gt; function takes an &lt;em&gt;IEnumerable&amp;lt;T&amp;gt;&lt;/em&gt;, a delegate, which takes a &lt;em&gt;T&lt;/em&gt; and returns an &lt;em&gt;IEnumerable&amp;lt;U&amp;gt;&lt;/em&gt;, and returns an &lt;em&gt;IEnumerable&amp;lt;U&amp;gt;&lt;/em&gt;.&lt;/p&gt;

&lt;blockquote&gt;
  &lt;pre class="code"&gt;&lt;span style="color: blue"&gt;public static &lt;/span&gt;&lt;span style="color: #2b91af"&gt;IEnumerable&lt;/span&gt;&amp;lt;U&amp;gt; SelectMany&amp;lt;T, U&amp;gt;(&lt;span style="color: blue"&gt;this &lt;/span&gt;&lt;span style="color: #2b91af"&gt;IEnumerable&lt;/span&gt;&amp;lt;T&amp;gt; m, &lt;span style="color: #2b91af"&gt;Func&lt;/span&gt;&amp;lt;T, &lt;span style="color: #2b91af"&gt;IEnumerable&lt;/span&gt;&amp;lt;U&amp;gt;&amp;gt; k)
{
    &lt;span style="color: blue"&gt;foreach &lt;/span&gt;(&lt;span style="color: blue"&gt;var &lt;/span&gt;x &lt;span style="color: blue"&gt;in &lt;/span&gt;m)
        &lt;span style="color: blue"&gt;foreach &lt;/span&gt;(&lt;span style="color: blue"&gt;var &lt;/span&gt;y &lt;span style="color: blue"&gt;in &lt;/span&gt;k(x))
            &lt;span style="color: blue"&gt;yield return &lt;/span&gt;y;
}&lt;/pre&gt;
&lt;/blockquote&gt;
&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;

&lt;p&gt;Now, the programmer can write the familiar query expressions with &lt;em&gt;IEnumerable&amp;lt;T&amp;gt;.&lt;/em&gt;&lt;/p&gt;

&lt;blockquote&gt;
  &lt;pre class="code"&gt;&lt;span style="color: blue"&gt;var &lt;/span&gt;r = &lt;span style="color: blue"&gt;from &lt;/span&gt;x &lt;span style="color: blue"&gt;in new&lt;/span&gt;[] { 0, 1, 2 }
        &lt;span style="color: blue"&gt;from &lt;/span&gt;y &lt;span style="color: blue"&gt;in new&lt;/span&gt;[] { 0, 1, 2 }
        &lt;span style="color: blue"&gt;select &lt;/span&gt;x + y;

&lt;span style="color: blue"&gt;foreach &lt;/span&gt;(&lt;span style="color: blue"&gt;var &lt;/span&gt;i &lt;span style="color: blue"&gt;in &lt;/span&gt;r)
    &lt;span style="color: #2b91af"&gt;Console&lt;/span&gt;.WriteLine(i);&lt;/pre&gt;
&lt;/blockquote&gt;
&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;

&lt;p&gt;Remember that it is the monad that enables the magic.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;The Continuation Monad&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;The continuation monad answers &lt;a href="http://blogs.msdn.com/wesdyer/archive/2007/12/22/continuation-passing-style.aspx"&gt;the question that was posed at the end of the last post&lt;/a&gt;: how can a programmer write CPS code in a more palatable way?&lt;/p&gt;

&lt;p&gt;The type of the continuation monad, &lt;em&gt;K&lt;/em&gt;, is a delegate which when given a continuation, which takes an argument and returns an answer, will return an answer.&lt;/p&gt;

&lt;blockquote&gt;
  &lt;pre class="code"&gt;&lt;span style="color: blue"&gt;delegate &lt;/span&gt;Answer &lt;span style="color: #2b91af"&gt;K&lt;/span&gt;&amp;lt;T,Answer&amp;gt;(&lt;span style="color: #2b91af"&gt;Func&lt;/span&gt;&amp;lt;T,Answer&amp;gt; k);&lt;/pre&gt;
&lt;/blockquote&gt;

&lt;p&gt;The type &lt;em&gt;K&lt;/em&gt; fundamentally differs from types &lt;em&gt;Identity&amp;lt;T&amp;gt;&lt;/em&gt;, &lt;em&gt;Maybe&amp;lt;T&amp;gt;&lt;/em&gt;, and &lt;em&gt;IEnumerable&amp;lt;T&amp;gt;&lt;/em&gt;.&amp;#160; All the other monads represent container types and allow computations to be specified in terms of the values rather than the containers, but the continuation monad contains nothing.&amp;#160; Rather, it composes together continuations the user writes.&lt;/p&gt;

&lt;p&gt;To be a monad, there must be a &lt;em&gt;Unit&lt;/em&gt; function which takes a &lt;em&gt;T &lt;/em&gt;and returns a &lt;em&gt;K&amp;lt;T&lt;/em&gt;,&lt;em&gt;Answer&amp;gt;&lt;/em&gt; for some answer type.&lt;/p&gt;

&lt;blockquote&gt;
  &lt;pre class="code"&gt;&lt;span style="color: blue"&gt;public static &lt;/span&gt;&lt;span style="color: #2b91af"&gt;K&lt;/span&gt;&amp;lt;T, Answer&amp;gt; ToContinuation&amp;lt;T, Answer&amp;gt;(&lt;span style="color: blue"&gt;this &lt;/span&gt;T value)&lt;/pre&gt;
&lt;/blockquote&gt;
&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;

&lt;p&gt;What should it do?&amp;#160; When in doubt, look to the types.&amp;#160;&amp;#160; The method takes a &lt;em&gt;T&lt;/em&gt; and returns a function, which takes a function from &lt;em&gt;T&lt;/em&gt; to &lt;em&gt;Answer&lt;/em&gt;, and returns an &lt;em&gt;Answer&lt;/em&gt;.&amp;#160; Therefore, the method must return a function and the only argument of that function must be a function from &lt;em&gt;T&lt;/em&gt; to &lt;em&gt;Answer&lt;/em&gt;.&amp;#160; Call the argument &lt;em&gt;c&lt;/em&gt;.&lt;/p&gt;

&lt;blockquote&gt;
  &lt;pre class="code"&gt;&lt;span style="color: blue"&gt;return &lt;/span&gt;(&lt;span style="color: #2b91af"&gt;Func&lt;/span&gt;&amp;lt;T, Answer&amp;gt; c) =&amp;gt; ...&lt;/pre&gt;
&lt;/blockquote&gt;
&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;

&lt;p&gt;The body of the lambda must return a value of type &lt;em&gt;Answer&lt;/em&gt;.&amp;#160; Values of type &lt;em&gt;Func&amp;lt;T,Answer&amp;gt;&lt;/em&gt; and a &lt;em&gt;T&lt;/em&gt; are&lt;em&gt;&amp;#160;&lt;/em&gt;available.&amp;#160; Apply &lt;em&gt;c&lt;/em&gt; to &lt;em&gt;value&lt;/em&gt; and the result is of type &lt;em&gt;Answer.&lt;/em&gt;&lt;/p&gt;

&lt;blockquote&gt;
  &lt;pre class="code"&gt;&lt;span style="color: blue"&gt;return &lt;/span&gt;(&lt;span style="color: #2b91af"&gt;Func&lt;/span&gt;&amp;lt;T, Answer&amp;gt; c) =&amp;gt; c(value);&lt;/pre&gt;
&lt;/blockquote&gt;
&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;

&lt;p&gt;To be a monad, &lt;em&gt;Bind&lt;/em&gt; must take a &lt;em&gt;K&amp;lt;T,Answer&amp;gt;&lt;/em&gt; and a function from &lt;em&gt;T &lt;/em&gt;to &lt;em&gt;K&amp;lt;U, Answer&amp;gt;&lt;/em&gt; and return a &lt;em&gt;K&amp;lt;U, Answer&amp;gt;&lt;/em&gt;.&lt;/p&gt;

&lt;blockquote&gt;
  &lt;pre class="code"&gt;&lt;span style="color: blue"&gt;public static &lt;/span&gt;&lt;span style="color: #2b91af"&gt;K&lt;/span&gt;&amp;lt;U, Answer&amp;gt; SelectMany&amp;lt;T, U, Answer&amp;gt;(&lt;span style="color: blue"&gt;this &lt;/span&gt;&lt;span style="color: #2b91af"&gt;K&lt;/span&gt;&amp;lt;T, Answer&amp;gt; m, &lt;span style="color: #2b91af"&gt;Func&lt;/span&gt;&amp;lt;T, &lt;span style="color: #2b91af"&gt;K&lt;/span&gt;&amp;lt;U, Answer&amp;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;But what about the body?&amp;#160; The result must be of type &lt;em&gt;K&amp;lt;U, Answer&amp;gt;&lt;/em&gt;, but how is a result of the correct type formed?&lt;/p&gt;

&lt;p&gt;Expand &lt;em&gt;K&lt;/em&gt;'s definition to gain some insight.&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;&lt;strong&gt;return type&lt;/strong&gt;&lt;/p&gt;

  &lt;p&gt;&lt;strong&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;/strong&gt;&lt;font face="Courier New"&gt;&lt;span style="color: blue"&gt;&lt;font color="#008080"&gt;Func&lt;/font&gt;&lt;/span&gt;&amp;lt;&lt;font color="#008080"&gt;Func&lt;/font&gt;&amp;lt;U, Answer&amp;gt;, Answer&amp;gt;&lt;/font&gt;&lt;/p&gt;

  &lt;p&gt;&lt;strong&gt;&lt;em&gt;m&lt;/em&gt;'s type&lt;/strong&gt;&lt;/p&gt;

  &lt;p&gt;&lt;strong&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;/strong&gt;&lt;font face="Courier New"&gt;&lt;span style="color: blue"&gt;&lt;font color="#008080"&gt;Func&lt;/font&gt;&lt;/span&gt;&amp;lt;&lt;font color="#008080"&gt;Func&lt;/font&gt;&amp;lt;T, Answer&amp;gt;, Answer&amp;gt;&lt;/font&gt;&lt;/p&gt;

  &lt;p&gt;&lt;strong&gt;&lt;em&gt;k&lt;/em&gt;'s type&lt;/strong&gt;&lt;/p&gt;

  &lt;p&gt;&lt;strong&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;/strong&gt;&lt;font face="Courier New"&gt;&lt;span style="color: #2b91af"&gt;Func&lt;/span&gt;&amp;lt;T, &lt;font color="#2b91af"&gt;Func&lt;/font&gt;&amp;lt;&lt;font color="#008080"&gt;Func&lt;/font&gt;&amp;lt;U, Answer&amp;gt;, Answer&amp;gt;&amp;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;Applying &lt;em&gt;k&lt;/em&gt; to a value of type &lt;em&gt;T&lt;/em&gt; results in a value of type &lt;em&gt;K&amp;lt;U,Answer&amp;gt;&lt;/em&gt;, but no value of type &lt;em&gt;T&lt;/em&gt; is available.&amp;#160; Build the return type directly by constructing a function, which takes a function from &lt;em&gt;U&lt;/em&gt; to &lt;em&gt;Answer&lt;/em&gt;.&amp;#160; Call the parameter &lt;em&gt;c&lt;/em&gt;.&lt;/p&gt;

&lt;blockquote&gt;
  &lt;pre class="code"&gt;&lt;span style="color: blue"&gt;return &lt;/span&gt;(&lt;span style="color: #2b91af"&gt;Func&lt;/span&gt;&amp;lt;U,Answer&amp;gt; c) =&amp;gt; ...&lt;/pre&gt;
&lt;/blockquote&gt;
&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;

&lt;p&gt;The body must be type of &lt;em&gt;Answer &lt;/em&gt;so that the return type of &lt;em&gt;Bind&lt;/em&gt; is &lt;em&gt;K&amp;lt;U,Answer&amp;gt;&lt;/em&gt;.&amp;#160; Perhaps, &lt;em&gt;m&lt;/em&gt; could be applied to a function from &lt;em&gt;T&lt;/em&gt; to &lt;em&gt;Answer&lt;/em&gt;.&amp;#160; The result is a value of type &lt;em&gt;Answer&lt;/em&gt;.&lt;/p&gt;

&lt;blockquote&gt;
  &lt;pre class="code"&gt;&lt;span style="color: blue"&gt;return &lt;/span&gt;(&lt;span style="color: #2b91af"&gt;Func&lt;/span&gt;&amp;lt;U,Answer&amp;gt; c) =&amp;gt; m(...)&lt;/pre&gt;
&lt;/blockquote&gt;
&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;

&lt;p&gt;The expression inside the invocation of &lt;em&gt;m&lt;/em&gt; must be of type &lt;em&gt;Func&amp;lt;T,Answer&amp;gt;&lt;/em&gt;.&amp;#160; Since there is nothing of that type, construct the function by creating a lambda with one parameter, &lt;em&gt;x&lt;/em&gt;, of type &lt;em&gt;T.&lt;/em&gt;&lt;/p&gt;

&lt;blockquote&gt;
  &lt;pre class="code"&gt;&lt;span style="color: blue"&gt;return &lt;/span&gt;(&lt;span style="color: #2b91af"&gt;Func&lt;/span&gt;&amp;lt;U,Answer&amp;gt; c) =&amp;gt; m((T x) =&amp;gt; ...)&lt;/pre&gt;
&lt;/blockquote&gt;
&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;

&lt;p&gt;The body of this lambda must be of type &lt;em&gt;Answer&lt;/em&gt;.&amp;#160; Values of type &lt;em&gt;T, &lt;/em&gt;&lt;em&gt;Func&amp;lt;U,Answer&amp;gt;, &lt;/em&gt;and &lt;em&gt;Func&amp;lt;T,Func&amp;lt;Func&amp;lt;U,Answer&amp;gt;, Answer&amp;gt;&amp;gt;&lt;/em&gt; haven't been used yet.&amp;#160; Apply &lt;em&gt;k&lt;/em&gt; to &lt;em&gt;x&lt;/em&gt;.&lt;/p&gt;

&lt;blockquote&gt;
  &lt;pre class="code"&gt;&lt;span style="color: blue"&gt;return &lt;/span&gt;(&lt;span style="color: #2b91af"&gt;Func&lt;/span&gt;&amp;lt;U,Answer&amp;gt; c) =&amp;gt; m((T x) =&amp;gt; k(x)...)&lt;/pre&gt;
&lt;/blockquote&gt;
&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;

&lt;p&gt;The result is a value of type &lt;em&gt;Func&amp;lt;Func&amp;lt;U,Answer&amp;gt;,Answer&amp;gt;&lt;/em&gt;.&amp;#160; Apply the result to &lt;em&gt;c&lt;/em&gt;.&lt;/p&gt;

&lt;blockquote&gt;
  &lt;pre class="code"&gt;&lt;span style="color: blue"&gt;return &lt;/span&gt;(&lt;span style="color: #2b91af"&gt;Func&lt;/span&gt;&amp;lt;U,Answer&amp;gt; c) =&amp;gt; m((T x) =&amp;gt; k(x)(c));&lt;/pre&gt;
&lt;/blockquote&gt;
&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;

&lt;p&gt;The continuation monad turns the computation inside out.&amp;#160; The comprehension syntax can be used to construct continuations.&lt;/p&gt;

&lt;p&gt;Construct a computation, which invokes a continuation with the value seven.&amp;#160; Pass this computation to another computation, which invokes a continuation with the value six.&amp;#160;&amp;#160; Pass this computation to another computation, which invokes a continuation with the result of adding the results of the first two continuations together.&amp;#160; Finally, pass a continuation, which replaces &amp;quot;1&amp;quot;s with &amp;quot;a&amp;quot;s, to the result.&lt;/p&gt;

&lt;blockquote&gt;
  &lt;pre class="code"&gt;&lt;span style="color: blue"&gt;var &lt;/span&gt;r = &lt;span style="color: blue"&gt;from &lt;/span&gt;x &lt;span style="color: blue"&gt;in &lt;/span&gt;7.ToContinuation&amp;lt;&lt;span style="color: blue"&gt;int&lt;/span&gt;,&lt;span style="color: blue"&gt;string&lt;/span&gt;&amp;gt;()
        &lt;span style="color: blue"&gt;from &lt;/span&gt;y &lt;span style="color: blue"&gt;in &lt;/span&gt;6.ToContinuation&amp;lt;&lt;span style="color: blue"&gt;int&lt;/span&gt;,&lt;span style="color: blue"&gt;string&lt;/span&gt;&amp;gt;()
        &lt;span style="color: blue"&gt;select &lt;/span&gt;x + y;

&lt;span style="color: #2b91af"&gt;Console&lt;/span&gt;.WriteLine(r(z =&amp;gt; z.ToString().Replace(&lt;span style="color: #a31515"&gt;'1'&lt;/span&gt;, &lt;span style="color: #a31515"&gt;'a'&lt;/span&gt;))); &lt;font color="#008000"&gt;// displays a3&lt;/font&gt;&lt;/pre&gt;
&lt;/blockquote&gt;

&lt;p&gt;The continuation monad does the heavy-lifting of constructing the continuations.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Monadic Magic&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Beautiful composition of amplified values requires monads.&amp;#160; The &lt;em&gt;Identity&lt;/em&gt;, &lt;em&gt;Maybe&lt;/em&gt;, and &lt;em&gt;IEnumerable&lt;/em&gt; monads demonstrate the power of monads as container types.&amp;#160; The continuation monad, &lt;em&gt;K&lt;/em&gt;, shows how monads can readily express complex computation.&lt;/p&gt;

&lt;p&gt;Stay tuned for more with monads.&amp;#160; Until then, see what monads can do for you.&lt;/p&gt;&lt;img src="http://blogs.msdn.com/aggbug.aspx?PostID=7064392" width="1" height="1"&gt;</description><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/Theory/default.aspx">Theory</category></item><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>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>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>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>Why Functional Programming is Important in a Mixed Environment</title><link>http://blogs.msdn.com/wesdyer/archive/2007/01/18/why-functional-programming-is-important-in-a-mixed-environment.aspx</link><pubDate>Thu, 18 Jan 2007 13:37:00 GMT</pubDate><guid isPermaLink="false">91d46819-8472-40ad-a661-2c78acb4018c:1488315</guid><dc:creator>wesdyer</dc:creator><slash:comments>11</slash:comments><comments>http://blogs.msdn.com/wesdyer/comments/1488315.aspx</comments><wfw:commentRss>http://blogs.msdn.com/wesdyer/commentrss.aspx?PostID=1488315</wfw:commentRss><description>&lt;P&gt;While my last post addressed how to go about learning to think functionally, it did not address why a programmer should embark on the journey in the first place.&amp;nbsp; Why is learning to think functionally important, especially in a mixed environment like&amp;nbsp;C#, Python, or Ruby?&amp;nbsp; Why is it not good&amp;nbsp;enough to stick with the tried and true object-oriented and structured programming styles?&lt;/P&gt;
&lt;P&gt;&lt;EM&gt;&lt;STRONG&gt;Learning to&amp;nbsp;program functionally&amp;nbsp;will lead to more modular, expression-oriented, and&amp;nbsp;conceptually simple code.&lt;/STRONG&gt;&lt;/EM&gt;&lt;/P&gt;
&lt;P&gt;&lt;STRONG&gt;Modular Code&lt;/STRONG&gt; 
&lt;P&gt;Think about a programmer who is introduced to &lt;A href="http://en.wikipedia.org/wiki/Structured_programming" mce_href="http://en.wikipedia.org/wiki/Structured_programming"&gt;structured programming&lt;/A&gt; for the first time.&amp;nbsp; He may remark that it is all about while, if, and for statements.&amp;nbsp; A programmer who encounters &lt;A href="http://en.wikipedia.org/wiki/Object_oriented_programming" mce_href="http://en.wikipedia.org/wiki/Object_oriented_programming"&gt;object-oriented programming&lt;/A&gt; may&amp;nbsp;opine in turn that it is all about inheritance, encapsulation, and polymorphism.&amp;nbsp; In our consideration of &lt;A href="http://en.wikipedia.org/wiki/Functional_programming" mce_href="http://en.wikipedia.org/wiki/Functional_programming"&gt;functional programming&lt;/A&gt;, let's not also make the mistake of confusing the tools we use with the goals we are working towards accomplishing.&amp;nbsp; All&amp;nbsp;of these programming styles are&amp;nbsp;designed to increase the beauty, maintainability, and modularity of&amp;nbsp;code. 
&lt;P&gt;Programmers are trained to notice &lt;A href="http://en.wikipedia.org/wiki/Code_smells" mce_href="http://en.wikipedia.org/wiki/Code_smells"&gt;bad smells&lt;/A&gt;.&amp;nbsp; One particularly potent stench is &lt;A href="http://en.wikipedia.org/wiki/Code_duplication" mce_href="http://en.wikipedia.org/wiki/Code_duplication"&gt;duplicated code&lt;/A&gt;.&amp;nbsp; A programmer tends to notice and remove the smell when the culprit is a block of contiguous statements that is repeated throughout a codebase, but sometimes the smell is more subtle and the cure is less obvious. 
&lt;P&gt;Consider a function that computes the sum of the squares of a list of numbers.&amp;nbsp; A typical approach might look like this: 
&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 int SumOfSquares(IEnumerable&amp;lt;int&amp;gt; nums)&lt;BR&gt;{&lt;BR&gt;&amp;nbsp; int result = 0;&lt;BR&gt;&amp;nbsp; foreach (var item in nums)&lt;BR&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; result += item * item;&lt;BR&gt;&amp;nbsp; return result;&lt;BR&gt;}&lt;/FONT&gt;&lt;/P&gt;&lt;/BLOCKQUOTE&gt;
&lt;P&gt;It seems good enough, but look closely.&amp;nbsp; How many times do programmers compute the sum of a list of numbers?&amp;nbsp; All of the time.&amp;nbsp; So let's write a function to compute the sum. 
&lt;BLOCKQUOTE&gt;
&lt;P&gt;&lt;FONT face="Courier New"&gt;static int Sum(this IEnumerable&amp;lt;int&amp;gt; nums)&lt;BR&gt;{&lt;BR&gt;&amp;nbsp; int result = 0;&lt;BR&gt;&amp;nbsp; foreach (var item in nums)&lt;BR&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; result += item;&lt;BR&gt;&amp;nbsp; return result;&lt;BR&gt;}&lt;/FONT&gt;&lt;/P&gt;&lt;/BLOCKQUOTE&gt;
&lt;P&gt;Ok, now we can simplify our SumOfSquares function by reusing the code to compute the sum.&lt;/P&gt;
&lt;BLOCKQUOTE&gt;
&lt;P&gt;&lt;FONT face="Courier New"&gt;static int SumOfSquares(IEnumerable&amp;lt;int&amp;gt; nums)&lt;BR&gt;{&lt;BR&gt;&amp;nbsp; List&amp;lt;int&amp;gt; squares = new List&amp;lt;int&amp;gt;();&lt;BR&gt;&amp;nbsp; foreach (var item in nums)&lt;BR&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; squares.Add(item * item);&lt;BR&gt;&amp;nbsp; return squares.Sum();&lt;BR&gt;}&lt;/FONT&gt;&lt;/P&gt;&lt;/BLOCKQUOTE&gt;
&lt;P&gt;Hmm.&amp;nbsp; Not really the effect we wanted.&amp;nbsp; If anything the code only got more complicated.&amp;nbsp; Maybe we should extract out the part that takes a list of numbers and returns a list of squares.&amp;nbsp; No, that really isn't a reusable piece of code so it would only be moving the complexity around.&amp;nbsp; The problem is that the code is &lt;A href="http://en.wikipedia.org/wiki/Coupling_%28computer_science%29" mce_href="http://en.wikipedia.org/wiki/Coupling_%28computer_science%29"&gt;tightly coupled&lt;/A&gt; to the expression &lt;FONT face="Courier New"&gt;&lt;EM&gt;item * item&lt;/EM&gt;&lt;/FONT&gt;.&amp;nbsp; The expression is really local to the problem that we are solving, but the act of taking a list of things and performing some operation on each element to produce a new list&amp;nbsp;is a common reusable&amp;nbsp;operation.&amp;nbsp; Functional programmers call this function &lt;A href="http://en.wikipedia.org/wiki/Map_%28higher-order_function%29" mce_href="http://en.wikipedia.org/wiki/Map_%28higher-order_function%29"&gt;Map&lt;/A&gt;. 
&lt;BLOCKQUOTE&gt;
&lt;P&gt;&lt;FONT face="Courier New"&gt;static IEnumerable&amp;lt;U&amp;gt; Map&amp;lt;T, U&amp;gt;(this IEnumerable&amp;lt;T&amp;gt; s, Func&amp;lt;T, U&amp;gt; f)&lt;BR&gt;{&lt;BR&gt;&amp;nbsp; foreach (var item in s)&lt;BR&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; yield return f(item);&lt;BR&gt;}&lt;/FONT&gt;&lt;/P&gt;&lt;/BLOCKQUOTE&gt;
&lt;P&gt;Now we can use Map to reduce the complexity of SumOfSquares.&lt;/P&gt;
&lt;BLOCKQUOTE&gt;
&lt;P&gt;&lt;FONT face="Courier New"&gt;static int SumOfSquares(IEnumerable&amp;lt;int&amp;gt; nums)&lt;BR&gt;{&lt;BR&gt;&amp;nbsp; return nums.Map(x =&amp;gt; x * x).Sum();&lt;BR&gt;}&lt;/FONT&gt;&lt;/P&gt;&lt;/BLOCKQUOTE&gt;
&lt;P&gt;Now that is something to write home about.&amp;nbsp; It does exactly what we want without specifying &lt;A href="http://en.wikipedia.org/wiki/State_machine" mce_href="http://en.wikipedia.org/wiki/State_machine"&gt;state-transition by state-transition&lt;/A&gt; how&amp;nbsp;to go about doing it.&amp;nbsp; Although this is a small example, it is very compelling.&amp;nbsp; Functional programming took a tightly coupled section of code (&lt;FONT face="Courier New"&gt;item * item&lt;/FONT&gt;) and removed the dependency by use of &lt;A href="http://en.wikipedia.org/wiki/Higher-order_functions" mce_href="http://en.wikipedia.org/wiki/Higher-order_functions"&gt;higher-order functions&lt;/A&gt;.&lt;/P&gt;
&lt;P&gt;&lt;STRONG&gt;Expression-Oriented vs Statement-Oriented&lt;/STRONG&gt;&lt;/P&gt;
&lt;P&gt;As a compiler guy, I often work with parsers and&amp;nbsp;abstract syntax&amp;nbsp;trees.&amp;nbsp; Most people are familiar enough with parsing to know there are &lt;A href="http://en.wikipedia.org/wiki/Top-down_parsing" mce_href="http://en.wikipedia.org/wiki/Top-down_parsing"&gt;top-down&lt;/A&gt; and &lt;A href="http://en.wikipedia.org/wiki/Bottom-up_parsing" mce_href="http://en.wikipedia.org/wiki/Bottom-up_parsing"&gt;bottom-up&lt;/A&gt; approaches.&amp;nbsp; What is sometimes overlooked is that there are top-down and bottom-up ways to create parse trees as well.&amp;nbsp; If parent nodes are required to be created before child nodes&amp;nbsp;then the tree is created top-down but if the child nodes&amp;nbsp;must be&amp;nbsp;created before the parent node&amp;nbsp;then the tree is created bottom-up.&amp;nbsp;&amp;nbsp;There are several reasons why a particular system may prefer one approach or the other&amp;nbsp;but one reason&amp;nbsp;deserves closer examination for our purposes: top-down creation of trees is statement-oriented whereas bottom-up creation is expression-oriented.&amp;nbsp; Take a look at the following code to create a parse tree for an &lt;EM&gt;if&lt;/EM&gt; statement.&lt;/P&gt;
&lt;BLOCKQUOTE&gt;
&lt;P&gt;&lt;FONT face="Courier New"&gt;IfNode ifNode = CreateIfNode(parent);&lt;BR&gt;ifNode.Condition = ParseCondition(ifNode);&lt;BR&gt;ifNode.Consequence = ParseBlock(ifNode);&lt;BR&gt;ifNode.Alternative = ParseBlock(ifNode);&lt;/FONT&gt;&lt;/P&gt;&lt;/BLOCKQUOTE&gt;
&lt;P&gt;Contrast this statement-oriented&amp;nbsp;creation with an expression-oriented approach: 
&lt;BLOCKQUOTE&gt;
&lt;P&gt;&lt;FONT face="Courier New"&gt;CreateIfNode(ParseCondition(), ParseBlock(), ParseBlock());&lt;/FONT&gt;&lt;/P&gt;&lt;/BLOCKQUOTE&gt;
&lt;P&gt;The statement-oriented approach is&amp;nbsp;characterized by series of state transitions caused by assignments&amp;nbsp;where some syntactic elements are &lt;A href="http://en.wikipedia.org/wiki/Lvalue" mce_href="http://en.wikipedia.org/wiki/Lvalue"&gt;L-values and others are R-values&lt;/A&gt;.&amp;nbsp; The expression-oriented approach is just&amp;nbsp;a combination of values which is itself a value.&amp;nbsp; Expression-oriented code is more succinct and easier to grasp since it is not cluttered.&amp;nbsp; Each piece is either a primitive&lt;A href="http://mitpress.mit.edu/sicp/full-text/book/book-Z-H-10.html#%_sec_1.1" mce_href="http://mitpress.mit.edu/sicp/full-text/book/book-Z-H-10.html#%_sec_1.1"&gt; value or a combination of values&lt;/A&gt;.&amp;nbsp; In contrast, statement-oriented code is marred by lack of conceptual unity. 
&lt;P&gt;As the C# language has added more functional features, it has become a more expression-oriented language.&amp;nbsp; Similarly, as a programmer learns to follow a functional style, he will naturally write code that is more expression-oriented in nature. 
&lt;P&gt;&lt;STRONG&gt;Conceptually Simpler&lt;/STRONG&gt; 
&lt;P&gt;Imperative programming is sometimes reminiscent of&amp;nbsp;a &lt;A href="http://en.wikipedia.org/wiki/Rube_Goldberg_machine" mce_href="http://en.wikipedia.org/wiki/Rube_Goldberg_machine"&gt;Rube Goldberg machine&lt;/A&gt;.&amp;nbsp; Both require meticulous thought to ensure that a process works correctly despite a myriad of state transitions and interdependencies.&amp;nbsp; It is amazing these complicated programs work at all. 
&lt;P&gt;Dijkstra &lt;A href="http://www.cs.utexas.edu/users/EWD/transcriptions/EWD10xx/EWD1036.html" mce_href="http://www.cs.utexas.edu/users/EWD/transcriptions/EWD10xx/EWD1036.html"&gt;pointed out&lt;/A&gt; that &lt;A href="http://www.cs.utexas.edu/~EWD/transcriptions/EWD03xx/EWD303.html" mce_href="http://www.cs.utexas.edu/~EWD/transcriptions/EWD03xx/EWD303.html"&gt;too many&lt;/A&gt; programmers rely on executing a program in order to understand it.&amp;nbsp; The reason is imperative programs lack sufficient underlying formalisms to make guarantees about any but the most trivial of programs.&amp;nbsp; As much as I love a debugger, it is disheartening to &lt;EM&gt;need&lt;/EM&gt; to use it to understand my code. 
&lt;P&gt;Contrast this with functional&amp;nbsp;programs which have solid theoretical foundations and&amp;nbsp;therefore can more easily make runtime guarantees.&amp;nbsp; In fact, many functional programming books dedicate a significant portion of their pages to showing the reader how&amp;nbsp;to prove&amp;nbsp;various runtime properties of programs.&amp;nbsp; While most programmers wouldn't take the time to &lt;A href="http://en.wikipedia.org/wiki/Euclid's_Elements" mce_href="http://en.wikipedia.org/wiki/Euclid's_Elements"&gt;write proofs like Euclid's&lt;/A&gt; about their programs, it is&amp;nbsp;compelling to think about creating sections of a program which are written so well that their properties are provable and understandable.&amp;nbsp; In our own codebase, those sections of the code that approach this ideal are the most understandable and solid pieces of code that we have. 
&lt;P&gt;&lt;STRONG&gt;The Journey to Understanding&lt;/STRONG&gt; 
&lt;P&gt;While reaching a point where we naturally think functionally is the goal, do not think that there are not ample rewards on the journey to understanding.&amp;nbsp; Pause to&amp;nbsp;appreciate the beauty of higher-order functions.&amp;nbsp; Bask in the joy of type inferencing.&amp;nbsp; Reflect on the infinite.&amp;nbsp; Over the next couple of months, I will be writing about various functional gems that pertain to C# 3.0.&amp;nbsp; And if I haven't done a good enough job explaining why functional programming is important then here are some fantastic papers&amp;nbsp;which detail&amp;nbsp;the subject. 
&lt;P&gt;&lt;EM&gt;&lt;A href="http://www.stanford.edu/class/cs242/readings/backus.pdf" mce_href="http://www.stanford.edu/class/cs242/readings/backus.pdf"&gt;Can Programming Be Liberated from the von Neumann Style? A Functional Style and Its Algebra of Programs - John Backus&lt;/A&gt;&lt;/EM&gt;&lt;/P&gt;
&lt;P&gt;&lt;EM&gt;&lt;A href="http://www.math.chalmers.se/~rjmh/Papers/whyfp.pdf" mce_href="http://www.math.chalmers.se/~rjmh/Papers/whyfp.pdf"&gt;Why Functional Programming Matters - John Hughes&lt;/A&gt;&lt;/EM&gt;&lt;/P&gt;&lt;img src="http://blogs.msdn.com/aggbug.aspx?PostID=1488315" width="1" height="1"&gt;</description><category domain="http://blogs.msdn.com/wesdyer/archive/tags/Functional+Programming/default.aspx">Functional Programming</category></item><item><title>Thinking Functionally</title><link>http://blogs.msdn.com/wesdyer/archive/2007/01/15/thinking-functionally.aspx</link><pubDate>Tue, 16 Jan 2007 00:45:00 GMT</pubDate><guid isPermaLink="false">91d46819-8472-40ad-a661-2c78acb4018c:1473040</guid><dc:creator>wesdyer</dc:creator><slash:comments>8</slash:comments><comments>http://blogs.msdn.com/wesdyer/comments/1473040.aspx</comments><wfw:commentRss>http://blogs.msdn.com/wesdyer/commentrss.aspx?PostID=1473040</wfw:commentRss><description>&lt;P&gt;Every programmer has a story about how he got his start.&amp;nbsp; My own journey began at age 14 when I was bored to death while completing a second-year algebra assignment.&amp;nbsp; My father who was working on the couch with a brand new laptop showed me that I could write a program to&amp;nbsp;do the work for me.&amp;nbsp; I&amp;nbsp;instantly fell in love with the idea and have been rediscovering that love ever since.&lt;/P&gt;
&lt;P&gt;I first began programming in BASIC.&amp;nbsp; It didn't take long to learn &lt;A href="http://en.wikipedia.org/wiki/Gwbasic" mce_href="http://en.wikipedia.org/wiki/Gwbasic"&gt;BASIC.&lt;/A&gt;&amp;nbsp; Within a matter of days, I had written a few &lt;A href="http://en.wikipedia.org/wiki/Text_adventure" mce_href="http://en.wikipedia.org/wiki/Text_adventure"&gt;adventure games&lt;/A&gt;, a prime number sieve, and a menu system.&amp;nbsp; I had come to embrace &lt;A href="http://www.acm.org/classics/oct95/" mce_href="http://www.acm.org/classics/oct95/"&gt;GOTO statements&lt;/A&gt;.&amp;nbsp; Hopefully, &lt;A href="http://www.pipeline.com/~hbaker1/sigplannotices/gigo-1997-03.html" mce_href="http://www.pipeline.com/~hbaker1/sigplannotices/gigo-1997-03.html"&gt;my brain&lt;/A&gt; hasn't &lt;A href="http://www.cs.virginia.edu/~evans/cs655/readings/ewd498.html" mce_href="http://www.cs.virginia.edu/~evans/cs655/readings/ewd498.html"&gt;sustained irreparable damage&lt;/A&gt;.&lt;/P&gt;
&lt;P&gt;Within a few months of learning BASIC, I wanted to learn something else a little more lean and mean so I started to learn C.&amp;nbsp; The process was extremely painful.&amp;nbsp; I still remember feeling&amp;nbsp;at times the strong desire to just give up and go back to BASIC.&amp;nbsp; I felt this when the concepts just didn't sink in or when they did sink in but I wasn't as proficient at "doing it in C" as I was at "doing it in BASIC".&amp;nbsp; When confronted with a new programming task,&amp;nbsp;my instinct was&amp;nbsp;to&amp;nbsp;run off and do it in BASIC but I forced myself to learn to do it in C and within a month or two I had not only met my previous ability in BASIC but far surpassed it.&amp;nbsp;&amp;nbsp;New opportunities were open to me after I made the change.&lt;/P&gt;
&lt;P&gt;As silly as this sounds now, when I first started the transition from BASIC to C, I wasn't even sure that it was possible.&amp;nbsp; It was an act of faith&amp;nbsp;to proceed to learn something that I wasn't even sure would payoff.&amp;nbsp; After seeing the tremendous benefit at the end of the proverbial rainbow, I vowed that I would never let pain and difficultly get in the way of accomplishing something new.&lt;/P&gt;
&lt;P&gt;The lesson has been repeated throughout my life.&amp;nbsp; I remember another time when I first began riding&amp;nbsp;seriously&amp;nbsp;(mountain biking).&amp;nbsp; It was painful.&amp;nbsp; I would approach the bottom of a seemingly endless hill and whimper inside at the prospect of climbing it.&amp;nbsp; After the ascent began it was only worse.&amp;nbsp; My whole body screamed at me to drop the bike and walk up the hill, but I persevered.&amp;nbsp; In the end, it was the constant perseverance that strengthened my muscles, my lungs, and my confidence such that I wasn't daunted by the hills anymore.&amp;nbsp; In fact, I soon came to love the hills that put my strength, endurance, and determination to the test.&lt;/P&gt;
&lt;P&gt;There are&amp;nbsp;a number of lessons that can be gleaned from both experiences:&lt;/P&gt;
&lt;BLOCKQUOTE&gt;
&lt;P&gt;1.&amp;nbsp; Pain is part of the learning process.&lt;/P&gt;
&lt;P&gt;2.&amp;nbsp; Do not allow previous knowledge to act as a crutch in the learning process.&lt;/P&gt;
&lt;P&gt;3.&amp;nbsp; The best way to succeed is to embrace the challenge.&lt;/P&gt;&lt;/BLOCKQUOTE&gt;
&lt;P&gt;Continuing the story of my programming language education, a few years after I learned C, I desired to learn about object-oriented programming so I began reading books about C++ and writing OO code.&amp;nbsp; The learning process began anew but this time it was coupled with a new problem:&amp;nbsp;when, where, and&amp;nbsp;how&amp;nbsp;should I apply OO techniques to the problems that I was solving.&amp;nbsp; This proved much more difficult than just absorbing OO syntax or semantics.&amp;nbsp; In fact, it took a number of years to get a good grasp on this problem.&amp;nbsp; The solution&amp;nbsp;involved several important parts:&amp;nbsp;learn from the best minds (read good code and books, discuss with experts), practice, and experiment.&lt;/P&gt;
&lt;P&gt;Of course, I was not alone in my quest to understand OO.&amp;nbsp; The mainstream programming community was introduced to it in the 80s and&amp;nbsp;really bought into it&amp;nbsp;in the 90s.&amp;nbsp; Quite a few people get it somewhat, some people have no clue (think thinly veiled procedural programs in OO clothing or a clutter of design patterns where there is barely a need), and a few people really get it right.&amp;nbsp; I personally think that OO is especially hard to get since there is a dearth of good literature on the subject.&amp;nbsp; Only a few books stand out as generally accepted, &lt;A href="http://www.amazon.com/Design-Patterns-Object-Oriented-Addison-Wesley-Professional/dp/0201633612/sr=8-1/qid=1168896517/ref=pd_bbs_sr_1/102-0642895-0660153?ie=UTF8&amp;amp;s=books" mce_href="http://www.amazon.com/Design-Patterns-Object-Oriented-Addison-Wesley-Professional/dp/0201633612/sr=8-1/qid=1168896517/ref=pd_bbs_sr_1/102-0642895-0660153?ie=UTF8&amp;amp;s=books"&gt;Design Patterns&lt;/A&gt; and &lt;A href="http://www.amazon.com/Refactoring-Improving-Design-Existing-Code/dp/0201485672/sr=1-1/qid=1168896551/ref=pd_bbs_sr_1/102-0642895-0660153?ie=UTF8&amp;amp;s=books" mce_href="http://www.amazon.com/Refactoring-Improving-Design-Existing-Code/dp/0201485672/sr=1-1/qid=1168896551/ref=pd_bbs_sr_1/102-0642895-0660153?ie=UTF8&amp;amp;s=books"&gt;Refactoring&lt;/A&gt; come to mind, but even these books are criticized by many.&lt;/P&gt;
&lt;P&gt;More recently there has been a trend towards programming languages incorporating functional language features in the language.&amp;nbsp; This has been happening for some time (procedures, recursion, and more recently garbage collection), but it really has been hitting its stride in recent years (closures, lambdas, continuations, type inference, monad like patterns).&amp;nbsp; The problem is this is the first time that the mainstream programmer has been exposed to these concepts.&amp;nbsp; How is she supposed to learn how to use these features?&amp;nbsp; How will it impact her work?&amp;nbsp; Are we in for the same process of maturation that OO programming&amp;nbsp;experienced?&amp;nbsp; I think not.&lt;/P&gt;
&lt;P&gt;Fortunately, there is a wealth of information about functional programming and a long history of experience.&amp;nbsp; This doesn't entirely free the would be functional programmer from the cost of learning a new way of thinking but it does drastically reduce the cost.&amp;nbsp; So how should a programmer learn to think functionally?&amp;nbsp; I recommend that a programmer read the best books, immerse himself in a functional language, and then practice, practice, practice.&lt;/P&gt;
&lt;P&gt;&lt;STRONG&gt;The Best Books&lt;/STRONG&gt;&lt;/P&gt;
&lt;P&gt;Functional programming has been around since LISP which was the second programming language (following FORTRAN).&amp;nbsp; Whereas OO programming had its genesis in common sense modeling of the real world (simulation software), functional programming was born through theory (lambda calculus).&amp;nbsp; Academics have really embraced functional programming in research and so there are a number of very good books on functional programming.&amp;nbsp; Here are two of the best books on the subject.&lt;/P&gt;
&lt;BLOCKQUOTE&gt;
&lt;P&gt;1.&amp;nbsp; &lt;A href="http://www.amazon.com/Structure-Interpretation-Computer-Programs-Engineering/dp/0262011530/sr=1-1/qid=1168896608/ref=pd_bbs_1/102-0642895-0660153?ie=UTF8&amp;amp;s=books" mce_href="http://www.amazon.com/Structure-Interpretation-Computer-Programs-Engineering/dp/0262011530/sr=1-1/qid=1168896608/ref=pd_bbs_1/102-0642895-0660153?ie=UTF8&amp;amp;s=books"&gt;Structure and Interpretation of Computer Programs - Abelson and Sussman&lt;/A&gt;&lt;/P&gt;
&lt;P&gt;2.&amp;nbsp;&amp;nbsp;Introduction to Functional Programming 1st Edition - Bird and Wadler (Out of Print - maybe on Ebay?)&lt;/P&gt;&lt;/BLOCKQUOTE&gt;
&lt;P&gt;Read these books and enjoy drinking from the firehose.&lt;/P&gt;
&lt;P&gt;&lt;STRONG&gt;Learning by Immersion&lt;/STRONG&gt;&lt;/P&gt;
&lt;P&gt;My second recommendation is to meet the challenge head on.&amp;nbsp; Learn a functional language like &lt;A href="http://en.wikipedia.org/wiki/Lisp_programming_language" mce_href="http://en.wikipedia.org/wiki/Lisp_programming_language"&gt;Lisp&lt;/A&gt;, &lt;A href="http://en.wikipedia.org/wiki/Scheme_%28programming_language%29" mce_href="http://en.wikipedia.org/wiki/Scheme_%28programming_language%29"&gt;Scheme&lt;/A&gt;, &lt;A href="http://en.wikipedia.org/wiki/ML_programming_language" mce_href="http://en.wikipedia.org/wiki/ML_programming_language"&gt;ML&lt;/A&gt;, &lt;A href="http://en.wikipedia.org/wiki/Haskell_%28programming_language%29" mce_href="http://en.wikipedia.org/wiki/Haskell_%28programming_language%29"&gt;Haskell&lt;/A&gt;, or &lt;A href="http://en.wikipedia.org/wiki/Erlang_programming_language" mce_href="http://en.wikipedia.org/wiki/Erlang_programming_language"&gt;Erlang&lt;/A&gt;.&amp;nbsp; It doesn't matter which language it is as long as&amp;nbsp;it doesn't allow&amp;nbsp;a regression to previous ways of thinking.&amp;nbsp; There will be a temptation at first to attempt a problem in ways that are comfortable and familiar, but working in a functional language will require a functional approach to the problem.&amp;nbsp; It is very analogous to my story of learning to climb hills on a bike.&amp;nbsp; I wanted to walk and at first it might well have been faster to walk but I forced myself to stay in saddle and in the end I could climb hills much faster on the bike than I ever could walking.&amp;nbsp; So stay in the saddle and learn to think functionally.&lt;/P&gt;
&lt;P&gt;&lt;STRONG&gt;Practice&lt;/STRONG&gt;&lt;/P&gt;
&lt;P&gt;Once good literature and immersion have been used in the learning process, it will be natural&amp;nbsp;to apply functional programming techniques to problems in a language that allows both functional and non-functional approaches to problem solving.&amp;nbsp; The final step is learning when to use the new tool in a mixed environment and the key to overcoming this challenge is to practice.&amp;nbsp; Experience is vital in any art because it tunes the senses to appreciate beautiful solutions.&lt;/P&gt;
&lt;P&gt;C# 3.0 offers some features which can drastically improve the programming experience but only by learning to think functionally can they be fully appreciated.&lt;/P&gt;&lt;img src="http://blogs.msdn.com/aggbug.aspx?PostID=1473040" width="1" height="1"&gt;</description><category domain="http://blogs.msdn.com/wesdyer/archive/tags/Functional+Programming/default.aspx">Functional Programming</category></item><item><title>Thus Quoth the Humble Programmer</title><link>http://blogs.msdn.com/wesdyer/archive/2006/12/22/thus-quoth-the-humble-programmer.aspx</link><pubDate>Sat, 23 Dec 2006 02:20:01 GMT</pubDate><guid isPermaLink="false">91d46819-8472-40ad-a661-2c78acb4018c:1349791</guid><dc:creator>wesdyer</dc:creator><slash:comments>6</slash:comments><comments>http://blogs.msdn.com/wesdyer/comments/1349791.aspx</comments><wfw:commentRss>http://blogs.msdn.com/wesdyer/commentrss.aspx?PostID=1349791</wfw:commentRss><description>&lt;p&gt;I love Scheme!&amp;nbsp; It is such a beautiful language.&amp;nbsp; I was first introduced to it during college.&amp;nbsp; At that time, I thought it was an interesting language but I didn't see the power of the language until later.&amp;nbsp; That moment came when I experienced reading &lt;a href="http://mitpress.mit.edu/sicp/full-text/book/book.html"&gt;The Structure and Interpretation of Computer Programs&lt;/a&gt;.&amp;nbsp; It was a great joy to read the text and work through the exercises.&amp;nbsp; But the most fulfilling part was thinking about what it all meant.&amp;nbsp; I definitely encourage anyone who wants to expand their mind to read this wonderful text.&lt;/p&gt; &lt;p&gt;&lt;a onclick="return amz_js_PopWin('http://www.amazon.com/gp/product/images/0262011530/ref=dp_image_0/002-7913622-5508035?ie=UTF8&amp;amp;n=283155&amp;amp;s=books','AmazonHelp','width=700,height=600,resizable=1,scrollbars=1,toolbar=0,status=1');" href="http://www.amazon.com/gp/product/images/0262011530/ref=dp_image_0/002-7913622-5508035?ie=UTF8&amp;amp;n=283155&amp;amp;s=books" target="AmazonHelp"&gt;&lt;img id="prodImage" height="240" alt="Structure and Interpretation of Computer Programs - 2nd Edition (MIT Electrical Engineering and Computer Science)" src="http://ec1.images-amazon.com/images/P/0262011530.01._AA240_SCLZZZZZZZ_.jpg" width="240" border="0"&gt;&lt;/a&gt;&lt;/p&gt; &lt;p&gt;&amp;nbsp;&lt;/p&gt; &lt;p&gt;&lt;strong&gt;Quoting in Scheme&lt;/strong&gt;&lt;/p&gt; &lt;p&gt;Scheme&amp;nbsp;(or any other LISP dialect)&amp;nbsp;allows programmers&amp;nbsp;to&amp;nbsp;define variables, define lambdas, and evaluate expressions (I know that I am greatly simplifying here).&amp;nbsp; But one feature that is particularly interesting is the ability to quote.&amp;nbsp; Quoting an expression causes the expression not be evaluated but instead to return the structure of the expression.&amp;nbsp; For example (line numbers added for discussion purposes):&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;1:&amp;nbsp;&amp;nbsp;&amp;nbsp; (define f1 (lambda (x y) (+ x y)))&lt;br&gt;2:&amp;nbsp;&amp;nbsp;&amp;nbsp; f1&lt;br&gt;3:&amp;nbsp;&amp;nbsp;&amp;nbsp; (define e (quote (lambda (x y) (+ x y))))&lt;br&gt;4:&amp;nbsp;&amp;nbsp;&amp;nbsp; e&lt;br&gt;5:&amp;nbsp;&amp;nbsp;&amp;nbsp; (define f2 (eval e))&lt;br&gt;6:&amp;nbsp;&amp;nbsp;&amp;nbsp; (f1 3 4)&lt;br&gt;7:&amp;nbsp;&amp;nbsp;&amp;nbsp; (f2 3 4)&lt;/font&gt;&lt;/p&gt;&lt;/blockquote&gt; &lt;p&gt;This program produces the following results. &lt;blockquote&gt; &lt;p&gt;&lt;font face="Courier New"&gt;#&amp;lt;procedure:f1&amp;gt;&lt;br&gt;(lambda (x y) (+ x y))&lt;br&gt;7&lt;br&gt;7&lt;/font&gt;&lt;/p&gt;&lt;/blockquote&gt; &lt;p&gt;Line number 1 defines a variable f1 to be the result of evaluating a lambda expression, thus f1 is a function.&amp;nbsp; Line 2 evaluates f1 which simply returns the function.&amp;nbsp; Line 3 defines e to be the result of evaluating the quote of the same lambda expression that appeared in line 1.&amp;nbsp; But now e is &lt;em&gt;not &lt;/em&gt;a function but rather a structure describing the lambda.&amp;nbsp; Line 4 evaluates e, which displays the structure it references.&amp;nbsp; Line 5 defines a variable f2 to be the result of apply eval to e.&amp;nbsp; Eval runs the Scheme interpreter on its arguments.&amp;nbsp; Recall, that e is a structure describing a lambda.&amp;nbsp; So applying eval to e we get a lambda and so f2 is now a function described by this lambda.&amp;nbsp; Finally, on lines 6 and 7 we apply f1 and f2 respectively to arguments 3 and 4.&amp;nbsp; Since they are both functions that correspond to the same lambda structure we expect to get the same results and indeed we do. &lt;p&gt;&lt;strong&gt;Quoting in C#&lt;/strong&gt; &lt;p&gt;With C# 3.0 we can do essentially the same thing (again line numbers added for discussion purposes). &lt;blockquote&gt; &lt;p&gt;&lt;font face="Courier New"&gt;1:&amp;nbsp;&amp;nbsp;&amp;nbsp; Func&amp;lt;int, int, int&amp;gt; f1 = (x, y) =&amp;gt; x + y;&lt;br&gt;2:&amp;nbsp;&amp;nbsp;&amp;nbsp; Console.WriteLine(f1);&lt;br&gt;3:&amp;nbsp;&amp;nbsp;&amp;nbsp; Expression&amp;lt;Func&amp;lt;int, int, int&amp;gt;&amp;gt; e = (x, y) =&amp;gt; x + y;&lt;br&gt;4:&amp;nbsp;&amp;nbsp;&amp;nbsp; Console.WriteLine(e);&lt;br&gt;5:&amp;nbsp;&amp;nbsp;&amp;nbsp; Func&amp;lt;int, int, int&amp;gt; f2 = e.Compile();&lt;br&gt;6:&amp;nbsp;&amp;nbsp;&amp;nbsp; Console.WriteLine(f1(3, 4));&lt;br&gt;7:&amp;nbsp;&amp;nbsp;&amp;nbsp; Console.WriteLine(f2(3, 4));&lt;/font&gt;&lt;/p&gt;&lt;/blockquote&gt; &lt;p&gt;This program displays the following: &lt;blockquote&gt; &lt;p&gt;&lt;font face="Courier New"&gt;System.Linq.Func`3[System.Int32,System.Int32,System.Int32]&lt;br&gt;(x, y) =&amp;gt; (x + y)&lt;br&gt;7&lt;br&gt;7&lt;/font&gt;&lt;/p&gt;&lt;/blockquote&gt; &lt;p&gt;Notice how remarkably similar both the programs and that outputs are.&amp;nbsp; Again, on line 1 we define a delegate to be the result of evaluating a lambda expression.&amp;nbsp; On line 2, we display this delegate.&amp;nbsp; On line 3, we assign e the result of evaluating a lambda expression.&amp;nbsp; Notice that in C# both assignments (lines&amp;nbsp;1 and 3)&amp;nbsp;look the same except for the type of the variable to which the lambda is assigned.&amp;nbsp; Lambdas can be converted either to delegates or to expression trees depending on the usage.&amp;nbsp; Delegates can be invoked while expression trees preserve the structure of the lambda.&amp;nbsp; On line 4, we display the expression tree for e which corresponds to the structure of the lambda.&amp;nbsp; On line 5, we do the equivalent of the eval in Scheme by compiling the expression tree structure to a delegate.&amp;nbsp; We can now invoke f2 like we can invoke f1.&amp;nbsp; On lines 6 and 7, we invoke these two delegates and display their results. &lt;p&gt;&lt;strong&gt;So What?&lt;/strong&gt; &lt;p&gt;While this is all very remarkable, it may seem a bit esoteric.&amp;nbsp; Why take the trouble to have a variable with a value that corresponds to the structure of a lambda and then convert that to an invocable form?&amp;nbsp; Why not just always create the delegate immediately?&amp;nbsp; The reason is with the expression tree form of the lambda, we can reason about the structure and then take action on it.&amp;nbsp; Consider queries.&amp;nbsp; When a query is translated it creates a number of lambdas, but one of the key questions is: Are those lambdas then converted to delegates or expression trees?&amp;nbsp; For example: &lt;blockquote&gt; &lt;p&gt;&lt;font face="Courier New"&gt;var q = from x in foo&lt;/font&gt; &lt;p&gt;&lt;font face="Courier New"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;where x &amp;gt; 1&lt;/font&gt; &lt;p&gt;&lt;font face="Courier New"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;select x + 1;&lt;/font&gt;&lt;/p&gt;&lt;/blockquote&gt; &lt;p&gt;This is &lt;a href="http://blogs.msdn.com/wesdyer/archive/2006/12/21/comprehending-comprehensions.aspx"&gt;translated&lt;/a&gt; to: &lt;blockquote&gt; &lt;p&gt;&lt;font face="Courier New"&gt;var q = foo.Where(x =&amp;gt; x &amp;gt; 1)&lt;/font&gt; &lt;p&gt;&lt;font face="Courier New"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; .Select(x =&amp;gt; x + 1);&lt;/font&gt;&lt;/p&gt;&lt;/blockquote&gt; &lt;p&gt;&lt;a href="http://blogs.msdn.com/wesdyer/archive/2006/12/21/comprehending-comprehensions.aspx"&gt;We have already discussed&lt;/a&gt; that which "Where" and "Select" methods are called depends upon what the type of foo is and which extension methods are in scope.&amp;nbsp; If the "Where" and "Select" methods take a delegate then the lambdas will be converted to delegates; however, if they take an expression tree then the lambdas are converted to expression trees instead.&amp;nbsp; So a LINQ provider (or someone who has implemented the query pattern methods like "Where" and "Select") can choose whether they would like the lambdas in delegate or expression tree form.&amp;nbsp; Now lets look at a few providers and see what they do.&amp;nbsp; LINQ to objects (or the in-memory query operators that apply to IEnumerable&amp;lt;T&amp;gt;) take delegates.&amp;nbsp; This is because they will invoke the delegates to do things like evaluate predicates or projections.&amp;nbsp; However, LINQ to SQL&amp;nbsp;on the other hand takes expression trees.&amp;nbsp; It does not "invoke" the lambdas but instead reasons over the structure of the lambdas and then translates the expression trees to equivalent SQL code given a schema for a database.&amp;nbsp; This is the beauty of the LINQ pattern. &lt;p&gt;Adding the ability to quote lambdas enables all sorts of possiblities.&amp;nbsp; You might easily imagine other uses for expression trees: remoting evaluation of expressions, query planning, executing them on a GPU, .... &lt;p&gt;What can you think of doing?&lt;/p&gt;&lt;img src="http://blogs.msdn.com/aggbug.aspx?PostID=1349791" 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/Queries/default.aspx">Queries</category><category domain="http://blogs.msdn.com/wesdyer/archive/tags/Scheme/default.aspx">Scheme</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/Lambdas/default.aspx">Lambdas</category></item></channel></rss>