<?xml version="1.0" encoding="utf-8"?>
<rss xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="2.0">
  <channel>
    <title>Removing All Doubt</title>
    <link>http://www.removingalldoubt.com</link>
    <description />
    <copyright>Copyright 2005 Chuck Jazdzewski</copyright>
    <lastBuildDate>Fri, 06 Mar 2009 19:22:46 GMT</lastBuildDate>
    <generator>ChrisAn's BlogX</generator>
    <managingEditor>chuckjaz@hotmail.com</managingEditor>
    <webMaster>chuckjaz@hotmail.com</webMaster>
    <item>
      <title>Simulating INumeric with policies</title>
      <guid>http://www.removingalldoubt.com/permalink.aspx/66b75287-2a94-415c-88b1-9778adffb406</guid>
      <link>http://www.removingalldoubt.com/permalink.aspx/66b75287-2a94-415c-88b1-9778adffb406</link>
      <pubDate>Fri, 06 Mar 2009 19:22:46 GMT</pubDate>
      <description>&lt;body xmlns="http://www.w3.org/1999/xhtml"&gt;
&lt;p&gt;After reading &lt;a href="http://blogs.msdn.com/lucabol"&gt;Luca Bolognese&amp;#39;s&lt;/a&gt; 
blog post regarding using
&lt;a href="http://blogs.msdn.com/lucabol/archive/2009/02/05/simulating-inumeric-with-dynamic-in-c-4-0.aspx"&gt;
C# 4.0&amp;#39;s dynamic keyword to simulate INumeric&lt;/a&gt; I immediately thought that must be a way to express 
this with generics instead. Generics, however, do not allow you to abstract over operators (which is what
is is needed to really do &lt;code&gt;INumeric&lt;/code&gt;) but you can simulate it using adapters as described in
&lt;a href="http://www.removingalldoubt.com/PermaLink.aspx/f712e487-a6f5-4a65-a718-5ce580f399a8"&gt;
this post&lt;/a&gt;.&lt;/p&gt;
&lt;p&gt;Say I want to write a general average routine that is generic over what type I am using to store the data.
That is, I want one routine that works equally for &lt;code&gt;&lt;strong&gt;double&lt;/strong&gt;&lt;/code&gt; as well as &lt;code&gt;&lt;strong&gt;decimal&lt;/strong&gt;&lt;/code&gt;.
What I want to be able to write is something like,&lt;/p&gt;
&lt;pre class="code"&gt;
        &lt;strong&gt;public&lt;/strong&gt; &lt;strong&gt;static&lt;/strong&gt; T Average(&lt;strong&gt;params&lt;/strong&gt; T[] values) {
            T total = 0;

            &lt;strong&gt;foreach&lt;/strong&gt; (&lt;strong&gt;var&lt;/strong&gt; v &lt;strong&gt;in&lt;/strong&gt; values) 
                total = total + v;

            &lt;strong&gt;return&lt;/strong&gt; total / values.Length;
        }
&lt;/pre&gt;
&lt;p&gt;where the &lt;code&gt;T&lt;/code&gt; is any type that supports adding and dividing. I can't get this code to
compile exactly but we can get surprisingly close! My final version looks like,&lt;/p&gt;
&lt;pre class="code"&gt;
    &lt;strong&gt;class&lt;/strong&gt; Math&amp;lt;T, A&amp;gt; : PolicyUser&amp;lt;T, A&amp;gt; &lt;strong&gt;where&lt;/strong&gt; A : &lt;strong&gt;struct&lt;/strong&gt;, IOperatorPolicy&amp;lt;T&amp;gt; {
        &lt;strong&gt;public&lt;/strong&gt; &lt;strong&gt;static&lt;/strong&gt; T Average(&lt;strong&gt;params&lt;/strong&gt; T[] values) {
            &lt;strong&gt;var&lt;/strong&gt; total = L(0);

            &lt;strong&gt;foreach&lt;/strong&gt; (&lt;strong&gt;var&lt;/strong&gt; v &lt;strong&gt;in&lt;/strong&gt; values) 
                total = total + v;

            &lt;strong&gt;return&lt;/strong&gt; total / values.Length;
        }
    }
&lt;/pre&gt;
&lt;p&gt;which is much closer to the original than I thought originally could get!&lt;/p&gt;
&lt;p&gt;I started by cloning the operator policy and added a &lt;code&gt;FromInt()&lt;/code&gt; I will explain below,&lt;/p&gt;
&lt;pre class="code"&gt;
    &lt;strong&gt;interface&lt;/strong&gt; IOperatorPolicy&amp;lt;T&amp;gt; {
        T Add(T a, T b);
        T Subtract(T a, T b);
        T Multiply(T a, T b);
        T Divide(T a, T b);
        T FromInt(&lt;strong&gt;int&lt;/strong&gt; value);
    }
&lt;/pre&gt;
&lt;p&gt;Then I cloned the &lt;code&gt;&lt;strong&gt;double&lt;/strong&gt;&lt;/code&gt; policy struct and then added a &lt;code&gt;&lt;strong&gt;decimal&lt;/strong&gt;&lt;/code&gt; mainly by cut/paste/search/replace&lt;/p&gt;
&lt;pre class="code"&gt;
    &lt;strong&gt;struct&lt;/strong&gt; DoubleOperatorPolicy : IOperatorPolicy&amp;lt;&lt;strong&gt;double&lt;/strong&gt;&amp;gt; {
        &lt;strong&gt;double&lt;/strong&gt; IOperatorPolicy&amp;lt;&lt;strong&gt;double&lt;/strong&gt;&amp;gt;.Add(&lt;strong&gt;double&lt;/strong&gt; a, &lt;strong&gt;double&lt;/strong&gt; b) { &lt;strong&gt;return&lt;/strong&gt; a + b; }
        &lt;strong&gt;double&lt;/strong&gt; IOperatorPolicy&amp;lt;&lt;strong&gt;double&lt;/strong&gt;&amp;gt;.Subtract(&lt;strong&gt;double&lt;/strong&gt; a, &lt;strong&gt;double&lt;/strong&gt; b) { &lt;strong&gt;return&lt;/strong&gt; a - b; }
        &lt;strong&gt;double&lt;/strong&gt; IOperatorPolicy&amp;lt;&lt;strong&gt;double&lt;/strong&gt;&amp;gt;.Multiply(&lt;strong&gt;double&lt;/strong&gt; a, &lt;strong&gt;double&lt;/strong&gt; b) { &lt;strong&gt;return&lt;/strong&gt; a * b; }
        &lt;strong&gt;double&lt;/strong&gt; IOperatorPolicy&amp;lt;&lt;strong&gt;double&lt;/strong&gt;&amp;gt;.Divide(&lt;strong&gt;double&lt;/strong&gt; a, &lt;strong&gt;double&lt;/strong&gt; b) { &lt;strong&gt;return&lt;/strong&gt; a / b; }
        &lt;strong&gt;double&lt;/strong&gt; IOperatorPolicy&amp;lt;&lt;strong&gt;double&lt;/strong&gt;&amp;gt;.FromInt(&lt;strong&gt;int&lt;/strong&gt; value) { &lt;strong&gt;return&lt;/strong&gt; value; }
    }

    &lt;strong&gt;struct&lt;/strong&gt; DecimalOperatorPolicy : IOperatorPolicy&amp;lt;&lt;strong&gt;decimal&lt;/strong&gt;&amp;gt; {
        &lt;strong&gt;decimal&lt;/strong&gt; IOperatorPolicy&amp;lt;&lt;strong&gt;decimal&lt;/strong&gt;&amp;gt;.Add(&lt;strong&gt;decimal&lt;/strong&gt; a, &lt;strong&gt;decimal&lt;/strong&gt; b) { &lt;strong&gt;return&lt;/strong&gt; a + b; }
        &lt;strong&gt;decimal&lt;/strong&gt; IOperatorPolicy&amp;lt;&lt;strong&gt;decimal&lt;/strong&gt;&amp;gt;.Subtract(&lt;strong&gt;decimal&lt;/strong&gt; a, &lt;strong&gt;decimal&lt;/strong&gt; b) { &lt;strong&gt;return&lt;/strong&gt; a - b; }
        &lt;strong&gt;decimal&lt;/strong&gt; IOperatorPolicy&amp;lt;&lt;strong&gt;decimal&lt;/strong&gt;&amp;gt;.Multiply(&lt;strong&gt;decimal&lt;/strong&gt; a, &lt;strong&gt;decimal&lt;/strong&gt; b) { &lt;strong&gt;return&lt;/strong&gt; a * b; }
        &lt;strong&gt;decimal&lt;/strong&gt; IOperatorPolicy&amp;lt;&lt;strong&gt;decimal&lt;/strong&gt;&amp;gt;.Divide(&lt;strong&gt;decimal&lt;/strong&gt; a, &lt;strong&gt;decimal&lt;/strong&gt; b) { &lt;strong&gt;return&lt;/strong&gt; a / b; }
        &lt;strong&gt;decimal&lt;/strong&gt; IOperatorPolicy&amp;lt;&lt;strong&gt;decimal&lt;/strong&gt;&amp;gt;.FromInt(int value) { &lt;strong&gt;return&lt;/strong&gt; value; }
    }
&lt;/pre&gt;
&lt;p&gt;The cleaver bit is to define a base type that contains a &lt;code&gt;struct&lt;/code&gt; that defines the operators
as overloads. The overloads use a policy &lt;code&gt;&lt;strong&gt;struct&lt;/strong&gt;&lt;/code&gt; to implement that overloaded operators. This &lt;code&gt;
&lt;strong&gt;struct&lt;/strong&gt;&lt;/code&gt;
also defines implicit conversion operators to hide some (but not all) of the messiness introduced by using this
wrapper type. The &lt;code&gt;PolicyUser&lt;/code&gt; class looks like,&lt;/p&gt;
&lt;pre class="code"&gt;
    &lt;strong&gt;class&lt;/strong&gt; PolicyUser&amp;lt;T, A&amp;gt; &lt;strong&gt;where&lt;/strong&gt; A: &lt;strong&gt;struct&lt;/strong&gt;, IOperatorPolicy&amp;lt;T&amp;gt; {
        &lt;strong&gt;static&lt;/strong&gt; A Policy = &lt;strong&gt;new&lt;/strong&gt; A();
        
        &lt;strong&gt;protected&lt;/strong&gt; &lt;strong&gt;struct&lt;/strong&gt; Value {
            &lt;strong&gt;public&lt;/strong&gt; T V;

            &lt;strong&gt;public&lt;/strong&gt; Value(T v) { V = v; }

            &lt;strong&gt;public&lt;/strong&gt; &lt;strong&gt;static&lt;/strong&gt; Value &lt;strong&gt;operator&lt;/strong&gt; +(Value a, Value b) { &lt;strong&gt;return&lt;/strong&gt; &lt;strong&gt;new&lt;/strong&gt; Value(Policy.Add(a.V, b.V)); }
            &lt;strong&gt;public&lt;/strong&gt; &lt;strong&gt;static&lt;/strong&gt; Value &lt;strong&gt;operator&lt;/strong&gt; -(Value a, Value b) { &lt;strong&gt;return&lt;/strong&gt; &lt;strong&gt;new&lt;/strong&gt; Value(Policy.Subtract(a.V, b.V)); }
            &lt;strong&gt;public&lt;/strong&gt; &lt;strong&gt;static&lt;/strong&gt; Value &lt;strong&gt;operator&lt;/strong&gt; *(Value a, Value b) { &lt;strong&gt;return&lt;/strong&gt; &lt;strong&gt;new&lt;/strong&gt; Value(Policy.Multiply(a.V, b.V)); }
            &lt;strong&gt;public&lt;/strong&gt; &lt;strong&gt;static&lt;/strong&gt; Value &lt;strong&gt;operator&lt;/strong&gt; /(Value a, Value b) { &lt;strong&gt;return&lt;/strong&gt; &lt;strong&gt;new&lt;/strong&gt; Value(Policy.Divide(a.V, b.V)); }
            &lt;strong&gt;public&lt;/strong&gt; &lt;strong&gt;static&lt;/strong&gt; &lt;strong&gt;implicit&lt;/strong&gt; &lt;strong&gt;operator&lt;/strong&gt; Value(T v) { &lt;strong&gt;return&lt;/strong&gt; &lt;strong&gt;new&lt;/strong&gt; Value(v); }
            &lt;strong&gt;public&lt;/strong&gt; &lt;strong&gt;static&lt;/strong&gt; &lt;strong&gt;implicit&lt;/strong&gt; &lt;strong&gt;operator&lt;/strong&gt; Value(&lt;strong&gt;int&lt;/strong&gt; v) { &lt;strong&gt;return&lt;/strong&gt; &lt;strong&gt;new&lt;/strong&gt; Value(Policy.FromInt(v)); }
            &lt;strong&gt;public&lt;/strong&gt; &lt;strong&gt;static&lt;/strong&gt; &lt;strong&gt;implicit&lt;/strong&gt; &lt;strong&gt;operator&lt;/strong&gt; T(Value v) { &lt;strong&gt;return&lt;/strong&gt; v.V; }
        }

        &lt;strong&gt;protected&lt;/strong&gt; &lt;strong&gt;static&lt;/strong&gt; Value L(&lt;strong&gt;int&lt;/strong&gt; value) { &lt;strong&gt;return&lt;/strong&gt; &lt;strong&gt;new&lt;/strong&gt; Value(Policy.FromInt(value)); }
    }
&lt;/pre&gt;
&lt;p&gt;What the &lt;code&gt;Value&lt;/code&gt; struct does is allows you to use the type &lt;code&gt;Value&lt;/code&gt; in place of the type &lt;code&gt;T&lt;/code&gt; whenever you want to 
use operators. When operators are used you only need to ensure one sub-expression is promoted to &lt;code&gt;Value&lt;/code&gt; and the implict operator will
take care of the rest.&lt;/p&gt;
&lt;p&gt;One remaining oddness is using literals. Implicit operators have there limits which makes using literal a bit strange. This was also odd in the 
&lt;a href="http://www.removingalldoubt.com/PermaLink.aspx/f712e487-a6f5-4a65-a718-5ce580f399a8"&gt;Policy&lt;/a&gt; post as well and I used the same trick to make it a little less cumbersome. I introduced
a static method &lt;code&gt;L()&lt;/code&gt; that takes an integer and converts it to &lt;code&gt;Value&lt;/code&gt; allowing you to use integer literals by calling &lt;code&gt;FromInt()&lt;/code&gt; I introduced earlier. You can 
extend to this to allow other types by repeating the pattern for, say &lt;code&gt;&lt;strong&gt;double&lt;/strong&gt;&lt;/code&gt;, allowing you to use &lt;code&gt;&lt;strong&gt;double&lt;/strong&gt;&lt;/code&gt; literals as well. I didn't 
because I didn't need it for my example (but probably will if I try to implement something more complicated.
&lt;/p&gt;
&lt;p&gt;To bind the actual data type to provide the data type and the policy. To make this simpler I created two create implementations of &lt;code&gt;Math&lt;/code&gt;.&lt;/p&gt;
&lt;pre class="code"&gt;
  &lt;strong&gt;class&lt;/strong&gt; DoubleMath : Math&amp;lt;&lt;strong&gt;double&lt;/strong&gt;, DoubleOperatorPolicy&amp;gt; { }
  &lt;strong&gt;class&lt;/strong&gt; DecimalMath : Math&amp;lt;&lt;strong&gt;decimal&lt;/strong&gt;, DecimalOperatorPolicy&amp;gt; { }
&lt;/pre&gt;
&lt;p&gt;Calling the average method looks like,&lt;/p&gt;
&lt;pre class="code"&gt;
    &lt;strong&gt;var&lt;/strong&gt; resultDouble = DoubleMath.Average(1, 2, 3, 4, 5);
    &lt;strong&gt;var&lt;/strong&gt; resultDecimal = DecimalMath.Average(1, 2, 3, 4, 5);
&lt;/pre&gt;
&lt;p&gt;It should be straight forward to see how this could be adapted to a &lt;code&gt;Financial&lt;/code&gt; class, as Luca was trying to build, and how the routines could
be made independent of the data type used in the calculations.&lt;/p&gt;
&lt;p&gt;There you have it. Policies can be used to simulate &lt;code&gt;INumeric&lt;/code&gt; without having to resort to using &lt;code&gt;&lt;strong&gt;dynamic&lt;/strong&gt;&lt;/code&gt;.&lt;/p&gt;
&lt;p&gt;Edit: Mar 9, 2009: Fixed HTML formatting error
&lt;/body&gt;
                </description>
      <comments>http://www.removingalldoubt.com/commentview.aspx/66b75287-2a94-415c-88b1-9778adffb406</comments>
      <category>Programming</category>
    </item>
    <item>
      <title>Zero the value is not</title>
      <guid>http://www.removingalldoubt.com/permalink.aspx/1d2c1827-9b4d-493e-88ba-10ab27c0dae6</guid>
      <link>http://www.removingalldoubt.com/permalink.aspx/1d2c1827-9b4d-493e-88ba-10ab27c0dae6</link>
      <pubDate>Sun, 31 Aug 2008 18:41:05 GMT</pubDate>
      <description>&lt;body xmlns="http://www.w3.org/1999/xhtml"&gt;
&lt;p&gt;One of my pet-peeves is code written like this,&lt;/p&gt;
&lt;blockquote&gt;&lt;pre class="code"&gt;&lt;strong&gt;if&lt;/strong&gt; (0 != value) { ... }&lt;/pre&gt;&lt;/blockquote&gt;

&lt;p&gt;This reads backwards to me. I hear echoes of 
&lt;a href="http://en.wikipedia.org/wiki/Frank_Oz"&gt;Frank Oz&lt;/a&gt; in my head, &amp;quot;if zero 
the value is not&amp;quot;. As cute as this dialect is coming from a pointy-eared muppet, 
it still takes a bit to translate back into the more common English phrasing, 
&amp;quot;if the value is not zero&amp;quot;. It seems programmers who insist on writing in this style 
have forgotten that their source should be readable as well as executable. Don&amp;#39;t 
force your readers to have to do grammar gymnastics as well as having to 
decipher your algorithmic gynmastics.&lt;/p&gt;
&lt;p&gt;Once upon a time, this was considered good style in order to avoid accidentally 
writing something like,&lt;/p&gt;
&lt;blockquote&gt;&lt;pre class="code"&gt;&lt;strong&gt;if&lt;/strong&gt; (value = 0) { ... }&lt;/pre&gt;&lt;/blockquote&gt;

&lt;p&gt;In C#, this is illegal. In most (all?) modern C and C++ compilers, this will 
generate a warning. (You do compile with warnings reported as errors right?) 
There ceases to be a good reason to write test expressions backwards. Let&amp;#39;s let 
this style rest in peace.&lt;/p&gt;
&lt;p&gt;Even if you think the above form has some redeeming value, let&amp;#39;s all agree 
that any programmer that voluntarily writes something like,&lt;/p&gt;
&lt;blockquote&gt;&lt;pre class="code"&gt;&lt;strong&gt;if&lt;/strong&gt; (&lt;strong&gt;false&lt;/strong&gt; == value) { ... }&lt;/pre&gt;&lt;/blockquote&gt;

&lt;p&gt;should have an electric shock sent directly through their keyboard.&lt;/p&gt;
&lt;/body&gt;</description>
      <body xmlns="http://www.w3.org/1999/xhtml">
        <p>One of my pet-peeves is code written like this,</p>
        <blockquote>
          <pre class="code">
            <strong>if</strong> (0 != value) { ... }</pre>
        </blockquote>
        <p>This reads backwards to me. I hear echoes of 
<a href="http://en.wikipedia.org/wiki/Frank_Oz">Frank Oz</a> in my head, "if zero 
the value is not". As cute as this dialect is coming from a pointy-eared muppet, 
it still takes a bit to translate back into the more common English phrasing, 
"if the value is not zero". It seems programmers who insist on writing in this style 
have forgotten that their source should be readable as well as executable. Don't 
force your readers to have to do grammar gymnastics as well as having to 
decipher your algorithmic gynmastics.</p>
        <p>Once upon a time, this was considered good style in order to avoid accidentally 
writing something like,</p>
        <blockquote>
          <pre class="code">
            <strong>if</strong> (value = 0) { ... }</pre>
        </blockquote>
        <p>In C#, this is illegal. In most (all?) modern C and C++ compilers, this will 
generate a warning. (You do compile with warnings reported as errors right?) 
There ceases to be a good reason to write test expressions backwards. Let's let 
this style rest in peace.</p>
        <p>Even if you think the above form has some redeeming value, let's all agree 
that any programmer that voluntarily writes something like,</p>
        <blockquote>
          <pre class="code">
            <strong>if</strong> (<strong>false</strong> == value) { ... }</pre>
        </blockquote>
        <p>should have an electric shock sent directly through their keyboard.</p>
      </body>
      <comments>http://www.removingalldoubt.com/commentview.aspx/1d2c1827-9b4d-493e-88ba-10ab27c0dae6</comments>
      <category>Programming</category>
    </item>
    <item>
      <title>BeginInvoke's last parameter: What's in a name?</title>
      <guid>http://www.removingalldoubt.com/permalink.aspx/b30e6145-bbfa-4697-992c-61d88f23bf14</guid>
      <link>http://www.removingalldoubt.com/permalink.aspx/b30e6145-bbfa-4697-992c-61d88f23bf14</link>
      <pubDate>Mon, 16 Jun 2008 13:21:57 GMT</pubDate>
      <description>&lt;body xmlns="http://www.w3.org/1999/xhtml"&gt;
&lt;p&gt;I have been playing around with asynchronous programming lately and it 
bothers me that the last parameter to the &lt;em&gt;begin invoke&lt;/em&gt; pattern doesn&amp;#39;t 
have a name that everyone agrees on. The &lt;em&gt;begin invoke&lt;/em&gt; pattern is the 
asynchronous calling pattern were the &lt;code&gt;BeginXxxx()&lt;/code&gt;, such as &lt;code&gt;
Stream.BeginRead()&lt;/code&gt;, takes a set of parameters, a callback method, and 
some, well, thing, at the end that is carried along with the asynchronous 
operation that eventually finds it way into the &lt;code&gt;IAsyncResult&lt;/code&gt;. The 
problem is what do we call that thing? In an informal survey of the methods in 
the BCL that implement this pattern I have found a wide variation. Here is a 
partial list in somewhat order of popularity,&lt;/p&gt;
&lt;ul&gt;
	&lt;li&gt;object&lt;/li&gt;
	&lt;li&gt;stateObject&lt;/li&gt;
	&lt;li&gt;state&lt;/li&gt;
	&lt;li&gt;asyncState&lt;/li&gt;
	&lt;li&gt;extraData&lt;/li&gt;
	&lt;li&gt;data&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;There seems to be little agreement about what to call it. We could pick the 
most prevalent but the name &lt;code&gt;
object&lt;/code&gt; occurs the most often because every 
delegate gets a &lt;code&gt;BeginInvoke()&lt;/code&gt; method created for it and in this 
automatically generated code the parameter is called &lt;code&gt;object&lt;/code&gt;. We can&amp;#39;t standardize on &lt;code&gt;object&lt;/code&gt; because it is a reserved word in several languages so either it would be impossible to 
specify or awkward (i.e. &lt;code&gt;@object&lt;/code&gt; in C#). What I would like is a 
name that we can all use and we can all agree on.&lt;/p&gt;
&lt;p&gt;To name the thing, we first must understand why it it is there at all. It 
exists to hold some state on behalf of the caller. Having the state object makes 
programming against the &lt;em&gt;begin invoke&lt;/em&gt; pattern easier in languages that 
do not have anonymous methods that capture local variables. Consider the 
following program (which intentionally ignores errors because it is only an 
example),&lt;/p&gt;
&lt;blockquote&gt;&lt;pre&gt;
&lt;b&gt;const&lt;/b&gt; &lt;b&gt;string&lt;/b&gt; uriFormat = 
    "http://messenger.services.live.com/users/{0}@apps.messenger.live.com/presence";
&lt;b&gt;const&lt;/b&gt; &lt;b&gt;string&lt;/b&gt; responsePattern = 
    @"""statusText""\s*:\s*""(?&amp;lt;status&amp;gt;\w+).*""displayName""\s*:\s*""(?&amp;lt;name&amp;gt;\w+)""";

&lt;b&gt;static&lt;/b&gt; &lt;b&gt;void&lt;/b&gt; Main(&lt;b&gt;string&lt;/b&gt;[] args) {
    &lt;b&gt;var&lt;/b&gt; uri = &lt;b&gt;string&lt;/b&gt;.Format(uriFormat, args[0]);
    &lt;b&gt;var&lt;/b&gt; request = WebRequest.Create(uri);
    &lt;b&gt;var&lt;/b&gt; result = request.BeginGetResponse(PresenceCallback, request);

    // Other interesting work....

    result.AsyncWaitHandle.WaitOne();
}

&lt;b&gt;private&lt;/b&gt; &lt;b&gt;static&lt;/b&gt; &lt;b&gt;void&lt;/b&gt; PresenceCallback(IAsyncResult result) {
    &lt;b&gt;var&lt;/b&gt; request = result.AsyncState &lt;b&gt;as&lt;/b&gt; WebRequest;
    &lt;b&gt;var&lt;/b&gt; response = request.EndGetResponse(result);
    &lt;b&gt;var&lt;/b&gt; s = &lt;b&gt;new&lt;/b&gt; StreamReader(response.GetResponseStream()).ReadToEnd();
    &lt;b&gt;var&lt;/b&gt; search = &lt;b&gt;new&lt;/b&gt; Regex(responsePattern);
    &lt;b&gt;var&lt;/b&gt; match = search.Match(s);    
    &lt;b&gt;if&lt;/b&gt; (match.Success)
        Console.WriteLine("{0} is {1}", 
           match.Groups["name"].Captures[0].Value, 
           match.Groups["status"].Captures[0].Value);
    &lt;b&gt;else&lt;/b&gt;
        Console.WriteLine("Unexpected response");
}
&lt;/pre&gt;
&lt;/blockquote&gt;

&lt;p&gt;This will get the online status of a Windows Live Messanger account given the 
live ID account number. For example, passing 1afa695addc07e5 as an argument to 
the above will tell whether or not I am online. In this case I am using last 
parameter of the &lt;code&gt;BeginGetResponse()&lt;/code&gt; method to pass the request 
itself. This then is cast back to &lt;code&gt;WebRequest&lt;/code&gt; in the &lt;code&gt;
PresenceCallback()&lt;/code&gt; method so I can call &lt;code&gt;EndGetResponse()&lt;/code&gt; to 
retrieve the actual response. As far at the &lt;code&gt;BeginGetResponse()&lt;/code&gt; call 
is concerned, this value is opaque. It ignores it completely and just supplies 
it blindly in the &lt;code&gt;IAsyncResult&lt;/code&gt;. It makes no assumptions about the 
data at all, it is just something the caller just wants carried around. If I was using 
anonymous delegates in C# this would look a lot better as,&lt;/p&gt;
&lt;blockquote&gt;&lt;pre&gt;&lt;b&gt;static&lt;/b&gt; &lt;b&gt;void&lt;/b&gt; Main(&lt;b&gt;string&lt;/b&gt;[] args) {
    &lt;b&gt;var&lt;/b&gt; uri = &lt;b&gt;string&lt;/b&gt;.Format(uriFormat, args[0]);
    &lt;b&gt;var&lt;/b&gt; request = WebRequest.Create(uri);
    request.BeginGetResponse(result =&amp;gt; {
        &lt;b&gt;var&lt;/b&gt; response = request.EndGetResponse(result);
        &lt;b&gt;var&lt;/b&gt; s = &lt;b&gt;new&lt;/b&gt; StreamReader(response.GetResponseStream()).ReadToEnd();
        &lt;b&gt;var&lt;/b&gt; search = &lt;b&gt;new&lt;/b&gt; Regex(responsePattern);
        &lt;b&gt;var&lt;/b&gt; match = search.Match(s);    
        &lt;b&gt;if&lt;/b&gt; (match.Success)
            Console.WriteLine("{0} is {1}", 
               match.Groups["name"].Captures[0].Value, 
               match.Groups["status"].Captures[0].Value);
        &lt;b&gt;else&lt;/b&gt;
            Console.WriteLine("Unexpected response");
        }   
    }, &lt;b&gt;null&lt;/b&gt;);

    // Other interesting work....

    result.AsyncWaitHandle.WaitOne();
}&lt;/pre&gt;&lt;/blockquote&gt;

&lt;p&gt;Here the request local variable &lt;code&gt;request&lt;/code&gt; is captured 
automatically by the C# compiler and placed into a compiler generated class as a 
field. The compiler generated class also contains the code I supplied in the 
lambda as an instance method. When I refer to response in the lambda the 
reference is automatically translated into a field lookup in the generated 
class. Since &lt;code&gt;request&lt;/code&gt; is already accessible in the lambda I don&amp;#39;t 
need the last parameter to carry anything useful so I pass &lt;code&gt;&lt;strong&gt;null&lt;/strong&gt;&lt;/code&gt;.&lt;/p&gt;
&lt;p&gt;Anonymous methods makes using callbacks much easier but since not all 
languages support anonymous methods or lambdas the BCL standardized on a method 
pattern for &lt;em&gt;begin invoke&lt;/em&gt; that can easily be used by those languages. If the calling pattern did not have a caller state 
object then the work performed automatically by the C# compiler would have to be 
repeated manually by the programmer in these, then, second class languages. The 
.NET team did not want such languages to be second class citizen (especially since neither C# nor VB.NET supported anonymous methods initially) 
so they required the presence of the caller state object parameter.&lt;/p&gt;
&lt;p&gt;Now we know why it is there, what to do we call it? I like &lt;code&gt;state&lt;/code&gt; 
because the parameter represents state the caller want&amp;#39;s to preserve. I don&amp;#39;t 
like &lt;code&gt;object&lt;/code&gt; because it is a common reserved word. I don&amp;#39;t like
&lt;code&gt;stateObject&lt;/code&gt; because a symbol&amp;#39;s type should not be repeated in the 
name, we already know it is an &lt;code&gt;&lt;b&gt;object&lt;/b&gt;&lt;/code&gt; by its type. &lt;code&gt;
asyncState&lt;/code&gt; is acceptable, especially since that is the name it is given 
by &lt;code&gt;IAsyncResult&lt;/code&gt;, but it is a bit redundant, we already know, by 
context, it is asynchronous state. Plus we should avoid abbreviation, like &amp;quot;async&amp;quot;, 
in symbol names (though it is very common, and asynchronous is very very long, 
so not that bad). &lt;code&gt;data&lt;/code&gt; seems fine to me, it is a synonym to state, 
but it is overused. &lt;code&gt;extraData&lt;/code&gt; I cannot, for the life of me, figure 
out. Extra for whom? Extra as opposed to what? Unfortunately, this is the name 
given to the parameter by &lt;code&gt;IHttpAsyncHandler&lt;/code&gt; (see, I told you &amp;quot;async&amp;quot; 
was common).&amp;nbsp; Its name tells me nothing about what I should do with it. It 
is very unclear that this value should be mapped to &lt;code&gt;AsyncState&lt;/code&gt; in &lt;code&gt;IAsyncResult&lt;/code&gt;.&lt;/p&gt;
&lt;p&gt;I propose we call it &lt;code&gt;state&lt;/code&gt;, with an acceptable variation of
&lt;code&gt;asyncState&lt;/code&gt;.&lt;/p&gt;
&lt;p&gt;Now, if changing a parameter name was not a breaking change...&lt;/p&gt;
&lt;hr /&gt;
&lt;p&gt;Trivia: &lt;/p&gt;
&lt;ul&gt;
	&lt;li&gt;The above uses the &lt;a href="http://live.com"&gt;Live Services&lt;/a&gt; that you 
	can find more about &lt;a href="http://dev.live.com"&gt;here&lt;/a&gt;.&lt;/li&gt;
	&lt;li&gt;The IM presence service returns JSON which I parse using a fancy looking
	&lt;code&gt;Regex&lt;/code&gt; instance. I recommend that production code use &lt;code&gt;
	DataContractJsonSerializer() &lt;/code&gt;instead.&lt;/li&gt;
&lt;/ul&gt;
&lt;/body&gt;
                </description>
      <comments>http://www.removingalldoubt.com/commentview.aspx/b30e6145-bbfa-4697-992c-61d88f23bf14</comments>
      <category>Programming</category>
    </item>
    <item>
      <title>If you are using a loop, you're doing it wrong</title>
      <guid>http://www.removingalldoubt.com/permalink.aspx/6080a8a8-bb63-4492-acd2-1398f086fca0</guid>
      <link>http://www.removingalldoubt.com/permalink.aspx/6080a8a8-bb63-4492-acd2-1398f086fca0</link>
      <pubDate>Sat, 29 Mar 2008 16:55:39 GMT</pubDate>
      <description>&lt;body xmlns="http://www.w3.org/1999/xhtml"&gt;
&lt;p&gt;&amp;quot;If you are using a loop, you&amp;#39;re doing it wrong.&amp;quot; &lt;/p&gt;
&lt;p&gt;That is the advice one of my college professors told us when he was teaching us
&lt;a href="http://en.wikipedia.org/wiki/APL_(programming_language)"&gt;APL&lt;/a&gt;. APL 
was designed to perform vector and matrix operations. Programming in APL is an 
exercise in stringing operators together to perform strange and wonderful 
things. Using a loop is just wrong and slows things down.&lt;/p&gt;
&lt;p&gt;It is similar with LINQ, if you are using a loop you are doing it wrong. I 
find myself 
doing a lot of prototyping lately and I am forcing myself to use LINQ; not 
because I don&amp;#39;t like it, far from it, I really like LINQ, but using loops is so 
ingrained into my psyche that I have to stop myself and force myself to think in 
LINQ. Every time I am tempted to write a loop that involves a collection or an 
array I ask myself, could I use LINQ instead? Programmers with more of a 
database background seem to take to LINQ like a duck to water. They think in 
sets and vectors, I don&amp;#39;t, but I am getting there.&lt;/p&gt;
&lt;p&gt;For example sometimes I find myself needing to return an &lt;code&gt;IEnumerable&amp;lt;T&amp;gt;&lt;/code&gt; when 
I have a &lt;code&gt;List&amp;lt;T&amp;gt;&lt;/code&gt; but of a different &lt;code&gt;T&lt;/code&gt;. This often happens when I want to keep 
internal implementation details private. My internal &lt;code&gt;List&amp;lt;T&amp;gt;&lt;/code&gt; might have the 
actual class but I need to return an enumerable for some interface. Before I 
would simply write a loop using the C# 2.0&amp;#39;s &lt;code&gt;&lt;strong&gt;yield&lt;/strong&gt;&lt;/code&gt; syntax,&lt;/p&gt;
&lt;blockquote&gt;
  &lt;pre class="code"&gt;
List&amp;lt;Foo&amp;gt; foos = &lt;strong&gt;new&lt;/strong&gt; List&amp;lt;Foo&amp;gt;();

...

&lt;strong&gt;public&lt;/strong&gt; IEnumerable&amp;lt;IFoo&amp;gt; Foos {
    &lt;strong&gt;get&lt;/strong&gt; {
        &lt;strong&gt;foreach&lt;/strong&gt; (Foo f &lt;strong&gt;in&lt;/strong&gt; foos)
            &lt;strong&gt;yield return&lt;/strong&gt; f;
    }
}&lt;/pre&gt;
&lt;/blockquote&gt;
&lt;p&gt;This loop involves a collection, can I use LINQ? Sure! By using LINQ&amp;#39;s &lt;code&gt;Cast&amp;lt;T&amp;gt;()&lt;/code&gt; method this can be replaced with,&lt;/p&gt;
&lt;blockquote&gt;
  &lt;pre class="code"&gt;
&lt;strong&gt;public&lt;/strong&gt; IEnumerable&amp;lt;IFoo&amp;gt; Foos {
    &lt;strong&gt;get&lt;/strong&gt; { &lt;strong&gt;return&lt;/strong&gt; foos.Cast&amp;lt;IFoo&amp;gt;(); }
}&lt;/pre&gt;
&lt;/blockquote&gt;
&lt;p&gt;If you are trying to find if a list contains an object by some name, you 
could write a loop like,&lt;/p&gt;
&lt;blockquote&gt;&lt;pre class="code"&gt;
&lt;strong&gt;public&lt;/strong&gt; &lt;strong&gt;bool&lt;/strong&gt; Contains(&lt;strong&gt;string&lt;/strong&gt; value) {
    &lt;strong&gt;foreach&lt;/strong&gt; (Foo foo &lt;strong&gt;in&lt;/strong&gt; foos)
        &lt;strong&gt;if&lt;/strong&gt; (foo.Name == value)
            &lt;strong&gt;return&lt;/strong&gt; &lt;strong&gt;true&lt;/strong&gt;;
    &lt;strong&gt;return&lt;/strong&gt; &lt;strong&gt;false&lt;/strong&gt;;
}
&lt;/pre&gt;&lt;/blockquote&gt;
&lt;p&gt;Using LINQ this might look like,&lt;/p&gt;
&lt;blockquote&gt;&lt;pre class="code"&gt;
&lt;strong&gt;public&lt;/strong&gt; &lt;strong&gt;bool&lt;/strong&gt; Contains(&lt;strong&gt;string&lt;/strong&gt; value) {
    &lt;strong&gt;return&lt;/strong&gt; (&lt;strong&gt;from&lt;/strong&gt; foo &lt;strong&gt;in&lt;/strong&gt; foos &lt;strong&gt;where&lt;/strong&gt; foo.Name == value &lt;strong&gt;select&lt;/strong&gt; foo).Any();
}
&lt;/pre&gt;&lt;/blockquote&gt;
&lt;p&gt;A nice thing about LINQ is you can perform complicated queries in pieces. 
With deferred execution of enumerators, this is fairly efficient as well. This 
is really helpful in the debugger. In one chunk of code I was writing I needed to 
coalesce adjacent ranges that are marked with the same text value. Assume you 
have a structure called Range that looks like,&lt;/p&gt;
&lt;blockquote&gt;&lt;pre class="code"&gt;&lt;strong&gt;struct&lt;/strong&gt; Range {
    &lt;strong&gt;public int&lt;/strong&gt; Start;
    &lt;strong&gt;public int&lt;/strong&gt; Length;
}&lt;/pre&gt;&lt;/blockquote&gt;
&lt;p&gt;and another &lt;code&gt;&lt;strong&gt;struct&lt;/strong&gt;&lt;/code&gt; that labels the ranges with names,&lt;/p&gt;
&lt;blockquote&gt;&lt;pre class="code"&gt;&lt;strong&gt;struct&lt;/strong&gt; NamedRange {
    &lt;strong&gt;public string&lt;/strong&gt; Name;
    &lt;strong&gt;public&lt;/strong&gt; Range Range;
}
&lt;/pre&gt;&lt;/blockquote&gt;
&lt;p&gt;Now lets have a routine that calculates the range information over some 
stream,&lt;/p&gt;
&lt;blockquote&gt;&lt;pre class="code"&gt;&lt;strong&gt;public&lt;/strong&gt; IEnumerable&amp;lt;NamedRange&amp;gt; GetNamedRanges(Stream stream) {
    ...
}&lt;/pre&gt;&lt;/blockquote&gt;
&lt;p&gt;Lets assume that name ranges are some things like &amp;quot;whtespace&amp;quot;, &amp;quot;reserved&amp;quot;, 
&amp;quot;identifier&amp;quot;, &amp;quot;number&amp;quot; &amp;quot;string&amp;quot;, etc. as you might expect to receive from a 
lexical scanner like found in this
&lt;a href="http://www.removingalldoubt.com/PermaLink.aspx/f615fab5-28e7-4560-8d9e-db90502a4c5e"&gt;
post&lt;/a&gt;.&lt;/p&gt;
&lt;p&gt;What I want to do with these ranges is to convert the names into styles such 
as you might find referencing a CSS style sheet. So, in effect, I am mapping 
NameRange values to StyledRange values where StyleRange would look something 
like,&lt;/p&gt;
&lt;blockquote&gt;&lt;pre class="code"&gt;&lt;strong&gt;struct&lt;/strong&gt; StyledRange {
    &lt;strong&gt;public&lt;/strong&gt; Style Style;
    &lt;strong&gt;public&lt;/strong&gt; Range Range;
}&lt;/pre&gt;&lt;/blockquote&gt;
&lt;p&gt;Lets create a dictionary that maps range names to styles such as,&lt;/p&gt;
&lt;blockquote&gt;&lt;pre cla="code"&gt;styleMap["number"] = &lt;strong&gt;new&lt;/strong&gt; Style() { Name = "green" };
styleMap["reserved"] = &lt;strong&gt;new&lt;/strong&gt; Style() { Name = "bold" };&lt;/pre&gt;&lt;/blockquote&gt;
&lt;p&gt;I only wanted to highlight numbers and reserved words, for everything 
else I will use the default style,&lt;/p&gt;
&lt;blockquote&gt;&lt;pre class="code"&gt;defaultStyle = &lt;strong&gt;new&lt;/strong&gt; Style { Name = "normal" };&lt;/pre&gt;&lt;/blockquote&gt;
&lt;p&gt;We can translate our named ranges directly into styled ranges by using a
LINQ query expression such as,&lt;/p&gt;
&lt;blockquote&gt;&lt;pre class="code"&gt;&lt;strong&gt;var&lt;/strong&gt; ranges = GetNamedRanges(stream);
&lt;strong&gt;var&lt;/strong&gt; styledRanges = &lt;strong&gt;from&lt;/strong&gt; range &lt;strong&gt;in&lt;/strong&gt; ranges
                  &lt;strong&gt; select new&lt;/strong&gt; StyledRange() {
                       Style = styleMap.MapOrDefault(range.Name) ?? defaultStyle,
                       Range = range.Range
                   };
&lt;/pre&gt;&lt;/blockquote&gt;
&lt;p&gt;where &lt;code&gt;MapOrDefault()&lt;/code&gt; is an extension method for &lt;code&gt;
IDictionary&amp;lt;TKey, TValue&amp;gt;&lt;/code&gt; that looks like,&lt;/p&gt;
&lt;blockquote&gt;&lt;pre class="code"&gt;&lt;strong&gt;public static&lt;/strong&gt; TValue MapOrDefault&lt;TKey, TValue&gt;(&lt;strong&gt;this&lt;/strong&gt; IDictionary&lt;TKey, TValue&gt; dictionary, TKey key) {
    TValue result;
    &lt;strong&gt;if&lt;/strong&gt; (dictionary.TryGetValue(key, &lt;strong&gt;out&lt;/strong&gt; result))
        &lt;strong&gt;return&lt;/strong&gt; result;
    &lt;strong&gt;return&lt;/strong&gt; &lt;strong&gt;default&lt;/strong&gt;(TValue);
}&lt;/pre&gt;&lt;/blockquote&gt;
&lt;p&gt;which is patterned after the existing LINQ methods for &lt;code&gt;IEnumerable&amp;lt;T&amp;gt;&lt;/code&gt;,
&lt;code&gt;FirstOrDefault()&lt;/code&gt; and &lt;code&gt;LastOrDefault()&lt;/code&gt;.&lt;/p&gt;
&lt;p&gt;Since many of the ranges that have different names will have the same style, it 
would be nice to coalesce adjacent styles together so no two adjacent ranges 
have the same style. In other words, we only want a new styled range when the 
style changes. The above query expression just produces a one-to-one 
mapping of named range to styled range. What we need is something that will 
merge adjacent ranges. Do do this I will introduce another extension method,
&lt;code&gt;Reduce&amp;lt;T&amp;gt;()&lt;/code&gt; for &lt;code&gt;IEnumerable&amp;lt;T&amp;gt;&lt;/code&gt;,&lt;/p&gt;
&lt;blockquote&gt;&lt;pre class="code"&gt;&lt;strong&gt;public static&lt;/strong&gt; IEnumerable&amp;lt;T&amp;gt; Reduce&amp;lt;T&amp;gt;(&lt;strong&gt;this&lt;/strong&gt; IEnumerable&amp;lt;T&amp;gt; e,
    Func&amp;lt;T, T, &lt;strong&gt;bool&lt;/strong&gt;&amp;gt; match,
    Func&amp;lt;T, T, T&amp;gt; reduce) {
    &lt;strong&gt;var&lt;/strong&gt; en = e.GetEnumerator();
    T last;
    &lt;strong&gt;if&lt;/strong&gt; (en.MoveNext()) {
        last = en.Current;
        &lt;strong&gt;while&lt;/strong&gt; (en.MoveNext()) {
            &lt;strong&gt;if&lt;/strong&gt; (!match(last, en.Current)) {
                &lt;strong&gt;yield return&lt;/strong&gt; last;
                last = en.Current;
            }
            &lt;strong&gt;else&lt;/strong&gt;
                last = reduce(last, en.Current);
        }
        &lt;strong&gt;yield return&lt;/strong&gt; last;
    }
}&lt;/pre&gt;&lt;/blockquote&gt;
&lt;p&gt;What this method does is if two adjacent elements match (as defined by the &lt;code&gt;match&lt;/code&gt; 
delegate returning &lt;code&gt;&lt;strong&gt;true&lt;/strong&gt;&lt;/code&gt;) they will be reduced into one element by calling the &lt;code&gt;reduce&lt;/code&gt; 
delegate. For example, the &lt;code&gt;Sum&amp;lt;T&amp;gt;()&lt;/code &gt;standard extension method could be 
implemented using &lt;code&gt;Reduce&amp;lt;T&amp;gt;()&lt;/code&gt; as,&lt;/p&gt;
&lt;blockquote&gt;&lt;pre class="code"&gt;&lt;strong&gt;var&lt;/strong&gt; sum = numbers.Reduce((a, b) =&amp;gt; true, (a, b) =&amp;gt; a + b).First();&lt;/pre&gt;&lt;/blockquote&gt;
&lt;p&gt;Now that we have &lt;code&gt;Reduce&amp;lt;T&amp;gt;()&lt;/code&gt;, lets reduce the list of styled 
ranges to coalesce the adjacent ranges with the same style. This can be done by,&lt;/p&gt;
&lt;blockquote&gt;&lt;pre class="code"&gt;styledRanges = styledRanges.Reduce(
    (r1, r2) =&amp;gt; r1.Style == r2.Style,
    (r1, r2) =&amp;gt; &lt;strong&gt;new&lt;/strong&gt; StyledRange() {
        Style = r1.Style,
        Range = MergeRanges(r1.Range, r2.Range)});&lt;/pre&gt;&lt;/blockquote&gt;
&lt;p&gt;&lt;code&gt;MergeRanges()&lt;/code&gt; referenced above, is,&lt;/p&gt;
&lt;blockquote&gt;&lt;pre class="code"&gt;Range MergeRanges(Range r1, Range r2) {
    &lt;strong&gt;return new&lt;/strong&gt; Range() { Start = r1.Start, Length = r2.Start - r1.Start + r2.Length };
}&lt;/pre&gt;&lt;/blockquote&gt;
&lt;p&gt;In my example, this took 18 ranges for a typical line of C# source down to 7 
ranges. Pretty good. But I noticed that some of those ranges were styling 
whitespace as &amp;quot;normal&amp;quot;. This seems like a waste; why switch back from 
green to black text for writing whitespace? Why not combine those with 
adjacent ranges instead? A simple approach to this is to add the following code 
prior to mapping the styles,&lt;/p&gt;
&lt;blockquote&gt;&lt;pre class="code"&gt;ranges = ranges.Reduce(
    (r1, r2) =&gt; r1.Name == "whitespace" || r2.Name == "whitespace",
    (r1, r2) =&gt; &lt;strong&gt;new&lt;/strong&gt; NamedRange() {
        Name = r1.Name == "whitespace" ? r2.Name : r1.Name,
        Range = MergeRanges(r1.Range, r2.Range)
    });&lt;/pre&gt;&lt;/blockquote&gt;
&lt;p&gt;This says to merge whitespace ranges with adjacent non-whitespace ranges. 
This reduces the range count from 7 to 4. Not bad from the original 18 and that 
was just for one line of source. This savings adds up quickly over an entire file.&lt;/p&gt;
&lt;p&gt;The complete example, made as a function, looks like,&lt;/p&gt;
&lt;blockquote&gt;&lt;pre class="code"&gt;IEnumerable&amp;lt;StyledRange&amp;gt; StyleRanges(IEnumerable&amp;lt;NamedRange&amp;gt; ranges) {

    &lt;em&gt;// Merge whitespace ranges with adjacent non-whitespace ranges&lt;/em&gt;
    ranges = ranges.Reduce(
        (r1, r2) =&amp;gt; r1.Name == "whitespace" || r2.Name == "whitespace",
        (r1, r2) =&amp;gt; new NamedRange() {
            Name = r1.Name == "whitespace" ? r2.Name : r1.Name,
            Range = MergeRanges(r1.Range, r2.Range)});

    &lt;em&gt;// Map named ranges to styles.&lt;/em&gt;
    &lt;strong&gt;var&lt;/strong&gt; styledRanges = &lt;strong&gt;from&lt;/strong&gt; range &lt;strong&gt;in&lt;/strong&gt; ranges 
                       &lt;strong&gt;select new&lt;/strong&gt; StyledRange() { 
                           Style = styleMap.MapOrDefault(range.Name) ?? defaultStyle,
                           Range = range.Range };

    &lt;em&gt;// Merge adjacent ranges with the same style.&lt;/em&gt;
    styledRanges = styledRanges.Reduce(
        (r1, r2) =&amp;gt; r1.Style == r2.Style,
        (r1, r2) =&amp;gt; &lt;strong&gt;new&lt;/strong&gt; StyledRange() {
            Style = r1.Style,
            Range = MergeRanges(r1.Range, r2.Range)});

    &lt;strong&gt;return&lt;/strong&gt; styledRanges;
}&lt;/pre&gt;
&lt;/blockquote&gt;
&lt;p&gt;There are a few nice things about this function. First, it builds up an &lt;code&gt;
IEnumerable&amp;lt;T&amp;gt;&lt;/code&gt; but this enumerable doesn&amp;#39;t execute until one of its 
enumerators is enumerated. This is due to the deferred execution of enumerators. 
Second, even though deferred execution makes single step debugging challenging, 
you can get a picture of what the function will do by using &lt;code&gt;ToArray()&lt;/code&gt; 
in the watch windows on the intermediate results. This allows you to inspect the 
intermediate result to see if the mapping or reducing is what you expected. 
Third, this routine has no loops. It operates on each enumerable as a set. Now 
some of you will rightly say there is a loop buried in the &lt;code&gt;Reduce&amp;lt;T&amp;gt;()&lt;/code&gt; 
method. True; &lt;code&gt;Reduce&amp;lt;T&amp;gt;()&lt;/code&gt; is just like many other LINQ extension 
methods, they contain loops implied by the returned enumerator. But LINQ allows me to write code that communicates 
what I am trying to do without it being obscured by the details of how it is done. 
I think of LINQ not so much as a set of features in C# but a way of programming. 
A way of programming that, if you are using loops, you are doing it wrong.&lt;/p&gt;
&lt;/body&gt;
                </description>
      <comments>http://www.removingalldoubt.com/commentview.aspx/6080a8a8-bb63-4492-acd2-1398f086fca0</comments>
      <category>Programming</category>
    </item>
    <item>
      <title>Scanners (not the movie)</title>
      <guid>http://www.removingalldoubt.com/permalink.aspx/f615fab5-28e7-4560-8d9e-db90502a4c5e</guid>
      <link>http://www.removingalldoubt.com/permalink.aspx/f615fab5-28e7-4560-8d9e-db90502a4c5e</link>
      <pubDate>Sun, 30 Dec 2007 17:01:58 GMT</pubDate>
      <description>&lt;body xmlns="http://www.w3.org/1999/xhtml"&gt;
&lt;p&gt;In my previous post I introduced a program I wrote to that uses the method 
described in 
&lt;a href="http://www.amazon.com/First-Order-Logic-Raymond-M-Smullyan/dp/0486683702/ref=sr_11_1/102-8843584-4849732?ie=UTF8&amp;amp;qid=1192783059&amp;amp;sr=11-1"&gt;First-Order Logic&lt;/a&gt; by
&lt;a href="http://en.wikipedia.org/wiki/Raymond_Smullyan"&gt;Raymond M. Smullyan&lt;/a&gt; 
to prove an arbitrary propositional logic expression is a tautology. In this 
program I use some techniques that I want to describe. The first is the scanner. 
When writing scanners I have always hand written the scanner. There are two 
primary reasons for this, first I have never found scanners that difficult to 
write and, second, they are very time critical, often taking more than 20% of 
the overall parsing time, and auto-generated scanners are hard to optimize. 
Tableaux uses a hand-written scanner. The code for the scanner is in Scanner.cs 
in the zip file found
&lt;a href="http://removingalldoubt.com/Examples/Tableaux.zip"&gt;here&lt;/a&gt;.&lt;/p&gt;
&lt;p&gt;A scanner is a routine that takes text input and classifies it into a stream 
of tokens. Scanners typically give one token at a time. The scanner is the lowest level of the parsing process. Parsers 
are built on top of scanners and use the scanner results to determine the 
meaning of the source using some kind of grammar. The distinction between the 
parser and the scanner is somewhat arbitrary. You could just consider each 
character of the input as a token and build the parser up from there. Doing this 
is typically slower than a traditional scanner, however, so most parsers use a 
scanner. The line between the scanner and the parser is usually drawn at the 
lexical elements such as identifiers, reserved words, numeric and string 
constants, comments, etc. More formally, a lexical element is a string of 
characters that can be matched and classified by a regular expression. Scanner 
generators, such as &lt;a href="http://en.wikipedia.org/wiki/Lex_programming_tool"&gt;
Lex&lt;/a&gt;, use regular expressions to specify the scanner.&lt;/p&gt;
&lt;p&gt;The trick to a fast scanner is to reduce the per-character cost of the 
scanner. One way to do this is to make sure you are executing the fewest number of instructions 
per-character-scanned as possible. A few of tricks I use to reduce the 
per-character cost include,&lt;/p&gt;
&lt;ol&gt;
	&lt;li&gt;Use the switch statement&lt;ul&gt;
		&lt;li&gt;That included switch or case statement typically heavily optimize 
		the result, often generating jump tables.&lt;/li&gt;
	&lt;/ul&gt;
	&lt;/li&gt;
	&lt;li&gt;Pull fields into local variables and only write them at the before 
	returning.&lt;ul&gt;
		&lt;li&gt;Local variables can be mapped to registers during code generation. 
		Fields never will be. Stores to global memory (i.e. a field of a object 
		allocated from the heap) are very hard for code generators to optimize. 
		Local variable are much easier.&lt;/li&gt;
	&lt;/ul&gt;
	&lt;/li&gt;
	&lt;li&gt;Make checking for boundaries (end of file or end of buffer) appear as a 
	character.&lt;ul&gt;
		&lt;li&gt;This merges the end-of-file check with character classification.&lt;/li&gt;
		&lt;li&gt;In this case I use the character value 0 to indicate end of file. If 
		I was willing to use unsafe code I would have taken advantage of the 
		fact that the CLR ensures a 0 value at the end of every string.&lt;/li&gt;
	&lt;/ul&gt;
	&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;One thing that looks slow that isn&amp;#39;t is the GetChar() routine. Normally you 
would see that and think I am paying for a CALL/RET pair but his gets inlined in 
retail. I am paying for the end of buffer check every character but, as noted 
above, this can be removed if I wanted to use unsafe code, definitely overkill 
for a small program like tableaux.&lt;/p&gt;
&lt;p&gt;I went a bit overboard, intentionally, with identifier. It handles C# style 
identifiers, handling Unicode letter and number classifications. To avoid 
calling the Unicode classification routines for every character I hard-coded the 
ASCII part and only call the Unicode classification routines when I encounter a 
non-ASCII potential identifier character. It is not that the classification 
routines are slow, it is that every cycle counts in the scanner and avoiding the 
CALL/RET and character table look is significant for file that contain mostly 
ASCII characters. Note also that I hard-code some non-identifier characters in 
the identifier internal loop. This avoids calling the Unicode classification 
routines for those character, which are the most common characters you might 
find after an identifier, which avoids calling the Unicode classification routines 
at all for most input.&lt;/p&gt;

&lt;/body&gt;
                </description>
      <body xmlns="http://www.w3.org/1999/xhtml">
        <p>In my previous post I introduced a program I wrote to that uses the method 
described in 
<a href="http://www.amazon.com/First-Order-Logic-Raymond-M-Smullyan/dp/0486683702/ref=sr_11_1/102-8843584-4849732?ie=UTF8&amp;qid=1192783059&amp;sr=11-1">First-Order Logic</a> by
<a href="http://en.wikipedia.org/wiki/Raymond_Smullyan">Raymond M. Smullyan</a> 
to prove an arbitrary propositional logic expression is a tautology. In this 
program I use some techniques that I want to describe. The first is the scanner. 
When writing scanners I have always hand written the scanner. There are two 
primary reasons for this, first I have never found scanners that difficult to 
write and, second, they are very time critical, often taking more than 20% of 
the overall parsing time, and auto-generated scanners are hard to optimize. 
Tableaux uses a hand-written scanner. The code for the scanner is in Scanner.cs 
in the zip file found
<a href="http://removingalldoubt.com/Examples/Tableaux.zip">here</a>.</p>
        <p>A scanner is a routine that takes text input and classifies it into a stream 
of tokens. Scanners typically give one token at a time. The scanner is the lowest level of the parsing process. Parsers 
are built on top of scanners and use the scanner results to determine the 
meaning of the source using some kind of grammar. The distinction between the 
parser and the scanner is somewhat arbitrary. You could just consider each 
character of the input as a token and build the parser up from there. Doing this 
is typically slower than a traditional scanner, however, so most parsers use a 
scanner. The line between the scanner and the parser is usually drawn at the 
lexical elements such as identifiers, reserved words, numeric and string 
constants, comments, etc. More formally, a lexical element is a string of 
characters that can be matched and classified by a regular expression. Scanner 
generators, such as <a href="http://en.wikipedia.org/wiki/Lex_programming_tool">
Lex</a>, use regular expressions to specify the scanner.</p>
        <p>The trick to a fast scanner is to reduce the per-character cost of the 
scanner. One way to do this is to make sure you are executing the fewest number of instructions 
per-character-scanned as possible. A few of tricks I use to reduce the 
per-character cost include,</p>
        <ol>
          <li>Use the switch statement<ul><li>That included switch or case statement typically heavily optimize 
		the result, often generating jump tables.</li></ul></li>
          <li>Pull fields into local variables and only write them at the before 
	returning.<ul><li>Local variables can be mapped to registers during code generation. 
		Fields never will be. Stores to global memory (i.e. a field of a object 
		allocated from the heap) are very hard for code generators to optimize. 
		Local variable are much easier.</li></ul></li>
          <li>Make checking for boundaries (end of file or end of buffer) appear as a 
	character.<ul><li>This merges the end-of-file check with character classification.</li><li>In this case I use the character value 0 to indicate end of file. If 
		I was willing to use unsafe code I would have taken advantage of the 
		fact that the CLR ensures a 0 value at the end of every string.</li></ul></li>
        </ol>
        <p>One thing that looks slow that isn't is the GetChar() routine. Normally you 
would see that and think I am paying for a CALL/RET pair but his gets inlined in 
retail. I am paying for the end of buffer check every character but, as noted 
above, this can be removed if I wanted to use unsafe code, definitely overkill 
for a small program like tableaux.</p>
        <p>I went a bit overboard, intentionally, with identifier. It handles C# style 
identifiers, handling Unicode letter and number classifications. To avoid 
calling the Unicode classification routines for every character I hard-coded the 
ASCII part and only call the Unicode classification routines when I encounter a 
non-ASCII potential identifier character. It is not that the classification 
routines are slow, it is that every cycle counts in the scanner and avoiding the 
CALL/RET and character table look is significant for file that contain mostly 
ASCII characters. Note also that I hard-code some non-identifier characters in 
the identifier internal loop. This avoids calling the Unicode classification 
routines for those character, which are the most common characters you might 
find after an identifier, which avoids calling the Unicode classification routines 
at all for most input.</p>
      </body>
      <comments>http://www.removingalldoubt.com/commentview.aspx/f615fab5-28e7-4560-8d9e-db90502a4c5e</comments>
      <category>Programming</category>
    </item>
    <item>
      <title>To b | !b, that is the question</title>
      <guid>http://www.removingalldoubt.com/permalink.aspx/1234d0f1-4ecd-424b-b2a0-cf855148f19b</guid>
      <link>http://www.removingalldoubt.com/permalink.aspx/1234d0f1-4ecd-424b-b2a0-cf855148f19b</link>
      <pubDate>Wed, 19 Dec 2007 21:10:53 GMT</pubDate>
      <description>&lt;body xmlns="http://www.w3.org/1999/xhtml"&gt;
   &lt;p&gt;When I was reading 
&lt;a href="http://www.amazon.com/First-Order-Logic-Raymond-M-Smullyan/dp/0486683702/ref=sr_11_1/102-8843584-4849732?ie=UTF8&amp;amp;qid=1192783059&amp;amp;sr=11-1"&gt;First-Order Logic&lt;/a&gt; by
&lt;a href="http://en.wikipedia.org/wiki/Raymond_Smullyan"&gt;Raymond M. Smullyan&lt;/a&gt; I 
was fascinated by 
the second chapter in which he describes a method for proving a propositional 
logic expression is a tautology. This method is called the Tableau Method. The Tableau Method is a 
rather straight forward way to prove a statement is always going to be true by 
demonstrating that asserting it is false will result in a contradiction. The 
propositional logic expression language Dr. Smullyan uses is rather simple. I 
present a modified version of it here. My version 
contains a not operator (!), a conjunction operator (&amp;amp;), a disjunction operator 
(|) and an implication operator (→).&lt;sup&gt;&lt;a name="note1_1ref" href="#note1_1"&gt;1&lt;/a&gt;&lt;/sup&gt; For example,&lt;/p&gt;
&lt;p style="margin-left: 40px;"&gt;p &amp;amp; q&lt;/p&gt;
&lt;p&gt;is true when both &lt;em&gt;p&lt;/em&gt; and &lt;em&gt;q&lt;/em&gt; are true; &lt;/p&gt;
&lt;p style="margin-left: 40px"&gt;p | q&lt;/p&gt;
&lt;p&gt;is true when either &lt;em&gt;p&lt;/em&gt; is true or &lt;em&gt;q&lt;/em&gt; is true;&lt;/p&gt;
&lt;p style="margin-left: 40px"&gt;p &lt;span class="style1"&gt;→ q&lt;/span&gt;&lt;/p&gt;
&lt;p&gt;is true when&lt;em&gt; p &lt;/em&gt;is false or &lt;em&gt;p&lt;/em&gt; is true and &lt;em&gt;q&lt;/em&gt; is also 
true; and finally,&lt;/p&gt;
&lt;p style="margin-left: 40px"&gt;!p&lt;/p&gt;
&lt;p&gt;is true only when &lt;em&gt;p&lt;/em&gt; is false. This should be very familiar to any 
programmer. A propositional logic expression is a tautology if it will always be 
true regardless of the value of its propositional variables. An example of a 
simple tautology is,&lt;/p&gt;
&lt;p style="margin-left: 40px"&gt;p | !p&lt;/p&gt;
&lt;p&gt;which will be true if &lt;em&gt;p&lt;/em&gt; is true or false. This statement is always 
true. This can be proven by simply demonstrating that asserting it is false 
results in a contradiction. For example, we assert a statement is false by 
prefixing it with a capital F or true with a capital T. For the above expression 
this would look like,&lt;/p&gt;
&lt;p style="margin-left: 40px"&gt;F p | !p&lt;/p&gt;
&lt;p&gt;For this to be false both of the sub-expressions would also have to be 
false. This would then look like&lt;/p&gt;
&lt;p style="margin-left: 40px"&gt;F p&lt;br/&gt;F !p&lt;/p&gt;
&lt;p&gt;For &lt;em&gt;!p&lt;/em&gt; to be false &lt;em&gt;p&lt;/em&gt; would have to be true, which looks 
like,&lt;/p&gt;
&lt;p style="margin-left: 40px"&gt;T p&lt;/p&gt;
&lt;p&gt;Now we have a contradiction, according to propositional logic, &lt;em&gt;p&lt;/em&gt; cannot be both true and false so &lt;em&gt;
p | !p&lt;/em&gt; must always be true. Using the Tableau Method this would look like,&lt;/p&gt;
&lt;p style="margin-left: 40px"&gt;(1) F p | !p&lt;br/&gt;(2) F p (1)&lt;br/&gt;(3) F !p (1)&lt;br/&gt;(4) T p (3)&lt;br/&gt;X&lt;/p&gt;
&lt;p&gt;where the X indicates that the tableau ends in a contradiction (i.e. is 
closed) and the 
numbers to the left label the expressions and the numbers to the right indicate 
which expression the assertion is derived from. To produce a tableau you first 
assert the expression is false then use the following table to add assertions,&lt;/p&gt;
&lt;table style="width: 100%"&gt;
	&lt;tr&gt;
		&lt;td&gt;&lt;strong&gt;Expression of the form&lt;/strong&gt;&lt;/td&gt;
		&lt;td&gt;&lt;strong&gt;Asserts&lt;/strong&gt;&lt;/td&gt;
	&lt;/tr&gt;
	&lt;tr&gt;
		&lt;td style="width: 273px"&gt;T !p&lt;/td&gt;
		&lt;td&gt;F p&lt;/td&gt;
	&lt;/tr&gt;
	&lt;tr&gt;
		&lt;td style="width: 273px"&gt;F !p&lt;/td&gt;
		&lt;td&gt;T p&lt;/td&gt;
	&lt;/tr&gt;
	&lt;tr&gt;
		&lt;td style="width: 273px"&gt;T p &amp;amp; q&lt;/td&gt;
		&lt;td&gt;T p and T q&lt;/td&gt;
	&lt;/tr&gt;
	&lt;tr&gt;
		&lt;td style="width: 273px"&gt;F p &amp;amp; q&lt;/td&gt;
		&lt;td&gt;F p or F q&lt;/td&gt;
	&lt;/tr&gt;
	&lt;tr&gt;
		&lt;td style="width: 273px"&gt;T p | q&lt;/td&gt;
		&lt;td&gt;T p or T q&lt;/td&gt;
	&lt;/tr&gt;
	&lt;tr&gt;
		&lt;td style="width: 273px"&gt;F p | q&lt;/td&gt;
		&lt;td&gt;F p and F q&lt;/td&gt;
	&lt;/tr&gt;
	&lt;tr&gt;
		&lt;td style="width: 273px"&gt;T p → q&lt;/td&gt;
		&lt;td&gt;F p or T q&lt;/td&gt;
	&lt;/tr&gt;
	&lt;tr&gt;
		&lt;td style="width: 273px"&gt;F p → q&lt;/td&gt;
		&lt;td&gt;T p and F q&lt;/td&gt;
	&lt;/tr&gt;
&lt;/table&gt;
&lt;p&gt;When two expressions are asserted the table might branch. If the above table 
says &amp;quot;and&amp;quot; then both statement are asserted directly, but if it contains an &amp;quot;or&amp;quot; 
then both assertions must lead to a contradiction independently. For example, 
consider wanting to prove the transitive property of the implication operator, 
that is &lt;em&gt;(p→q &amp;amp; q→r) → (p→r)&lt;/em&gt;, this would start off with adding asserts 
until we are required to branch,&lt;/p&gt;
&lt;p style="margin-left: 40px"&gt;
  (1) F (p→q &amp;amp; q→r) → (p→r)&lt;br/&gt;
  (2) T p→q &amp;amp; q→r (1)&lt;br/&gt;
  (3) F p→r (1)&lt;br/&gt;
  (4) T p→q (2)&lt;br/&gt;
  (5) T q→r (2)&lt;br/&gt;
  (6) T p (3)&lt;br/&gt;
  (7) F r (3)&lt;br/&gt;
&lt;/p&gt;
&lt;p&gt;We now have to handle (4) and (5) with require us to branch the table. The first branch is 
the &lt;em&gt;F p&lt;/em&gt; branch,&lt;/p&gt;
&lt;p style="margin-left: 40px"&gt;
  (8) F p (4)&lt;br/&gt;
  X
&lt;/p&gt;
&lt;p&gt;This lead immediately to a contradiction because of (6) so this branch of the tableau is closed. We now need
handle the &lt;em&gt;T q&lt;/em&gt; branch,&lt;/p&gt;
&lt;p style="margin-left: 40px"&gt;
  (9) T q (4)
&lt;/p&gt;
&lt;p&gt;This doesn't lead to an immediate contradiction so we need to branch again for (5). The first
branch for (5) looks like&lt;/p&gt;
&lt;p style="margin-left: 40px"&gt;
  (10) F q (5)&lt;br/&gt;
  X
&lt;/p&gt;
&lt;p&gt;This again leads to an immediate contradiction, we already asserted
that &lt;em&gt;q&lt;/em&gt; must be true in (9). The second branch for (5) is the &lt;em&gt;T r&lt;/em&gt; branch.&lt;/p&gt;
&lt;p style="margin-left: 40px"&gt;
  (11) T r (5)&lt;br/&gt;
  X
&lt;/p&gt;
&lt;p&gt;This also lead to an immediate contradiction because of (7). Since all 
branches lead to a contradiction the original expression must always be true.&lt;/p&gt;
&lt;p&gt;Putting this altogether we get,&lt;/p&gt;
&lt;table&gt;
&lt;tr&gt;
&lt;td&gt;
&lt;p&gt;
  (1) F (p→q &amp;amp; q→r) → (p→r)&lt;br/&gt;
  (2) T p→q &amp;amp; q→r (1)&lt;br/&gt;
  (3) F p→r (1)&lt;br/&gt;
  (4) T p→q (2)&lt;br/&gt;
  (5) T q→r (2)&lt;br/&gt;
  (6) T p (3)&lt;br/&gt;
  (7) F r (3)&lt;br/&gt;
&lt;/p&gt;
&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;
&lt;table style="text-align: center;"&gt;
&lt;tr&gt;
&lt;td valign="top" style="border-right-color: black; 
	border-right-style:solid; 
	border-right-width:thin; 
	padding-right: 10px"&gt;
&lt;p&gt;
  (8) F p (4)&lt;br/&gt;
  X
&lt;/p&gt;
&lt;/td&gt;
&lt;td style="padding-right:10px;"&gt;
&lt;p&gt;
  (9) T q (4)
&lt;/p&gt;
&lt;table &gt;
&lt;tr&gt;
&lt;td style="border-right-color: black; 
	border-right-style:solid; 
	border-right-width:thin; 
	padding-right: 10px"&gt;
&lt;p &gt;
  (10) F q (5)&lt;br/&gt;
  X
&lt;/p&gt;
&lt;/td&gt;
&lt;td style="padding-right:10px;"&gt;
&lt;p &gt;
  (11) T r (5)&lt;br/&gt;
  X
&lt;/p&gt;
&lt;/td&gt;
&lt;/tr&gt;
&lt;/table&gt;
&lt;/td&gt;
&lt;/tr&gt;
&lt;/table&gt;
&lt;/td&gt;
&lt;/tr&gt;
&lt;/table&gt;
&lt;p&gt;This is a simple and elegant way to demonstrate proof by contradiction. Of 
course I just had to write a program to tell me whether an 
arbitrary propositional logic expression is a tautology and automatically 
generate the tableau.&lt;/p&gt;
&lt;p&gt;You can find the source project that is works with the just released Visual 
Studio 2008 &lt;a href="http://removingalldoubt.com/Examples/Tableaux.zip"&gt;here&lt;/a&gt;. It requires VS 2008 because I am addicted to some of the new 
C# features, especially the &lt;b&gt;&lt;code&gt;var&lt;/code&gt;&lt;/b&gt; keyword.&lt;/p&gt;
&lt;hr /&gt;
&lt;p&gt;&lt;a name="note1_1"&gt;&lt;sup&gt;1&lt;/sup&gt;&lt;/a&gt; Dr. Sumullyan uses different characters for his operators 
but his characters are not as commonly included in browser fonts and are not as easy to 
type on a standard keyboard (using &lt;span class="style3"&gt;-&amp;gt;&lt;/span&gt; as a synonym 
of →) as the ones I use. &lt;a href="#note1_1ref"&gt;&amp;lt;&amp;lt; back&lt;/a&gt;&lt;/p&gt;

&lt;/body&gt;
                </description>
      <body xmlns="http://www.w3.org/1999/xhtml">
        <p>When I was reading 
<a href="http://www.amazon.com/First-Order-Logic-Raymond-M-Smullyan/dp/0486683702/ref=sr_11_1/102-8843584-4849732?ie=UTF8&amp;qid=1192783059&amp;sr=11-1">First-Order Logic</a> by
<a href="http://en.wikipedia.org/wiki/Raymond_Smullyan">Raymond M. Smullyan</a> I 
was fascinated by 
the second chapter in which he describes a method for proving a propositional 
logic expression is a tautology. This method is called the Tableau Method. The Tableau Method is a 
rather straight forward way to prove a statement is always going to be true by 
demonstrating that asserting it is false will result in a contradiction. The 
propositional logic expression language Dr. Smullyan uses is rather simple. I 
present a modified version of it here. My version 
contains a not operator (!), a conjunction operator (&amp;), a disjunction operator 
(|) and an implication operator (→).<sup><a name="note1_1ref" href="#note1_1">1</a></sup> For example,</p>
        <p style="margin-left: 40px;">p &amp; q</p>
        <p>is true when both <em>p</em> and <em>q</em> are true; </p>
        <p style="margin-left: 40px">p | q</p>
        <p>is true when either <em>p</em> is true or <em>q</em> is true;</p>
        <p style="margin-left: 40px">p <span class="style1">→ q</span></p>
        <p>is true when<em> p </em>is false or <em>p</em> is true and <em>q</em> is also 
true; and finally,</p>
        <p style="margin-left: 40px">!p</p>
        <p>is true only when <em>p</em> is false. This should be very familiar to any 
programmer. A propositional logic expression is a tautology if it will always be 
true regardless of the value of its propositional variables. An example of a 
simple tautology is,</p>
        <p style="margin-left: 40px">p | !p</p>
        <p>which will be true if <em>p</em> is true or false. This statement is always 
true. This can be proven by simply demonstrating that asserting it is false 
results in a contradiction. For example, we assert a statement is false by 
prefixing it with a capital F or true with a capital T. For the above expression 
this would look like,</p>
        <p style="margin-left: 40px">F p | !p</p>
        <p>For this to be false both of the sub-expressions would also have to be 
false. This would then look like</p>
        <p style="margin-left: 40px">F p<br />F !p</p>
        <p>For <em>!p</em> to be false <em>p</em> would have to be true, which looks 
like,</p>
        <p style="margin-left: 40px">T p</p>
        <p>Now we have a contradiction, according to propositional logic, <em>p</em> cannot be both true and false so <em>
p | !p</em> must always be true. Using the Tableau Method this would look like,</p>
        <p style="margin-left: 40px">(1) F p | !p<br />(2) F p (1)<br />(3) F !p (1)<br />(4) T p (3)<br />X</p>
        <p>where the X indicates that the tableau ends in a contradiction (i.e. is 
closed) and the 
numbers to the left label the expressions and the numbers to the right indicate 
which expression the assertion is derived from. To produce a tableau you first 
assert the expression is false then use the following table to add assertions,</p>
        <table style="width: 100%">
          <tr>
            <td>
              <strong>Expression of the form</strong>
            </td>
            <td>
              <strong>Asserts</strong>
            </td>
          </tr>
          <tr>
            <td style="width: 273px">T !p</td>
            <td>F p</td>
          </tr>
          <tr>
            <td style="width: 273px">F !p</td>
            <td>T p</td>
          </tr>
          <tr>
            <td style="width: 273px">T p &amp; q</td>
            <td>T p and T q</td>
          </tr>
          <tr>
            <td style="width: 273px">F p &amp; q</td>
            <td>F p or F q</td>
          </tr>
          <tr>
            <td style="width: 273px">T p | q</td>
            <td>T p or T q</td>
          </tr>
          <tr>
            <td style="width: 273px">F p | q</td>
            <td>F p and F q</td>
          </tr>
          <tr>
            <td style="width: 273px">T p → q</td>
            <td>F p or T q</td>
          </tr>
          <tr>
            <td style="width: 273px">F p → q</td>
            <td>T p and F q</td>
          </tr>
        </table>
        <p>When two expressions are asserted the table might branch. If the above table 
says "and" then both statement are asserted directly, but if it contains an "or" 
then both assertions must lead to a contradiction independently. For example, 
consider wanting to prove the transitive property of the implication operator, 
that is <em>(p→q &amp; q→r) → (p→r)</em>, this would start off with adding asserts 
until we are required to branch,</p>
        <p style="margin-left: 40px">
  (1) F (p→q &amp; q→r) → (p→r)<br />
  (2) T p→q &amp; q→r (1)<br />
  (3) F p→r (1)<br />
  (4) T p→q (2)<br />
  (5) T q→r (2)<br />
  (6) T p (3)<br />
  (7) F r (3)<br /></p>
        <p>We now have to handle (4) and (5) with require us to branch the table. The first branch is 
the <em>F p</em> branch,</p>
        <p style="margin-left: 40px">
  (8) F p (4)<br />
  X
</p>
        <p>This lead immediately to a contradiction because of (6) so this branch of the tableau is closed. We now need
handle the <em>T q</em> branch,</p>
        <p style="margin-left: 40px">
  (9) T q (4)
</p>
        <p>This doesn't lead to an immediate contradiction so we need to branch again for (5). The first
branch for (5) looks like</p>
        <p style="margin-left: 40px">
  (10) F q (5)<br />
  X
</p>
        <p>This again leads to an immediate contradiction, we already asserted
that <em>q</em> must be true in (9). The second branch for (5) is the <em>T r</em> branch.</p>
        <p style="margin-left: 40px">
  (11) T r (5)<br />
  X
</p>
        <p>This also lead to an immediate contradiction because of (7). Since all 
branches lead to a contradiction the original expression must always be true.</p>
        <p>Putting this altogether we get,</p>
        <table>
          <tr>
            <td>
              <p>
  (1) F (p→q &amp; q→r) → (p→r)<br />
  (2) T p→q &amp; q→r (1)<br />
  (3) F p→r (1)<br />
  (4) T p→q (2)<br />
  (5) T q→r (2)<br />
  (6) T p (3)<br />
  (7) F r (3)<br /></p>
            </td>
          </tr>
          <tr>
            <td>
              <table style="text-align: center;">
                <tr>
                  <td valign="top" style="border-right-color: black; &#xA;	border-right-style:solid; &#xA;	border-right-width:thin; &#xA;	padding-right: 10px">
                    <p>
  (8) F p (4)<br />
  X
</p>
                  </td>
                  <td style="padding-right:10px;">
                    <p>
  (9) T q (4)
</p>
                    <table>
                      <tr>
                        <td style="border-right-color: black; &#xA;	border-right-style:solid; &#xA;	border-right-width:thin; &#xA;	padding-right: 10px">
                          <p>
  (10) F q (5)<br />
  X
</p>
                        </td>
                        <td style="padding-right:10px;">
                          <p>
  (11) T r (5)<br />
  X
</p>
                        </td>
                      </tr>
                    </table>
                  </td>
                </tr>
              </table>
            </td>
          </tr>
        </table>
        <p>This is a simple and elegant way to demonstrate proof by contradiction. Of 
course I just had to write a program to tell me whether an 
arbitrary propositional logic expression is a tautology and automatically 
generate the tableau.</p>
        <p>You can find the source project that is works with the just released Visual 
Studio 2008 <a href="http://removingalldoubt.com/Examples/Tableaux.zip">here</a>. It requires VS 2008 because I am addicted to some of the new 
C# features, especially the <b><code>var</code></b> keyword.</p>
        <hr />
        <p>
          <a name="note1_1">
            <sup>1</sup>
          </a> Dr. Sumullyan uses different characters for his operators 
but his characters are not as commonly included in browser fonts and are not as easy to 
type on a standard keyboard (using <span class="style3">-&gt;</span> as a synonym 
of →) as the ones I use. <a href="#note1_1ref">&lt;&lt; back</a></p>
      </body>
      <comments>http://www.removingalldoubt.com/commentview.aspx/1234d0f1-4ecd-424b-b2a0-cf855148f19b</comments>
      <category>Programming</category>
    </item>
    <item>
      <title>Operators, Generics and Policies II: Adapter Policy</title>
      <guid>http://www.removingalldoubt.com/permalink.aspx/f712e487-a6f5-4a65-a718-5ce580f399a8</guid>
      <link>http://www.removingalldoubt.com/permalink.aspx/f712e487-a6f5-4a65-a718-5ce580f399a8</link>
      <pubDate>Tue, 31 Jul 2007 22:27:00 GMT</pubDate>
      <description>&lt;body xmlns="http://www.w3.org/1999/xhtml"&gt;
&lt;p&gt;The mixin technique in my 
&lt;a href="http://www.removingalldoubt.com/PermaLink.aspx/b97049b8-c16d-430b-991b-0a3922b6eea7"&gt;last post&lt;/a&gt; was a bit awkward to use 
with generic 
methods. It is much less awkward to use for classes, however. For example, if 
you want an expression evaluator much like I posted
&lt;a href="http://www.removingalldoubt.com/commentview.aspx/bece3be7-04a1-4130-b1ac-0b88c94e7708"&gt;
here&lt;/a&gt;, but you want to leave the result type open, you can use this technique 
to do it.&lt;/p&gt;
&lt;p&gt;First, I declared a policy interface for the operators I wanted to abstract 
over,&lt;/p&gt;
&lt;blockquote&gt;&lt;pre&gt;&lt;b&gt;partial&lt;/b&gt; &lt;b&gt;interface&lt;/b&gt; IOperatorPolicy&amp;lt;T&amp;gt; {
    T Add(T a, T b);
    T Subtract(T a, T b);
    T Multiply(T a, T b);
    T Divide(T a, T b);
}&lt;/pre&gt;&lt;/blockquote&gt;

&lt;p&gt;Second, I created the operator policies for &lt;code&gt;&lt;strong&gt;int&lt;/strong&gt;&lt;/code&gt; 
and &lt;code&gt;&lt;strong&gt;double&lt;/strong&gt;&lt;/code&gt;. I could have created more, &lt;code&gt;
&lt;strong&gt;decimal&lt;/strong&gt;&lt;/code&gt;, &lt;code&gt;&lt;strong&gt;float&lt;/strong&gt;&lt;/code&gt;, etc. but 
two is sufficient for demonstration.&lt;/p&gt;
&lt;blockquote&gt;&lt;pre&gt;&lt;strong&gt;partial&lt;/strong&gt; &lt;b&gt;struct&lt;/b&gt; IntOperatorPolicy : IOperatorPolicy&amp;lt;&lt;b&gt;int&lt;/b&gt;&amp;gt; {
    &lt;b&gt;int&lt;/b&gt; IOperatorPolicy&amp;lt;&lt;b&gt;int&lt;/b&gt;&amp;gt;.Add(&lt;b&gt;int&lt;/b&gt; a, &lt;b&gt;int&lt;/b&gt; b) { &lt;b&gt;return&lt;/b&gt; a + b; }
    &lt;b&gt;int&lt;/b&gt; IOperatorPolicy&amp;lt;&lt;b&gt;int&lt;/b&gt;&amp;gt;.Subtract(&lt;b&gt;int&lt;/b&gt; a, &lt;b&gt;int&lt;/b&gt; b) { &lt;b&gt;return&lt;/b&gt; a - b; }
    &lt;b&gt;int&lt;/b&gt; IOperatorPolicy&amp;lt;&lt;b&gt;int&lt;/b&gt;&amp;gt;.Multiply(&lt;b&gt;int&lt;/b&gt; a, &lt;b&gt;int&lt;/b&gt; b) { &lt;b&gt;return&lt;/b&gt; a * b; }
    &lt;b&gt;int&lt;/b&gt; IOperatorPolicy&amp;lt;&lt;b&gt;int&lt;/b&gt;&amp;gt;.Divide(&lt;b&gt;int&lt;/b&gt; a, &lt;b&gt;int&lt;/b&gt; b) { &lt;b&gt;return&lt;/b&gt; a / b; }
}

&lt;b&gt;partial struct&lt;/b&gt; DoubleOperatorPolicy : IOperatorPolicy&amp;lt;&lt;b&gt;double&lt;/b&gt;&amp;gt; {
    &lt;b&gt;double&lt;/b&gt; IOperatorPolicy&amp;lt;&lt;b&gt;double&lt;/b&gt;&amp;gt;.Add(&lt;b&gt;double&lt;/b&gt; a, &lt;b&gt;double&lt;/b&gt; b) { &lt;b&gt;return&lt;/b&gt; a + b;
    &lt;b&gt;double&lt;/b&gt; IOperatorPolicy&amp;lt;&lt;b&gt;double&lt;/b&gt;&amp;gt;.Subtract(&lt;b&gt;double&lt;/b&gt; a, &lt;b&gt;double&lt;/b&gt; b) { &lt;b&gt;return&lt;/b&gt; a - b; }
    &lt;b&gt;double&lt;/b&gt; IOperatorPolicy&amp;lt;&lt;b&gt;double&lt;/b&gt;&amp;gt;.Multiply(&lt;b&gt;double&lt;/b&gt; a, &lt;b&gt;double&lt;/b&gt; b) { &lt;b&gt;return&lt;/b&gt; a * b; }
    &lt;b&gt;double&lt;/b&gt; IOperatorPolicy&amp;lt;&lt;b&gt;double&lt;/b&gt;&amp;gt;.Divide(&lt;b&gt;double&lt;/b&gt; a, &lt;b&gt;double&lt;/b&gt; b) { &lt;b&gt;return&lt;/b&gt; a / b; }
}&lt;/pre&gt;&lt;/blockquote&gt;

&lt;p&gt;Next are the expression nodes themselves. I wrap them in a generic class 
that takes the parameters. This mitigates some of the clutter caused by the 
policy.&lt;/p&gt;
&lt;blockquote&gt;&lt;pre&gt;&lt;b&gt;partial&lt;/b&gt; &lt;b&gt;class&lt;/b&gt; Expression&amp;lt;T, OperatorPolicy&amp;gt;
    &lt;strong&gt;where&lt;/strong&gt; OperatorPolicy : &lt;b&gt;struct&lt;/b&gt;, IOperatorPolicy&amp;lt;T&amp;gt; {

    &lt;b&gt;static&lt;/b&gt; OperatorPolicy _operatorPolicy = &lt;b&gt;new&lt;/b&gt; OperatorPolicy();

    &lt;b&gt;public&lt;/b&gt; &lt;b&gt;abstract&lt;/b&gt; &lt;b&gt;partial&lt;/b&gt; &lt;b&gt;class&lt;/b&gt; Expr {
        &lt;b&gt;public&lt;/b&gt; &lt;b&gt;abstract&lt;/b&gt; T Evaluate();
    }

    &lt;b&gt;public&lt;/b&gt; &lt;b&gt;partial&lt;/b&gt; &lt;b&gt;class&lt;/b&gt; Literal : Expr {
        &lt;b&gt;private&lt;/b&gt; T _literal;

        &lt;b&gt;public&lt;/b&gt; Literal(T literal) { _literal = literal; }

        &lt;b&gt;public&lt;/b&gt; &lt;b&gt;override&lt;/b&gt; T Evaluate() {
            &lt;b&gt;return&lt;/b&gt; _literal;
        }

        &lt;b&gt;public&lt;/b&gt; &lt;b&gt;override&lt;/b&gt; &lt;b&gt;string&lt;/b&gt; ToString() {
            &lt;b&gt;return&lt;/b&gt; _literal.ToString();
        }
    }

    &lt;b&gt;public&lt;/b&gt; &lt;b&gt;abstract&lt;/b&gt; &lt;b&gt;partial&lt;/b&gt; &lt;b&gt;class&lt;/b&gt; BinaryOp : Expr {
        &lt;b&gt;private&lt;/b&gt; Expr _left;
        &lt;b&gt;private&lt;/b&gt; Expr _right;

        &lt;b&gt;protected&lt;/b&gt; BinaryOp(Expr left, Expr right) { _left = left; _right = right; }

        &lt;b&gt;public&lt;/b&gt; &lt;b&gt;override&lt;/b&gt; T Evaluate() {
            &lt;b&gt;return&lt;/b&gt; EvaluateOp(_left.Evaluate(), _right.Evaluate());
        }

        &lt;b&gt;protected&lt;/b&gt; &lt;b&gt;abstract&lt;/b&gt; T EvaluateOp(T left, T right);
    }

    &lt;b&gt;public&lt;/b&gt; &lt;b&gt;partial&lt;/b&gt; &lt;b&gt;class&lt;/b&gt; Add : BinaryOp {
        &lt;b&gt;public&lt;/b&gt; Add(Expr left, Expr right) : &lt;b&gt;base&lt;/b&gt;(left, right) { }
        &lt;b&gt;protected&lt;/b&gt; &lt;b&gt;override&lt;/b&gt; T EvaluateOp(T left, T right) {
            &lt;b&gt;return&lt;/b&gt; _operatorPolicy.Add(left, right);
        }
    }
    
    &lt;b&gt;public&lt;/b&gt; &lt;b&gt;partial&lt;/b&gt; &lt;b&gt;class&lt;/b&gt; Add : BinaryOp {
        &lt;b&gt;public&lt;/b&gt; Add(Expr left, Expr right) : &lt;b&gt;base&lt;/b&gt;(left, right) { }
        &lt;b&gt;protected&lt;/b&gt; &lt;b&gt;override&lt;/b&gt; T EvaluateOp(T left, T right) {
            &lt;b&gt;return&lt;/b&gt; _operatorPolicy.Add(left, right);
        }
    }

    &lt;b&gt;public&lt;/b&gt; &lt;b&gt;partial&lt;/b&gt; &lt;b&gt;class&lt;/b&gt; Subtract : BinaryOp {
        &lt;b&gt;public&lt;/b&gt; Subtract(Expr left, Expr right) : &lt;b&gt;base&lt;/b&gt;(left, right) { }
        &lt;b&gt;protected&lt;/b&gt; &lt;b&gt;override&lt;/b&gt; T EvaluateOp(T left, T right) {
            &lt;b&gt;return&lt;/b&gt; _operatorPolicy.Subtract(left, right);
        }
    }

    &lt;b&gt;public&lt;/b&gt; &lt;b&gt;partial&lt;/b&gt; &lt;b&gt;class&lt;/b&gt; Multiply : BinaryOp {
        &lt;b&gt;public&lt;/b&gt; Multiply(Expr left, Expr right) : &lt;b&gt;base&lt;/b&gt;(left, right) { }
        &lt;b&gt;protected&lt;/b&gt; &lt;b&gt;override&lt;/b&gt; T EvaluateOp(T left, T right) {
            &lt;b&gt;return&lt;/b&gt; _operatorPolicy.Multiply(left, right);
        }
    }

    &lt;b&gt;public&lt;/b&gt; &lt;b&gt;partial&lt;/b&gt; &lt;b&gt;class&lt;/b&gt; Divide : BinaryOp {
        &lt;b&gt;public&lt;/b&gt; Divide(Expr left, Expr right) : &lt;b&gt;base&lt;/b&gt;(left, right) { }
        &lt;b&gt;protected&lt;/b&gt; &lt;b&gt;override&lt;/b&gt; T EvaluateOp(T left, T right) {
            &lt;b&gt;return&lt;/b&gt; _operatorPolicy.Divide(left, right);
        }
    }
}&lt;/pre&gt;&lt;/blockquote&gt;

&lt;p&gt;Here the &lt;code&gt;Expression&lt;/code&gt; class acts as a container of a family of 
classes. Once you have an instance of one of the &lt;code&gt;Expr&lt;/code&gt; derived classes, calling 
&lt;code&gt;Evaluate()&lt;/code&gt; is straight-forward. Unfortunately, constructing one is a bit of a 
challenge. To get a literal of the &lt;code&gt;&lt;strong&gt;int&lt;/strong&gt;&lt;/code&gt; expression you would need to do,&lt;/p&gt;
&lt;blockquote&gt;&lt;pre&gt;&lt;strong&gt;var&lt;/strong&gt; i1 = &lt;strong&gt;new&lt;/strong&gt; Expression&amp;lt;&lt;strong&gt;int&lt;/strong&gt;, IntOperatorPolicy&amp;gt;.Literal(1);&lt;/pre&gt;&lt;/blockquote&gt;

&lt;p&gt;You can make this a little better by introducing a &lt;code&gt;&lt;strong&gt;static&lt;/strong&gt;&lt;/code&gt; 
method into &lt;code&gt;Expression&lt;/code&gt; like,&lt;/p&gt;
&lt;blockquote&gt;&lt;pre&gt;&lt;b&gt;public&lt;/b&gt; &lt;b&gt;static&lt;/b&gt; Expr L(T literal) {
    &lt;b&gt;return&lt;/b&gt; &lt;b&gt;new&lt;/b&gt; Literal(literal);
}&lt;/pre&gt;&lt;/blockquote&gt;

&lt;p&gt;then the above becomes,&lt;/p&gt;
&lt;blockquote&gt;&lt;pre&gt;&lt;strong&gt;var&lt;/strong&gt; i1 = Expression&amp;lt;&lt;strong&gt;int&lt;/strong&gt;, IntOperatorPolicy&amp;gt;.L(1);&lt;/pre&gt;&lt;/blockquote&gt;
&lt;p&gt;This still a bit awkward especially when you want to construct a more 
complicated expression,&lt;/p&gt;
&lt;blockquote&gt;&lt;pre&gt;&lt;strong&gt;var&lt;/strong&gt; e = &lt;strong&gt;new&lt;/strong&gt; Expression&amp;lt;&lt;strong&gt;int&lt;/strong&gt;, IntOperatorPolicy&amp;gt;.Add(i1, i1);&lt;/pre&gt;&lt;/blockquote&gt;
&lt;p&gt;This can be made significantly better by adding operator overloads to &lt;code&gt;Expr&lt;/code&gt; as 
in,&lt;/p&gt;
&lt;blockquote&gt;&lt;pre&gt;&lt;b&gt;public&lt;/b&gt; &lt;b&gt;abstract&lt;/b&gt; &lt;strong&gt;partial&lt;/strong&gt; &lt;b&gt;class&lt;/b&gt; Expr {
    &lt;b&gt;public&lt;/b&gt; &lt;b&gt;abstract&lt;/b&gt; T Evaluate();
    &lt;b&gt;public&lt;/b&gt; &lt;b&gt;static&lt;/b&gt; Expr &lt;b&gt;operator&lt;/b&gt; +(Expr a, Expr b) {
        &lt;b&gt;return&lt;/b&gt; &lt;b&gt;new&lt;/b&gt; Add(a, b);
    }
    &lt;b&gt;public&lt;/b&gt; &lt;b&gt;static&lt;/b&gt; Expr &lt;b&gt;operator&lt;/b&gt; -(Expr a, Expr b) {
        &lt;b&gt;return&lt;/b&gt; &lt;b&gt;new&lt;/b&gt; Subtract(a, b);
    }
    &lt;b&gt;public&lt;/b&gt; &lt;b&gt;static&lt;/b&gt; Expr &lt;b&gt;operator&lt;/b&gt; *(Expr a, Expr b) {
        &lt;b&gt;return&lt;/b&gt; &lt;b&gt;new&lt;/b&gt; Multiply(a, b);
    }
    &lt;b&gt;public&lt;/b&gt; &lt;b&gt;static&lt;/b&gt; Expr &lt;b&gt;operator&lt;/b&gt; /(Expr a, Expr b) {
        &lt;b&gt;return&lt;/b&gt; &lt;b&gt;new&lt;/b&gt; Divide(a, b);
    }
}&lt;/pre&gt;&lt;/blockquote&gt;
&lt;p&gt;now the &lt;code&gt;e&lt;/code&gt; assignment can look like,&lt;/p&gt;
&lt;blockquote&gt;&lt;pre&gt;&lt;strong&gt;var&lt;/strong&gt; e = i1 + i1;&lt;/pre&gt;&lt;/blockquote&gt;
&lt;p&gt;and finally, to make it look even better you can put the code to create the 
expression in a static method of a class that derives from &lt;code&gt;Expression&lt;/code&gt; and closes the 
type parameters. Here are examples of one for &lt;code&gt;&lt;strong&gt;int&lt;/strong&gt;&lt;/code&gt; and 
a similar one for &lt;code&gt;&lt;strong&gt;double&lt;/strong&gt;&lt;/code&gt;.&lt;/p&gt;
&lt;blockquote&gt;&lt;pre&gt;&lt;b&gt;class&lt;/b&gt; TestInt : Expression&amp;lt;&lt;b&gt;int&lt;/b&gt;, IntOperatorPolicy&amp;gt; {
    &lt;b&gt;public&lt;/b&gt; &lt;b&gt;static&lt;/b&gt; &lt;b&gt;void&lt;/b&gt; Run() {
        &lt;strong&gt;var&lt;/strong&gt; iv = L(1) + L(2) * L(3);
        Console.WriteLine(iv.Evaluate());
    }
}

&lt;b&gt;class&lt;/b&gt; TestDouble : Expression&amp;lt;&lt;b&gt;double&lt;/b&gt;, DoubleOperatorPolicy&amp;gt; {
    &lt;b&gt;public&lt;/b&gt; &lt;b&gt;static&lt;/b&gt; &lt;b&gt;void&lt;/b&gt; Run() {
        &lt;strong&gt;var&lt;/strong&gt; dv = L(1.2) + L(3.4) * L(5.6);
        Console.WriteLine(dv.Evaluate());
    }
}&lt;/pre&gt;&lt;/blockquote&gt;
&lt;p&gt;This shows taking advantage of the C# compiler&amp;#39;s operator overloading to 
produce an expression tree and the use of the &lt;code&gt;L()&lt;/code&gt; method as a sort 
of cast to change a literal of &lt;code&gt;T&lt;/code&gt; into a &lt;code&gt;Literal&amp;lt;T&amp;gt;&lt;/code&gt;. 
The call to &lt;code&gt;Evaluate()&lt;/code&gt; calculates the result of the expression as 
an &lt;code&gt;&lt;strong&gt;int&lt;/strong&gt;&lt;/code&gt; or &lt;code&gt;&lt;strong&gt;double&lt;/strong&gt;&lt;/code&gt;. 
The code generated, as discussed
&lt;a href="http://www.removingalldoubt.com/PermaLink.aspx/b97049b8-c16d-430b-991b-0a3922b6eea7"&gt;
last time&lt;/a&gt;, is quite good when JIT&amp;#39;ing outside the debugger and using 
optimized retail bits.&lt;/p&gt;
&lt;p&gt;This use of a policy &lt;code&gt;&lt;strong&gt;struct&lt;/strong&gt;&lt;/code&gt; is what I refer to 
as an &lt;em&gt;adapter policy&lt;/em&gt;. The &lt;code&gt;Expression&lt;/code&gt; class has an 
abstraction it supports, represented by &lt;code&gt;IOperatorPolicy&amp;lt;T&amp;gt;&lt;/code&gt;, but 
this abstraction is not supported by any of the interesting types you would want 
to pass as &lt;code&gt;Expression&lt;/code&gt;&amp;#39;s &lt;code&gt;T&lt;/code&gt;. This is solved by creating 
an &lt;em&gt;adapter policy&lt;/em&gt; and passing that along with &lt;code&gt;T&lt;/code&gt;. This 
allows a generic type to introduce an abstraction that is unknown to the types 
the generic wants to range over, allow us, as above, to pass &lt;code&gt;int&lt;/code&gt; 
for &lt;code&gt;Expression&lt;/code&gt;&amp;#39;s &lt;code&gt;T&lt;/code&gt; even though &lt;code&gt;&lt;strong&gt;int&lt;/strong&gt;&lt;/code&gt; 
doesn&amp;#39;t implement &lt;code&gt;IOperatorPolicy&amp;lt;T&amp;gt;&lt;/code&gt; itself.&lt;/p&gt;
&lt;p&gt;Next time I will discuss another application of an &lt;em&gt;adapter policy&lt;/em&gt;.&lt;/p&gt;
&lt;/body&gt;
                </description>
      <body xmlns="http://www.w3.org/1999/xhtml">
        <p>The mixin technique in my 
<a href="http://www.removingalldoubt.com/PermaLink.aspx/b97049b8-c16d-430b-991b-0a3922b6eea7">last post</a> was a bit awkward to use 
with generic 
methods. It is much less awkward to use for classes, however. For example, if 
you want an expression evaluator much like I posted
<a href="http://www.removingalldoubt.com/commentview.aspx/bece3be7-04a1-4130-b1ac-0b88c94e7708">
here</a>, but you want to leave the result type open, you can use this technique 
to do it.</p>
        <p>First, I declared a policy interface for the operators I wanted to abstract 
over,</p>
        <blockquote>
          <pre>
            <b>partial</b>
            <b>interface</b> IOperatorPolicy&lt;T&gt; {
    T Add(T a, T b);
    T Subtract(T a, T b);
    T Multiply(T a, T b);
    T Divide(T a, T b);
}</pre>
        </blockquote>
        <p>Second, I created the operator policies for <code><strong>int</strong></code> 
and <code><strong>double</strong></code>. I could have created more, <code><strong>decimal</strong></code>, <code><strong>float</strong></code>, etc. but 
two is sufficient for demonstration.</p>
        <blockquote>
          <pre>
            <strong>partial</strong>
            <b>struct</b> IntOperatorPolicy : IOperatorPolicy&lt;<b>int</b>&gt; {
    <b>int</b> IOperatorPolicy&lt;<b>int</b>&gt;.Add(<b>int</b> a, <b>int</b> b) { <b>return</b> a + b; }
    <b>int</b> IOperatorPolicy&lt;<b>int</b>&gt;.Subtract(<b>int</b> a, <b>int</b> b) { <b>return</b> a - b; }
    <b>int</b> IOperatorPolicy&lt;<b>int</b>&gt;.Multiply(<b>int</b> a, <b>int</b> b) { <b>return</b> a * b; }
    <b>int</b> IOperatorPolicy&lt;<b>int</b>&gt;.Divide(<b>int</b> a, <b>int</b> b) { <b>return</b> a / b; }
}

<b>partial struct</b> DoubleOperatorPolicy : IOperatorPolicy&lt;<b>double</b>&gt; {
    <b>double</b> IOperatorPolicy&lt;<b>double</b>&gt;.Add(<b>double</b> a, <b>double</b> b) { <b>return</b> a + b;
    <b>double</b> IOperatorPolicy&lt;<b>double</b>&gt;.Subtract(<b>double</b> a, <b>double</b> b) { <b>return</b> a - b; }
    <b>double</b> IOperatorPolicy&lt;<b>double</b>&gt;.Multiply(<b>double</b> a, <b>double</b> b) { <b>return</b> a * b; }
    <b>double</b> IOperatorPolicy&lt;<b>double</b>&gt;.Divide(<b>double</b> a, <b>double</b> b) { <b>return</b> a / b; }
}</pre>
        </blockquote>
        <p>Next are the expression nodes themselves. I wrap them in a generic class 
that takes the parameters. This mitigates some of the clutter caused by the 
policy.</p>
        <blockquote>
          <pre>
            <b>partial</b>
            <b>class</b> Expression&lt;T, OperatorPolicy&gt;
    <strong>where</strong> OperatorPolicy : <b>struct</b>, IOperatorPolicy&lt;T&gt; {

    <b>static</b> OperatorPolicy _operatorPolicy = <b>new</b> OperatorPolicy();

    <b>public</b><b>abstract</b><b>partial</b><b>class</b> Expr {
        <b>public</b><b>abstract</b> T Evaluate();
    }

    <b>public</b><b>partial</b><b>class</b> Literal : Expr {
        <b>private</b> T _literal;

        <b>public</b> Literal(T literal) { _literal = literal; }

        <b>public</b><b>override</b> T Evaluate() {
            <b>return</b> _literal;
        }

        <b>public</b><b>override</b><b>string</b> ToString() {
            <b>return</b> _literal.ToString();
        }
    }

    <b>public</b><b>abstract</b><b>partial</b><b>class</b> BinaryOp : Expr {
        <b>private</b> Expr _left;
        <b>private</b> Expr _right;

        <b>protected</b> BinaryOp(Expr left, Expr right) { _left = left; _right = right; }

        <b>public</b><b>override</b> T Evaluate() {
            <b>return</b> EvaluateOp(_left.Evaluate(), _right.Evaluate());
        }

        <b>protected</b><b>abstract</b> T EvaluateOp(T left, T right);
    }

    <b>public</b><b>partial</b><b>class</b> Add : BinaryOp {
        <b>public</b> Add(Expr left, Expr right) : <b>base</b>(left, right) { }
        <b>protected</b><b>override</b> T EvaluateOp(T left, T right) {
            <b>return</b> _operatorPolicy.Add(left, right);
        }
    }
    
    <b>public</b><b>partial</b><b>class</b> Add : BinaryOp {
        <b>public</b> Add(Expr left, Expr right) : <b>base</b>(left, right) { }
        <b>protected</b><b>override</b> T EvaluateOp(T left, T right) {
            <b>return</b> _operatorPolicy.Add(left, right);
        }
    }

    <b>public</b><b>partial</b><b>class</b> Subtract : BinaryOp {
        <b>public</b> Subtract(Expr left, Expr right) : <b>base</b>(left, right) { }
        <b>protected</b><b>override</b> T EvaluateOp(T left, T right) {
            <b>return</b> _operatorPolicy.Subtract(left, right);
        }
    }

    <b>public</b><b>partial</b><b>class</b> Multiply : BinaryOp {
        <b>public</b> Multiply(Expr left, Expr right) : <b>base</b>(left, right) { }
        <b>protected</b><b>override</b> T EvaluateOp(T left, T right) {
            <b>return</b> _operatorPolicy.Multiply(left, right);
        }
    }

    <b>public</b><b>partial</b><b>class</b> Divide : BinaryOp {
        <b>public</b> Divide(Expr left, Expr right) : <b>base</b>(left, right) { }
        <b>protected</b><b>override</b> T EvaluateOp(T left, T right) {
            <b>return</b> _operatorPolicy.Divide(left, right);
        }
    }
}</pre>
        </blockquote>
        <p>Here the <code>Expression</code> class acts as a container of a family of 
classes. Once you have an instance of one of the <code>Expr</code> derived classes, calling 
<code>Evaluate()</code> is straight-forward. Unfortunately, constructing one is a bit of a 
challenge. To get a literal of the <code><strong>int</strong></code> expression you would need to do,</p>
        <blockquote>
          <pre>
            <strong>var</strong> i1 = <strong>new</strong> Expression&lt;<strong>int</strong>, IntOperatorPolicy&gt;.Literal(1);</pre>
        </blockquote>
        <p>You can make this a little better by introducing a <code><strong>static</strong></code> 
method into <code>Expression</code> like,</p>
        <blockquote>
          <pre>
            <b>public</b>
            <b>static</b> Expr L(T literal) {
    <b>return</b><b>new</b> Literal(literal);
}</pre>
        </blockquote>
        <p>then the above becomes,</p>
        <blockquote>
          <pre>
            <strong>var</strong> i1 = Expression&lt;<strong>int</strong>, IntOperatorPolicy&gt;.L(1);</pre>
        </blockquote>
        <p>This still a bit awkward especially when you want to construct a more 
complicated expression,</p>
        <blockquote>
          <pre>
            <strong>var</strong> e = <strong>new</strong> Expression&lt;<strong>int</strong>, IntOperatorPolicy&gt;.Add(i1, i1);</pre>
        </blockquote>
        <p>This can be made significantly better by adding operator overloads to <code>Expr</code> as 
in,</p>
        <blockquote>
          <pre>
            <b>public</b>
            <b>abstract</b>
            <strong>partial</strong>
            <b>class</b> Expr {
    <b>public</b><b>abstract</b> T Evaluate();
    <b>public</b><b>static</b> Expr <b>operator</b> +(Expr a, Expr b) {
        <b>return</b><b>new</b> Add(a, b);
    }
    <b>public</b><b>static</b> Expr <b>operator</b> -(Expr a, Expr b) {
        <b>return</b><b>new</b> Subtract(a, b);
    }
    <b>public</b><b>static</b> Expr <b>operator</b> *(Expr a, Expr b) {
        <b>return</b><b>new</b> Multiply(a, b);
    }
    <b>public</b><b>static</b> Expr <b>operator</b> /(Expr a, Expr b) {
        <b>return</b><b>new</b> Divide(a, b);
    }
}</pre>
        </blockquote>
        <p>now the <code>e</code> assignment can look like,</p>
        <blockquote>
          <pre>
            <strong>var</strong> e = i1 + i1;</pre>
        </blockquote>
        <p>and finally, to make it look even better you can put the code to create the 
expression in a static method of a class that derives from <code>Expression</code> and closes the 
type parameters. Here are examples of one for <code><strong>int</strong></code> and 
a similar one for <code><strong>double</strong></code>.</p>
        <blockquote>
          <pre>
            <b>class</b> TestInt : Expression&lt;<b>int</b>, IntOperatorPolicy&gt; {
    <b>public</b><b>static</b><b>void</b> Run() {
        <strong>var</strong> iv = L(1) + L(2) * L(3);
        Console.WriteLine(iv.Evaluate());
    }
}

<b>class</b> TestDouble : Expression&lt;<b>double</b>, DoubleOperatorPolicy&gt; {
    <b>public</b><b>static</b><b>void</b> Run() {
        <strong>var</strong> dv = L(1.2) + L(3.4) * L(5.6);
        Console.WriteLine(dv.Evaluate());
    }
}</pre>
        </blockquote>
        <p>This shows taking advantage of the C# compiler's operator overloading to 
produce an expression tree and the use of the <code>L()</code> method as a sort 
of cast to change a literal of <code>T</code> into a <code>Literal&lt;T&gt;</code>. 
The call to <code>Evaluate()</code> calculates the result of the expression as 
an <code><strong>int</strong></code> or <code><strong>double</strong></code>. 
The code generated, as discussed
<a href="http://www.removingalldoubt.com/PermaLink.aspx/b97049b8-c16d-430b-991b-0a3922b6eea7">
last time</a>, is quite good when JIT'ing outside the debugger and using 
optimized retail bits.</p>
        <p>This use of a policy <code><strong>struct</strong></code> is what I refer to 
as an <em>adapter policy</em>. The <code>Expression</code> class has an 
abstraction it supports, represented by <code>IOperatorPolicy&lt;T&gt;</code>, but 
this abstraction is not supported by any of the interesting types you would want 
to pass as <code>Expression</code>'s <code>T</code>. This is solved by creating 
an <em>adapter policy</em> and passing that along with <code>T</code>. This 
allows a generic type to introduce an abstraction that is unknown to the types 
the generic wants to range over, allow us, as above, to pass <code>int</code> 
for <code>Expression</code>'s <code>T</code> even though <code><strong>int</strong></code> 
doesn't implement <code>IOperatorPolicy&lt;T&gt;</code> itself.</p>
        <p>Next time I will discuss another application of an <em>adapter policy</em>.</p>
      </body>
      <comments>http://www.removingalldoubt.com/commentview.aspx/f712e487-a6f5-4a65-a718-5ce580f399a8</comments>
      <category>Programming</category>
    </item>
    <item>
      <title>Operators, Generics and Policies</title>
      <guid>http://www.removingalldoubt.com/permalink.aspx/b97049b8-c16d-430b-991b-0a3922b6eea7</guid>
      <link>http://www.removingalldoubt.com/permalink.aspx/b97049b8-c16d-430b-991b-0a3922b6eea7</link>
      <pubDate>Wed, 25 Jul 2007 10:46:57 GMT</pubDate>
      <description>&lt;body xmlns="http://www.w3.org/1999/xhtml"&gt;
&lt;p&gt;One of the limitations of C# generics is you cannot abstract over operators. 
That is not completely true, you can if the base class used in &lt;code&gt;&lt;strong&gt;where&lt;/strong&gt;&lt;/code&gt; clause has 
operators; but, since operators are more useful, and more common, on value types, 
that is only marginally helpful. Also, this abstraction is provided by the base 
class not by using generics. What I would like to do is declare that my type&amp;nbsp; 
parameter requires the type to implement a particular operator. For example, to create a generic &lt;code&gt;Add()&lt;/code&gt; 
method I would like to specify that the type parameter must implement the &lt;code&gt;
+&lt;/code&gt; operator and then be able to use the &lt;code&gt;+&lt;/code&gt; operator in my code 
such as,&lt;/p&gt;
&lt;blockquote&gt;&lt;pre&gt;&lt;span style="color: blue"&gt;&lt;em&gt;// Invalid C#&lt;/em&gt;&lt;/span&gt;
&lt;strong&gt;static&lt;/strong&gt; T Add&amp;lt;T&amp;gt;(T a, T b) &lt;strong&gt;where&lt;/strong&gt; T: T &lt;strong&gt;operator&lt;/strong&gt; +(T, T) {
    &lt;strong&gt;return&lt;/strong&gt; a + b;
}&lt;/pre&gt;&lt;/blockquote&gt;

&lt;p&gt;C# doesn&amp;#39;t support this but you can get somewhat close by supplying a policy
&lt;code&gt;&lt;strong&gt;struct&lt;/strong&gt;&lt;/code&gt; like I described in
&lt;a href="http://www.removingalldoubt.com/commentview.aspx/15e1444d-db2b-4f38-a448-ec7e5c7f6496"&gt;
this post&lt;/a&gt;. The policy &lt;code&gt;&lt;strong&gt;interface&lt;/strong&gt;&lt;/code&gt; and the &lt;code&gt;&lt;strong&gt;int&lt;/strong&gt;&lt;/code&gt; policy &lt;code&gt;&lt;strong&gt;struct&lt;/strong&gt;&lt;/code&gt; would 
look like,&lt;/p&gt;
&lt;blockquote&gt;&lt;pre&gt;&lt;b&gt;interface&lt;/b&gt; IAddPolicy&amp;lt;T&amp;gt; {
    T Add(T a, T b);
}

&lt;b&gt;struct&lt;/b&gt; IntAddPolicy : IAddPolicy&amp;lt;&lt;b&gt;int&lt;/b&gt;&amp;gt; {
    &lt;b&gt;public&lt;/b&gt; &lt;b&gt;int&lt;/b&gt; Add(&lt;b&gt;int&lt;/b&gt; a, &lt;b&gt;int&lt;/b&gt; b) { &lt;b&gt;return&lt;/b&gt; a + b; }
}&lt;/pre&gt;&lt;/blockquote&gt;
&lt;p&gt;This allows you to write the following,&lt;/p&gt;
&lt;blockquote&gt;&lt;pre&gt;&lt;b&gt;static&lt;/b&gt; T Add&amp;lt;T, P&amp;gt;(T a, T b) &lt;strong&gt;where&lt;/strong&gt; P: &lt;b&gt;struct&lt;/b&gt;, IAddPolicy&amp;lt;T&amp;gt; {
    &lt;b&gt;return&lt;/b&gt; &lt;b&gt;new&lt;/b&gt; P().Add(a, b);
}&lt;/pre&gt;&lt;/blockquote&gt;
&lt;p&gt;Unfortunately the policy &lt;code&gt;&lt;strong&gt;struct&lt;/strong&gt;&lt;/code&gt; cannot be 
inferred from the parameters so you have to supply the type parameter 
explicitly,&lt;/p&gt;
&lt;blockquote&gt;&lt;pre&gt;&lt;strong&gt;var&lt;/strong&gt; i = Add&amp;lt;&lt;b&gt;int&lt;/b&gt;, IntAddPolicy&amp;gt;(3, 4);&lt;/pre&gt;&lt;/blockquote&gt;
&lt;p&gt;which doesn&amp;#39;t look pretty and generates less than efficient code for the &lt;code&gt;Add()&lt;/code&gt; 
method on an i386 architecture,&lt;/p&gt;
&lt;blockquote&gt;&lt;pre&gt;00000000  sub         esp,8 
00000003  xor         eax,eax 
00000005  mov         dword ptr [esp],eax 
00000008  mov         dword ptr [esp+4],eax 
0000000c  mov         byte ptr [esp],0 
00000010  movsx       eax,byte ptr [esp] 
00000014  mov         byte ptr [esp+4],al 
00000018  add         ecx,edx 
0000001a  mov         eax,ecx 
0000001c  add         esp,8 
0000001f  ret              &lt;/pre&gt;&lt;/blockquote&gt;
&lt;p&gt;This generates code to initialize the policy 
structure we don&amp;#39;t actually use. We can get rid of that by recasting this a bit to save the dummy &lt;code&gt;&lt;strong&gt;struct&lt;/strong&gt;&lt;/code&gt; allocation by putting the 
&lt;code&gt;Add()&lt;/code&gt; method in a wrapping class that takes the type parameters. 
The type would allocate the &lt;code&gt;&lt;strong&gt;struct&lt;/strong&gt;&lt;/code&gt; instead of the 
method. This looks 
like,&lt;/p&gt;
&lt;blockquote&gt;&lt;pre&gt;&lt;b&gt;class&lt;/b&gt; Adder&amp;lt;T, P&amp;gt;
    &lt;strong&gt;where&lt;/strong&gt; P: &lt;b&gt;struct&lt;/b&gt;, IAddPolicy&amp;lt;T&amp;gt;
{
    &lt;b&gt;static&lt;/b&gt; P AddPolicy = &lt;b&gt;new&lt;/b&gt; P();
    &lt;b&gt;static&lt;/b&gt; &lt;b&gt;public&lt;/b&gt; T Add(T a, T b) { &lt;b&gt;return&lt;/b&gt; AddPolicy.Add(a, b); }
}&lt;/pre&gt;&lt;/blockquote&gt;
&lt;p&gt;which generates the following code for &lt;code&gt;Add()&lt;/code&gt;,&lt;/p&gt;
&lt;blockquote&gt;&lt;pre&gt;00000000  add         ecx,edx 
00000002  mov         eax,ecx 
00000004  ret              &lt;/pre&gt;&lt;/blockquote&gt;
&lt;p&gt;This can be called like,&lt;/p&gt;
&lt;blockquote&gt;&lt;pre&gt;&lt;strong&gt;var&lt;/strong&gt; i2 = Adder&amp;lt;&lt;b&gt;int&lt;/b&gt;, IntAddPolicy&amp;gt;.Add(3, 4);&lt;/pre&gt;&lt;/blockquote&gt;
&lt;p&gt;Note that the code in &lt;code&gt;IntAddPolicy&lt;/code&gt; gets inlined into the &lt;code&gt;
Add()&lt;/code&gt; method. Even though this doesn&amp;#39;t get inlined into the caller of
&lt;code&gt;Add(),&lt;/code&gt; it will still be pretty quick with the branch prediction and 
register aliasing of modern processors. This means that you are not paying much 
(and in many cases nothing) in code quality for using an &lt;code&gt;AddPolicy&lt;/code&gt; over writing out the &lt;code&gt;
Add()&lt;/code&gt; method explicitly.&lt;/p&gt;
&lt;p&gt;To use the &lt;code&gt;Add()&lt;/code&gt; method above with another type, such as &lt;code&gt;
&lt;strong&gt;double&lt;/strong&gt;&lt;/code&gt;, you need to create another 
add policy &lt;code&gt;&lt;strong&gt;struct&lt;/strong&gt;&lt;/code&gt;. This would look like,&lt;/p&gt;
&lt;blockquote&gt;&lt;pre&gt;&lt;b&gt;struct&lt;/b&gt; DoubleAddPolicy : IAddPolicy&amp;lt;&lt;b&gt;double&lt;/b&gt;&amp;gt; {
    &lt;b&gt;public&lt;/b&gt; &lt;b&gt;double&lt;/b&gt; Add(&lt;b&gt;double&lt;/b&gt; a, &lt;b&gt;double&lt;/b&gt; b) { &lt;b&gt;return&lt;/b&gt; a + b; }
}&lt;/pre&gt;&lt;/blockquote&gt;
&lt;p&gt;Using this &lt;code&gt;&lt;strong&gt;struct&lt;/strong&gt;&lt;/code&gt; to call &lt;code&gt;Add()&lt;/code&gt; 
will produce the following code for the &lt;code&gt;Add()&lt;/code&gt; method,&lt;/p&gt;
&lt;blockquote&gt;&lt;pre&gt;00000000  fld         qword ptr [esp+0Ch] 
00000004  fadd        qword ptr [esp+4] 
00000008  ret         10h  &lt;/pre&gt;&lt;/blockquote&gt;
&lt;p&gt;This is not quite as good as the code generated for &lt;code&gt;&lt;strong&gt;int&lt;/strong&gt;&lt;/code&gt; 
because it uses the stack to pass the parameters but it is still pretty fast.&lt;/p&gt;
&lt;p&gt;We now have a method that can add two values of any type &lt;code&gt;T&lt;/code&gt; for 
which an &lt;code&gt;AddPolicy&lt;/code&gt; can be created. This is pretty close to, and 
more general than, what I originally wanted. Unfortunately, even though the code 
generated is good, calling this code is very awkward; we have to call a static 
method of a parameterized class and the policy &lt;code&gt;&lt;strong&gt;struct&lt;/strong&gt;&lt;/code&gt; 
prevents the compiler from being able to use type inferencing to supply the 
parameters for us. Next time I will describe a more practical application of 
this technique where the awkwardness is not as noticiable.&lt;/p&gt;
&lt;/body&gt;
                </description>
      <comments>http://www.removingalldoubt.com/commentview.aspx/b97049b8-c16d-430b-991b-0a3922b6eea7</comments>
      <category>Programming</category>
    </item>
    <item>
      <title>C# Mixins - Sort of</title>
      <guid>http://www.removingalldoubt.com/permalink.aspx/15e1444d-db2b-4f38-a448-ec7e5c7f6496</guid>
      <link>http://www.removingalldoubt.com/permalink.aspx/15e1444d-db2b-4f38-a448-ec7e5c7f6496</link>
      <pubDate>Mon, 02 Jul 2007 23:42:25 GMT</pubDate>
      <description>&lt;body xmlns="http://www.w3.org/1999/xhtml"&gt;
&lt;p&gt;I recently needed to create a set of classes that was the combinatorial 
expansion of several implementation flavors of two independent sets of methods. Why I needed 
combinatorial expansion is not that interesting but the solution is. What I came 
up with is a way of supporting a form of
&lt;a href="http://en.wikipedia.org/wiki/Mixin"&gt;mixin&lt;/a&gt;&amp;#39;s in C#.&lt;/p&gt;
&lt;p&gt;Lets take the methods,&lt;/p&gt;
&lt;blockquote&gt;&lt;pre&gt;&lt;strong&gt;void&lt;/strong&gt; Lock();
&lt;strong&gt;bool&lt;/strong&gt; Unlock();
&lt;strong&gt;bool&lt;/strong&gt; Locked { &lt;strong&gt;get&lt;/strong&gt;; }&lt;/pre&gt;&lt;/blockquote&gt;

&lt;p&gt;If you call &lt;code&gt;Lock()&lt;/code&gt;, &lt;code&gt;Locked&lt;/code&gt; 
returns &lt;code&gt;&lt;strong&gt;true&lt;/strong&gt;&lt;/code&gt;, until you call &lt;code&gt;Unlock()&lt;/code&gt;. Also &lt;code&gt;Unlock()&lt;/code&gt; 
returns &lt;code&gt;&lt;strong&gt;true&lt;/strong&gt;&lt;/code&gt; if the object is now unlocked. There are several 
implementations I can think of for these methods, one uses a Boolean value and 
doesn&amp;#39;t support nested calls to &lt;code&gt;Lock()&lt;/code&gt;:&lt;/p&gt;
&lt;blockquote&gt;&lt;pre&gt;&lt;strong&gt;void&lt;/strong&gt; Lock() {
  _locked = &lt;strong&gt;true&lt;/strong&gt;;
}

&lt;strong&gt;bool&lt;/strong&gt; Unlock() {
  _locked = &lt;strong&gt;false&lt;/strong&gt;;
  &lt;strong&gt;return&lt;/strong&gt; &lt;strong&gt;true&lt;/strong&gt;;
}

&lt;strong&gt;bool&lt;/strong&gt; Locked {
  &lt;strong&gt;get&lt;/strong&gt; { &lt;strong&gt;return&lt;/strong&gt; _locked; }
}&lt;/pre&gt;&lt;/blockquote&gt;

&lt;p&gt;Another uses an integer value to count the number of nested calls to &lt;code&gt;
Lock()&lt;/code&gt; and it remains locked until a matching number of &lt;code&gt;Unlock()&lt;/code&gt; 
calls are made.&lt;/p&gt;
&lt;blockquote&gt;&lt;pre&gt;&lt;strong&gt;void&lt;/strong&gt; Lock() {
  _count++;
}

&lt;strong&gt;void&lt;/strong&gt; Unlock() {
  _count--;
  &lt;strong&gt;return&lt;/strong&gt; _count == 0;
}

&lt;strong&gt;void&lt;/strong&gt; Locked() {
  &lt;strong&gt;return&lt;/strong&gt; _count &amp;gt; 0;
}&lt;/pre&gt;&lt;/blockquote&gt;
&lt;p&gt;This isn&amp;#39;t thread safe so we could provide a relatively thread-safe version 
in,&lt;/p&gt;
&lt;blockquote&gt;&lt;pre&gt;&lt;b&gt;void&lt;/b&gt; Lock() {
    System.Threading.Interlocked.Increment(&lt;b&gt;ref&lt;/b&gt; _count);
}

&lt;b&gt;bool&lt;/b&gt; Unlock() {
    &lt;b&gt;return&lt;/b&gt; System.Threading.Interlocked.Decrement(&lt;b&gt;ref&lt;/b&gt; _count) == 0;
}

&lt;b&gt;bool&lt;/b&gt; Locked {
    get { &lt;b&gt;return&lt;/b&gt; _count &amp;gt; 0; }
}&lt;/pre&gt;
&lt;/blockquote&gt;
&lt;p&gt;I am sure you have already thought of at least one more. Now I have four 
possible implementations (including yours), which is the correct one? Unfortunately, that depends 
on how the locking is going to be used. If I know I will never need nested 
locks, only taking space for a Boolean makes sense. If I know I will need to 
support nested locks then the &lt;code&gt;&lt;strong&gt;int&lt;/strong&gt;&lt;/code&gt; seems like a 
good choice. If it is going to be used in a multi-threaded application I should 
probably use the thread-safe version. I now have two choices, pick one 
implementation or pass it the implementation as a parameter. Picking one 
implementation is easy, just copy of of the above implementation into the class; but how do you efficiently pass an implementation as a 
parameter? &lt;/p&gt;
&lt;p&gt;From now on I will refer to each implementation as a locking policy. What I 
want is an efficient way to pass the locking policy to a set of classes. Most obvious way is to 
write a class for each policy and pass the policy 
as a parameter to each instance. This might look something like,&lt;/p&gt;
&lt;blockquote&gt;&lt;pre&gt;&lt;strong&gt;abstract&lt;/strong&gt; &lt;strong&gt;class&lt;/strong&gt; LockingPolicy {
  &lt;strong&gt;public&lt;/strong&gt; &lt;strong&gt;abstract&lt;/strong&gt; &lt;strong&gt;void&lt;/strong&gt; Lock();
  &lt;strong&gt;public&lt;/strong&gt; &lt;strong&gt;abstract&lt;/strong&gt; &lt;strong&gt;bool&lt;/strong&gt; Unlock();
  &lt;strong&gt;public&lt;/strong&gt; &lt;strong&gt;abstract&lt;/strong&gt; &lt;strong&gt;bool&lt;/strong&gt; Locked { &lt;strong&gt;get&lt;/strong&gt;; }
}

&lt;strong&gt;class&lt;/strong&gt; LockableObject {
    &lt;strong&gt;private&lt;/strong&gt; LockingPolicy _lockingPolicy;
  
    &lt;strong&gt;public&lt;/strong&gt; LockableObject(LockingPolicy lockingPolicy) {
        _lockingPolicy = lockingPolicy;
    }
  
    &lt;b&gt;public&lt;/b&gt; &lt;b&gt;void&lt;/b&gt; Lock() {
        _lockingPolicy.Lock();
    }

    &lt;b&gt;public&lt;/b&gt; &lt;b&gt;bool&lt;/b&gt; Unlock() {
        &lt;b&gt;return&lt;/b&gt; _lockingPolicy.Unlock();
    }

    &lt;b&gt;public&lt;/b&gt; &lt;b&gt;bool&lt;/b&gt; Locked {
        get { &lt;b&gt;return&lt;/b&gt; _lockingPolicy.Locked; }
    }
}&lt;/pre&gt;
&lt;/blockquote&gt;
&lt;p&gt;Unfortunately, this has, on average, 36 bytes of overhead per instance on 
a 32 bit machine (more on 64).&amp;nbsp; This seems a bit much for such a policy and picking just one 
implementation, even one too general for the average application, starts 
looking like a better alternative. We must be able to do better than this.&lt;/p&gt;
&lt;p&gt;Since passing the implementation as a parameter to the instances is 
expensive, why not try to pass the implementation to the class instead? In order 
to do that we need use a type parameter. What we want is something like,&lt;/p&gt;
&lt;blockquote&gt;&lt;pre&gt;&lt;b&gt;class&lt;/b&gt; LockableObject&amp;lt;LockingPolicy&amp;gt; {
    &lt;b&gt;private&lt;/b&gt; LockingPolicy _lockingPolicy = &lt;b&gt;new&lt;/b&gt; LockingPolicy();

    &lt;b&gt;public&lt;/b&gt; &lt;b&gt;void&lt;/b&gt; Lock() {
        _lockingPolicy.Lock();
    }

    &lt;b&gt;public&lt;/b&gt; &lt;b&gt;bool&lt;/b&gt; Unlock() {
        &lt;b&gt;return&lt;/b&gt; _lockingPolicy.Unlock();
    }

    &lt;b&gt;public&lt;/b&gt; &lt;b&gt;bool&lt;/b&gt; Locked {
        get { &lt;b&gt;return&lt;/b&gt; _lockingPolicy.Locked; }
    }
}&lt;/pre&gt;&lt;/blockquote&gt;
&lt;p&gt;In other words, we need to passing a &lt;code&gt;&lt;strong&gt;class&lt;/strong&gt;&lt;/code&gt; and delegate the implementation to 
that &lt;code&gt;&lt;strong&gt;class&lt;/strong&gt;&lt;/code&gt;. This does not look significantly better than the previous 
implementation, however, because we are new&amp;#39;ing up an instance and assigning it 
to an instance variable which, as before, consumes a minimum of 36 bytes per 
instance. But if &lt;code&gt;LockingPolicy&lt;/code&gt; is a &lt;code&gt;&lt;strong&gt;struct&lt;/strong&gt;&lt;/code&gt; instead 
of a &lt;code&gt;&lt;strong&gt;class&lt;/strong&gt;&lt;/code&gt; then it will only add the size of the
&lt;code&gt;&lt;strong&gt;struct&lt;/strong&gt;&lt;/code&gt; to the &lt;code&gt;LockableObject&lt;/code&gt; instance 
size. In other words, we would only be taking space for either a &lt;code&gt;&lt;strong&gt;bool&lt;/strong&gt;&lt;/code&gt; 
or an &lt;code&gt;&lt;strong&gt;int&lt;/strong&gt;&lt;/code&gt;. The size overhead looks good, now how 
about the delegation? In order to call methods on &lt;code&gt;LockingPolicy&lt;/code&gt; the
&lt;code&gt;LockingPolicy&lt;/code&gt; &lt;code&gt;&lt;strong&gt;struct&lt;/strong&gt;&lt;/code&gt; must implement 
an interface. It cannot be an &lt;code&gt;&lt;strong&gt;abstract&lt;/strong&gt;&lt;/code&gt;
&lt;code&gt;&lt;strong&gt;class&lt;/strong&gt;&lt;/code&gt; because all &lt;code&gt;&lt;strong&gt;struct&lt;/strong&gt;&lt;/code&gt;s 
are sealed and cannot be inherited from. The interface for the locking policy is fairly straight 
forward and looks like,&lt;/p&gt;
&lt;blockquote&gt;&lt;pre&gt;&lt;b&gt;interface&lt;/b&gt; ILockingPolicy {
    &lt;b&gt;void&lt;/b&gt; Lock();
    &lt;b&gt;bool&lt;/b&gt; Unlock();
    &lt;b&gt;bool&lt;/b&gt; Locked { get; }
}&lt;/pre&gt;&lt;/blockquote&gt;
&lt;p&gt;An implementation of the Boolean locking policy looks like,&lt;/p&gt;
&lt;blockquote&gt;&lt;pre&gt;&lt;b&gt;struct&lt;/b&gt; SimpleLockPolicy : ILockingPolicy {
    &lt;b&gt;bool&lt;/b&gt; _locked;

    &lt;b&gt;void&lt;/b&gt; ILockingPolicy.Lock() {
        _locked = &lt;b&gt;true&lt;/b&gt;;
    }
    &lt;b&gt;bool&lt;/b&gt; ILockingPolicy.Unlock() {
        _locked = &lt;b&gt;false&lt;/b&gt;;
        &lt;b&gt;return&lt;/b&gt; &lt;b&gt;false&lt;/b&gt;;
    }
    &lt;b&gt;bool&lt;/b&gt; ILockingPolicy.Locked {
        get { &lt;b&gt;return&lt;/b&gt; _locked; }
    }
}&lt;/pre&gt;&lt;/blockquote&gt;
&lt;p&gt;The counted locking policy looks like,&lt;/p&gt;
&lt;blockquote&gt;&lt;pre&gt;&lt;b&gt;struct&lt;/b&gt; CountedLockPolicy : ILockingPolicy {
    &lt;b&gt;private&lt;/b&gt; &lt;b&gt;int&lt;/b&gt; _count;
    &lt;b&gt;void&lt;/b&gt; ILockingPolicy.Lock() {
        _count++;
    }
    &lt;b&gt;bool&lt;/b&gt; ILockingPolicy.Unlock() {
        _count--;
        &lt;b&gt;return&lt;/b&gt; _count == 0;
    }
    &lt;b&gt;bool&lt;/b&gt; ILockingPolicy.Locked {
        get { &lt;b&gt;return&lt;/b&gt; _count &amp;gt; 0; }
    }
}&lt;/pre&gt;&lt;/blockquote&gt;
&lt;p&gt;We now need to add a &lt;code&gt;&lt;strong&gt;where&lt;/strong&gt;&lt;/code&gt; clause to the &lt;code&gt;LockableObject&lt;/code&gt; 
class so we can call the methods provided by the &lt;code&gt;&lt;strong&gt;struct&lt;/strong&gt;&lt;/code&gt;&amp;#39;s methods. The modified &lt;code&gt;LockableObject&lt;/code&gt; 
class looks like,&lt;/p&gt;
&lt;blockquote&gt;&lt;pre&gt;&lt;b&gt;class&lt;/b&gt; LockableObject&amp;lt;LockingPolicy&amp;gt;
    &lt;strong&gt;where&lt;/strong&gt; LockingPolicy : &lt;b&gt;struct&lt;/b&gt;, ILockingPolicy 
{
    &lt;b&gt;private&lt;/b&gt; LockingPolicy _lockingPolicy = &lt;b&gt;new&lt;/b&gt; LockingPolicy();

    &lt;b&gt;public&lt;/b&gt; &lt;b&gt;void&lt;/b&gt; Lock() {
        _lockingPolicy.Lock();
    }

    &lt;b&gt;public&lt;/b&gt; &lt;b&gt;bool&lt;/b&gt; Unlock() {
        &lt;b&gt;return&lt;/b&gt; _lockingPolicy.Unlock();
    }

    &lt;b&gt;public&lt;/b&gt; &lt;b&gt;bool&lt;/b&gt; Locked {
        get { &lt;b&gt;return&lt;/b&gt; _lockingPolicy.Locked; }
    }
}&lt;/pre&gt;&lt;/blockquote&gt;
&lt;p&gt;The &lt;code&gt;LockableObject&lt;/code&gt; can now be instantiated like,&lt;/p&gt;
&lt;blockquote&gt;&lt;pre&gt;&lt;strong&gt;var&lt;/strong&gt; lockableObject = &lt;b&gt;new&lt;/b&gt; LockableObject&amp;lt;SimpleLockPolicy&amp;gt;();&lt;/pre&gt;&lt;/blockquote&gt;
&lt;p&gt;for a lockable object that uses the Boolean implementation. To use the 
counted locking policy you would construct the object like,&lt;/p&gt;
&lt;blockquote&gt;&lt;pre&gt;&lt;strong&gt;var&lt;/strong&gt; lockableObject = &lt;b&gt;new&lt;/b&gt; LockableObject&amp;lt;CountedLockPolicy&amp;gt;();&lt;/pre&gt;
&lt;/blockquote&gt;
&lt;p&gt;The space consumption looks good but the delegation looks expensive it call 
through an interface which is a virtual. But since we are using &lt;code&gt;&lt;strong&gt;
struct&lt;/strong&gt;&lt;/code&gt;s, which are &lt;code&gt;&lt;strong&gt;sealed&lt;/strong&gt;&lt;/code&gt;, the 
call through the &lt;code&gt;&lt;strong&gt;interface&lt;/strong&gt;&lt;/code&gt; can be made static
and then be a candidate for inlining. In fact, 
this is what happens in retail builds when not debugging. This is not entirely 
free however since there the runtime doesn&amp;#39;t inline twice. Implementing &lt;code&gt;
Lock()&lt;/code&gt; directly instead of through delegation means the &lt;code&gt;Lock()&lt;/code&gt; 
method can be inlined, removing the call entirely, the delegated version inlines 
the delegation but it still generates a call.&lt;/p&gt;
&lt;p&gt;This mechanism for C# mixins is not as convenient as languages that support 
multiple inheritance, because we have to manually delegate to the policy, but it 
is just as efficient as we will see demonstrated more clearly in some of the 
next entries.&lt;/p&gt;
&lt;/body&gt;
                </description>
      <comments>http://www.removingalldoubt.com/commentview.aspx/15e1444d-db2b-4f38-a448-ec7e5c7f6496</comments>
      <category>Programming</category>
    </item>
    <item>
      <title>Keyed Binary Search</title>
      <guid>http://www.removingalldoubt.com/permalink.aspx/f7e6feff-8257-4efe-ad64-acd1c7a4a1e3</guid>
      <link>http://www.removingalldoubt.com/permalink.aspx/f7e6feff-8257-4efe-ad64-acd1c7a4a1e3</link>
      <pubDate>Thu, 24 May 2007 16:44:43 GMT</pubDate>
      <description>&lt;body xmlns="http://www.w3.org/1999/xhtml"&gt;
&lt;p&gt;One thing that has always frustrated me about typical binary search routines 
found in libraries is they always assume you can easily produce a copy of the 
item you are searching for. What I mean is they typically follow this pattern,&lt;/p&gt;
&lt;blockquote&gt;&lt;pre&gt;&lt;strong&gt;int&lt;/strong&gt; BinarySearch&amp;lt;T&amp;gt;(IList&amp;lt;T&amp;gt; list, T item);&lt;/pre&gt;&lt;/blockquote&gt;

&lt;p&gt;which takes a list of some type, left open here, and searches for it in the 
list. This is great if the very next thing you do next is insert &lt;code&gt;item&lt;/code&gt; into 
the list. You already have &lt;code&gt;item&lt;/code&gt; in hand so this signature is 
perfect. But if you 
don&amp;#39;t have a ready &lt;code&gt;item&lt;/code&gt;, and &lt;code&gt;item&lt;/code&gt; is difficult to 
produce, you are stuck. &lt;/p&gt;
&lt;p&gt;This happened to me just recently in my code. I had a 
sorted list of a data structure representing a span of source, similar to a &lt;code&gt;TextPointer&lt;/code&gt; from WPF, called a 
&lt;code&gt;TextRange&lt;/code&gt;. My version can quickly return the 
offset of the beginning of the span but, since &lt;code&gt;TextRange&lt;/code&gt; tracks source changes, 
creating a new &lt;code&gt;TextRange&lt;/code&gt; is expensive. When text in the editor is 
change, I receive the location of 
the change in an event. How do I figure out which one of my &lt;code&gt;TextRange&lt;/code&gt;s was modified? Since 
the list is sorted, the obvious choice is to use a binary search which yields O(Log N) 
performance. Since my &lt;code&gt;TextRange&lt;/code&gt;s are store in a &lt;code&gt;List&amp;lt;TextRange&amp;gt;&lt;/code&gt;, 
obviously I should 
call &lt;code&gt;List&amp;lt;T&amp;gt;.BinarySearch()&lt;/code&gt;. Unfortunately, &lt;code&gt;TextRange&lt;/code&gt;s are expensive to produce; 
too expensive for a per-keystroke operation (I am glossing over some details for 
the sake of brevity; you need to trust me this is true). I have one of two choices, write my 
own &lt;code&gt;BinarySearch()&lt;/code&gt; or create a fake &lt;code&gt;TextRange&lt;/code&gt; that is a special 
&lt;code&gt;TextRange&lt;/code&gt; that 
is less expensive to create and only used for searching. Neither choice is 
pleasant. Hand-rolled binary searches are not hard to right but, for some 
strange reason, I always get them wrong the first time.&lt;/p&gt;
&lt;p&gt;What I needed is prebuilt and tested version of &lt;code&gt;BinarySearch()&lt;/code&gt; that looks more like,&lt;/p&gt;
&lt;blockquote&gt;&lt;pre&gt;&lt;strong&gt;int&lt;/strong&gt; BinarySearch&amp;lt;T, K&amp;gt;(IList&amp;lt;T&amp;gt; list, K key, Converter&amp;lt;T, K&amp;gt; converter);&lt;/pre&gt;&lt;/blockquote&gt;

&lt;p&gt;What this binary search routine does is find some key value in the list 
given a function that can convert any list item into the key. In my example, I 
would call it like,&lt;/p&gt;
&lt;blockquote&gt;&lt;pre&gt;&lt;strong&gt;int&lt;/strong&gt; location = BinarySearch(textRangeList, location, TextRangeToLocation);&lt;/pre&gt;&lt;/blockquote&gt;

&lt;p&gt;where &lt;code&gt;TextRangeToLocation&lt;/code&gt; looks something like,&lt;/p&gt;
&lt;blockquote&gt;&lt;pre&gt;&lt;strong&gt;int&lt;/strong&gt; TextRangeToLocation(TextRange range) { &lt;strong&gt;return&lt;/strong&gt; range.Location; }&lt;/pre&gt;&lt;/blockquote&gt;

&lt;p&gt;I don&amp;#39;t need to produce a &lt;code&gt;TextRange&lt;/code&gt;. I have the location I am looking for 
handy, I just need to know what, if any, &lt;code&gt;TextRange&lt;/code&gt; contains the 
location. This method 
would do just that. You can even use a lambda function in C# 3.0 to get this 
all on one line,&lt;/p&gt;
&lt;blockquote&gt;&lt;pre&gt;&lt;strong&gt;int&lt;/strong&gt; location = BinarySearch(textRangeList, location, (n) =&amp;gt; n.Location);&lt;/pre&gt;&lt;/blockquote&gt;
&lt;p&gt;This is starting to look like a good idea. Let&amp;#39;s code it up. Here is the 
method I ended up with,&lt;/p&gt;
&lt;blockquote&gt;&lt;pre&gt;&lt;b&gt;public&lt;/b&gt; &lt;b&gt;static&lt;/b&gt; &lt;b&gt;int&lt;/b&gt; BinarySearch&amp;lt;T, K&amp;gt;(IList&amp;lt;T&amp;gt; list, K value, 
    Converter&amp;lt;T, K&amp;gt; convert, Comparison&amp;lt;K&amp;gt; compare) {
    &lt;b&gt;int&lt;/b&gt; i = 0;
    &lt;b&gt;int&lt;/b&gt; j = list.Count - 1;
    &lt;b&gt;while&lt;/b&gt; (i &amp;lt;= j) {
        &lt;b&gt;int&lt;/b&gt; m = i + (j - i) / 2;
        &lt;b&gt;int&lt;/b&gt; c = compare(convert(list[m]), value);
        &lt;b&gt;if&lt;/b&gt; (c == 0)
            &lt;b&gt;return&lt;/b&gt; m;
        &lt;b&gt;if&lt;/b&gt; (c &amp;lt; 0)
            i = m + 1;
        &lt;b&gt;else&lt;/b&gt;
            j = m - 1;
    }
    &lt;b&gt;return&lt;/b&gt; ~i;
}&lt;/pre&gt;
&lt;/blockquote&gt;

&lt;p&gt;I added an extra parameter, &lt;code&gt;compare&lt;/code&gt;. This is required because I 
didn&amp;#39;t put any limits on what &lt;code&gt;K&lt;/code&gt; can be and I need a way to compare 
one &lt;code&gt;K&lt;/code&gt; with another. Many types, such as &lt;code&gt;int&lt;/code&gt;, already know how to 
compare values of their own type. Typically types that are comparable, such as
&lt;code&gt;int&lt;/code&gt;,&lt;code&gt; string&lt;/code&gt;, etc., implement
&lt;code&gt;IComparable&amp;lt;T&amp;gt;&lt;/code&gt;. We can accommodate such types by creating an 
overloaded version of &lt;code&gt;BinarySearch()&lt;/code&gt; that looks like, &lt;/p&gt;
&lt;blockquote&gt;&lt;pre&gt;&lt;b&gt;public&lt;/b&gt; &lt;b&gt;static&lt;/b&gt; &lt;b&gt;int&lt;/b&gt; BinarySearch&amp;lt;T, K&amp;gt;(IList&amp;lt;T&amp;gt; list, K value, 
    Converter&amp;lt;T, K&amp;gt; convert) &lt;strong&gt;where&lt;/strong&gt; K : IComparable&amp;lt;K&amp;gt; {
    &lt;b&gt;return&lt;/b&gt; list.BinarySearch(value, convert, (n, m) =&amp;gt; n.CompareTo(m));
}&lt;/pre&gt;
&lt;/blockquote&gt;

&lt;p&gt;which uses a lambda function to create a &lt;code&gt;Comparison&amp;lt;T&amp;gt;&lt;/code&gt;  for any 
type that supports &lt;code&gt;IComparable&amp;lt;T&amp;gt;&lt;/code&gt;. Beware that this doesn&amp;#39;t 
work well with reference types because it doesn&amp;#39;t check for &lt;strong&gt;&lt;code&gt;null&lt;/code&gt;&lt;/strong&gt;. 
You can make it safer by putting &lt;strong&gt;&lt;code&gt;struct&lt;/code&gt;&lt;/strong&gt; in the
&lt;strong&gt;&lt;code&gt;where&lt;/code&gt;&lt;/strong&gt; clause but that seemed overly restrictive to 
me.&lt;/p&gt;
&lt;p&gt;Now that I have a &lt;code&gt;BinarySearch()&lt;/code&gt; that meets my needs better than the built-in
&lt;code&gt;BinarySearch()&lt;/code&gt;, my next thought was I should evangelize the benefits my version 
of &lt;code&gt;BinarySearch()&lt;/code&gt; to the team responsible for maintaining the CLR 
collections and, maybe, someday, I will have it as 
a native part of the CLR; maybe, someday. Then I remember extensions methods. In 
C# 3.0, with a slight modification to the above methods, they can appear as if 
they were already part of the CLR.&lt;/p&gt;
&lt;blockquote&gt;&lt;pre&gt;&lt;b&gt;public&lt;/b&gt; &lt;b&gt;static&lt;/b&gt; &lt;b&gt;class&lt;/b&gt; ListExtensionMethods {
    &lt;b&gt;public&lt;/b&gt; &lt;b&gt;static&lt;/b&gt; &lt;b&gt;int&lt;/b&gt; BinarySearch&amp;lt;T, K&amp;gt;(&lt;b&gt;this&lt;/b&gt; IList&amp;lt;T&amp;gt; list, K value,
        Converter&amp;lt;T, K&amp;gt; convert, Comparison&amp;lt;K&amp;gt; compare) {
        &lt;b&gt;int&lt;/b&gt; i = 0;
        &lt;b&gt;int&lt;/b&gt; j = list.Count - 1;
        &lt;b&gt;while&lt;/b&gt; (i &amp;lt;= j) {
            &lt;b&gt;int&lt;/b&gt; m = i + (j - i) / 2;
            &lt;b&gt;int&lt;/b&gt; c = compare(convert(list[m]), value);
            &lt;b&gt;if&lt;/b&gt; (c == 0)
                &lt;b&gt;return&lt;/b&gt; m;
            &lt;b&gt;if&lt;/b&gt; (c &amp;lt; 0)
                i = m + 1;
            &lt;b&gt;else&lt;/b&gt;
                j = m - 1;
        }
        &lt;b&gt;return&lt;/b&gt; ~i;
    }

    &lt;b&gt;public&lt;/b&gt; &lt;b&gt;static&lt;/b&gt; &lt;b&gt;int&lt;/b&gt; BinarySearch&amp;lt;T, K&amp;gt;(&lt;b&gt;this&lt;/b&gt; IList&amp;lt;T&amp;gt; list, K value, 
        Converter&amp;lt;T, K&amp;gt; convert) where K : IComparable&amp;lt;K&amp;gt; {
        &lt;b&gt;return&lt;/b&gt; list.BinarySearch(value, convert, (n, m) =&amp;gt; n.CompareTo(m));
    }
}&lt;/pre&gt;&lt;/blockquote&gt;
&lt;p&gt;My version of &lt;code&gt;BinarySearch()&lt;/code&gt; now 
appears as part of the methods of any type that implements &lt;code&gt;IList&amp;lt;T&amp;gt;&lt;/code&gt;. 
This allows us to write,&lt;/p&gt;
&lt;blockquote&gt;&lt;pre&gt;&lt;strong&gt;int&lt;/strong&gt; location = textRangeList.BinarySearch(location, (n) =&amp;gt; n.Location);&lt;/pre&gt;&lt;/blockquote&gt;
&lt;p&gt;just like it was a native part of the CLR. No more hand-rolled &lt;code&gt;
BinarySearch()&lt;/code&gt;s!&lt;/p&gt;
&lt;p&gt;Now that we have a &lt;code&gt;ListExtensionMethods &lt;/code&gt;class, what other missing methods 
could we add? Here are a few that I thought would be useful,&lt;/p&gt;
&lt;blockquote&gt;&lt;pre&gt;&lt;b&gt;public&lt;/b&gt; &lt;b&gt;static&lt;/b&gt; &lt;b&gt;void&lt;/b&gt; Sort&amp;lt;T, K&amp;gt;(&lt;b&gt;this&lt;/b&gt; List&amp;lt;T&amp;gt; list, 
    Converter&amp;lt;T, K&amp;gt; coverter, Comparison&amp;lt;K&amp;gt; compare) {
    list.Sort((n, m) =&amp;gt; compare(convert(n), convert(m)));
}

&lt;b&gt;public&lt;/b&gt; &lt;b&gt;static&lt;/b&gt; &lt;b&gt;void&lt;/b&gt; Sort&amp;lt;T, K&amp;gt;(&lt;b&gt;this&lt;/b&gt; List&amp;lt;T&amp;gt; list, 
    Converter&amp;lt;T, K&amp;gt;  converter) &lt;b&gt;where&lt;/b&gt; K : IComparable&amp;lt;K&amp;gt; {
    list.Sort((n, m) =&amp;gt; convert(n).CompareTo(convert(m)));
}

&lt;b&gt;public&lt;/b&gt; &lt;b&gt;static&lt;/b&gt; &lt;b&gt;void&lt;/b&gt; Swap&amp;lt;T&amp;gt;(&lt;b&gt;this&lt;/b&gt; IList&amp;lt;T&amp;gt; list, &lt;b&gt;int&lt;/b&gt; index1, 
    &lt;b&gt;int&lt;/b&gt; index2) {
    var value = list[index1];
    list[index1] = list[index2];
    list[index2] = value;
}

&lt;b&gt;public&lt;/b&gt; &lt;b&gt;static&lt;/b&gt; &lt;b&gt;void&lt;/b&gt; Shuffle&amp;lt;T&amp;gt;(&lt;b&gt;this&lt;/b&gt; IList&amp;lt;T&amp;gt; list) {
    &lt;b&gt;int&lt;/b&gt; count = list.Count;
    Random r = &lt;b&gt;new&lt;/b&gt; Random();
    &lt;b&gt;for&lt;/b&gt;(&lt;b&gt;int&lt;/b&gt; i = count - 1; i &amp;gt; 1; i--)
        list.Swap(i, r.Next(i - 1));
}&lt;/pre&gt;&lt;/blockquote&gt;
&lt;p&gt;The &lt;code&gt;Sort()&lt;/code&gt; methods above are allow you to extract a key for 
sorting using the same methods as above. These are not strictly necessary since 
constructing the lambda function I use is not that complicated but I believe they 
make the code more readable if you are consistent in how you extract keys from a 
list, so these are convenient wrappers that allow you to use the same methods to 
sort and search. &lt;code&gt;Swap()&lt;/code&gt; and
&lt;code&gt;Shuffle()&lt;/code&gt; are throw-ins. They are really only useful for demo code 
or, in my case, test code. I used them to test the &lt;code&gt;Sort()&lt;/code&gt; method 
which I used to test the &lt;code&gt;BinarySearch()&lt;/code&gt; method.&lt;/p&gt;
&lt;/body&gt;
                </description>
      <body xmlns="http://www.w3.org/1999/xhtml">
        <p>One thing that has always frustrated me about typical binary search routines 
found in libraries is they always assume you can easily produce a copy of the 
item you are searching for. What I mean is they typically follow this pattern,</p>
        <blockquote>
          <pre>
            <strong>int</strong> BinarySearch&lt;T&gt;(IList&lt;T&gt; list, T item);</pre>
        </blockquote>
        <p>which takes a list of some type, left open here, and searches for it in the 
list. This is great if the very next thing you do next is insert <code>item</code> into 
the list. You already have <code>item</code> in hand so this signature is 
perfect. But if you 
don't have a ready <code>item</code>, and <code>item</code> is difficult to 
produce, you are stuck. </p>
        <p>This happened to me just recently in my code. I had a 
sorted list of a data structure representing a span of source, similar to a <code>TextPointer</code> from WPF, called a 
<code>TextRange</code>. My version can quickly return the 
offset of the beginning of the span but, since <code>TextRange</code> tracks source changes, 
creating a new <code>TextRange</code> is expensive. When text in the editor is 
change, I receive the location of 
the change in an event. How do I figure out which one of my <code>TextRange</code>s was modified? Since 
the list is sorted, the obvious choice is to use a binary search which yields O(Log N) 
performance. Since my <code>TextRange</code>s are store in a <code>List&lt;TextRange&gt;</code>, 
obviously I should 
call <code>List&lt;T&gt;.BinarySearch()</code>. Unfortunately, <code>TextRange</code>s are expensive to produce; 
too expensive for a per-keystroke operation (I am glossing over some details for 
the sake of brevity; you need to trust me this is true). I have one of two choices, write my 
own <code>BinarySearch()</code> or create a fake <code>TextRange</code> that is a special 
<code>TextRange</code> that 
is less expensive to create and only used for searching. Neither choice is 
pleasant. Hand-rolled binary searches are not hard to right but, for some 
strange reason, I always get them wrong the first time.</p>
        <p>What I needed is prebuilt and tested version of <code>BinarySearch()</code> that looks more like,</p>
        <blockquote>
          <pre>
            <strong>int</strong> BinarySearch&lt;T, K&gt;(IList&lt;T&gt; list, K key, Converter&lt;T, K&gt; converter);</pre>
        </blockquote>
        <p>What this binary search routine does is find some key value in the list 
given a function that can convert any list item into the key. In my example, I 
would call it like,</p>
        <blockquote>
          <pre>
            <strong>int</strong> location = BinarySearch(textRangeList, location, TextRangeToLocation);</pre>
        </blockquote>
        <p>where <code>TextRangeToLocation</code> looks something like,</p>
        <blockquote>
          <pre>
            <strong>int</strong> TextRangeToLocation(TextRange range) { <strong>return</strong> range.Location; }</pre>
        </blockquote>
        <p>I don't need to produce a <code>TextRange</code>. I have the location I am looking for 
handy, I just need to know what, if any, <code>TextRange</code> contains the 
location. This method 
would do just that. You can even use a lambda function in C# 3.0 to get this 
all on one line,</p>
        <blockquote>
          <pre>
            <strong>int</strong> location = BinarySearch(textRangeList, location, (n) =&gt; n.Location);</pre>
        </blockquote>
        <p>This is starting to look like a good idea. Let's code it up. Here is the 
method I ended up with,</p>
        <blockquote>
          <pre>
            <b>public</b>
            <b>static</b>
            <b>int</b> BinarySearch&lt;T, K&gt;(IList&lt;T&gt; list, K value, 
    Converter&lt;T, K&gt; convert, Comparison&lt;K&gt; compare) {
    <b>int</b> i = 0;
    <b>int</b> j = list.Count - 1;
    <b>while</b> (i &lt;= j) {
        <b>int</b> m = i + (j - i) / 2;
        <b>int</b> c = compare(convert(list[m]), value);
        <b>if</b> (c == 0)
            <b>return</b> m;
        <b>if</b> (c &lt; 0)
            i = m + 1;
        <b>else</b>
            j = m - 1;
    }
    <b>return</b> ~i;
}</pre>
        </blockquote>
        <p>I added an extra parameter, <code>compare</code>. This is required because I 
didn't put any limits on what <code>K</code> can be and I need a way to compare 
one <code>K</code> with another. Many types, such as <code>int</code>, already know how to 
compare values of their own type. Typically types that are comparable, such as
<code>int</code>,<code> string</code>, etc., implement
<code>IComparable&lt;T&gt;</code>. We can accommodate such types by creating an 
overloaded version of <code>BinarySearch()</code> that looks like, </p>
        <blockquote>
          <pre>
            <b>public</b>
            <b>static</b>
            <b>int</b> BinarySearch&lt;T, K&gt;(IList&lt;T&gt; list, K value, 
    Converter&lt;T, K&gt; convert) <strong>where</strong> K : IComparable&lt;K&gt; {
    <b>return</b> list.BinarySearch(value, convert, (n, m) =&gt; n.CompareTo(m));
}</pre>
        </blockquote>
        <p>which uses a lambda function to create a <code>Comparison&lt;T&gt;</code>  for any 
type that supports <code>IComparable&lt;T&gt;</code>. Beware that this doesn't 
work well with reference types because it doesn't check for <strong><code>null</code></strong>. 
You can make it safer by putting <strong><code>struct</code></strong> in the
<strong><code>where</code></strong> clause but that seemed overly restrictive to 
me.</p>
        <p>Now that I have a <code>BinarySearch()</code> that meets my needs better than the built-in
<code>BinarySearch()</code>, my next thought was I should evangelize the benefits my version 
of <code>BinarySearch()</code> to the team responsible for maintaining the CLR 
collections and, maybe, someday, I will have it as 
a native part of the CLR; maybe, someday. Then I remember extensions methods. In 
C# 3.0, with a slight modification to the above methods, they can appear as if 
they were already part of the CLR.</p>
        <blockquote>
          <pre>
            <b>public</b>
            <b>static</b>
            <b>class</b> ListExtensionMethods {
    <b>public</b><b>static</b><b>int</b> BinarySearch&lt;T, K&gt;(<b>this</b> IList&lt;T&gt; list, K value,
        Converter&lt;T, K&gt; convert, Comparison&lt;K&gt; compare) {
        <b>int</b> i = 0;
        <b>int</b> j = list.Count - 1;
        <b>while</b> (i &lt;= j) {
            <b>int</b> m = i + (j - i) / 2;
            <b>int</b> c = compare(convert(list[m]), value);
            <b>if</b> (c == 0)
                <b>return</b> m;
            <b>if</b> (c &lt; 0)
                i = m + 1;
            <b>else</b>
                j = m - 1;
        }
        <b>return</b> ~i;
    }

    <b>public</b><b>static</b><b>int</b> BinarySearch&lt;T, K&gt;(<b>this</b> IList&lt;T&gt; list, K value, 
        Converter&lt;T, K&gt; convert) where K : IComparable&lt;K&gt; {
        <b>return</b> list.BinarySearch(value, convert, (n, m) =&gt; n.CompareTo(m));
    }
}</pre>
        </blockquote>
        <p>My version of <code>BinarySearch()</code> now 
appears as part of the methods of any type that implements <code>IList&lt;T&gt;</code>. 
This allows us to write,</p>
        <blockquote>
          <pre>
            <strong>int</strong> location = textRangeList.BinarySearch(location, (n) =&gt; n.Location);</pre>
        </blockquote>
        <p>just like it was a native part of the CLR. No more hand-rolled <code>
BinarySearch()</code>s!</p>
        <p>Now that we have a <code>ListExtensionMethods </code>class, what other missing methods 
could we add? Here are a few that I thought would be useful,</p>
        <blockquote>
          <pre>
            <b>public</b>
            <b>static</b>
            <b>void</b> Sort&lt;T, K&gt;(<b>this</b> List&lt;T&gt; list, 
    Converter&lt;T, K&gt; coverter, Comparison&lt;K&gt; compare) {
    list.Sort((n, m) =&gt; compare(convert(n), convert(m)));
}

<b>public</b><b>static</b><b>void</b> Sort&lt;T, K&gt;(<b>this</b> List&lt;T&gt; list, 
    Converter&lt;T, K&gt;  converter) <b>where</b> K : IComparable&lt;K&gt; {
    list.Sort((n, m) =&gt; convert(n).CompareTo(convert(m)));
}

<b>public</b><b>static</b><b>void</b> Swap&lt;T&gt;(<b>this</b> IList&lt;T&gt; list, <b>int</b> index1, 
    <b>int</b> index2) {
    var value = list[index1];
    list[index1] = list[index2];
    list[index2] = value;
}

<b>public</b><b>static</b><b>void</b> Shuffle&lt;T&gt;(<b>this</b> IList&lt;T&gt; list) {
    <b>int</b> count = list.Count;
    Random r = <b>new</b> Random();
    <b>for</b>(<b>int</b> i = count - 1; i &gt; 1; i--)
        list.Swap(i, r.Next(i - 1));
}</pre>
        </blockquote>
        <p>The <code>Sort()</code> methods above are allow you to extract a key for 
sorting using the same methods as above. These are not strictly necessary since 
constructing the lambda function I use is not that complicated but I believe they 
make the code more readable if you are consistent in how you extract keys from a 
list, so these are convenient wrappers that allow you to use the same methods to 
sort and search. <code>Swap()</code> and
<code>Shuffle()</code> are throw-ins. They are really only useful for demo code 
or, in my case, test code. I used them to test the <code>Sort()</code> method 
which I used to test the <code>BinarySearch()</code> method.</p>
      </body>
      <comments>http://www.removingalldoubt.com/commentview.aspx/f7e6feff-8257-4efe-ad64-acd1c7a4a1e3</comments>
      <category>Programming</category>
    </item>
  </channel>
</rss>
