<?xml version="1.0" encoding="UTF-8" ?>
<?xml-stylesheet type="text/xsl" href="http://blogs.msdn.com/utility/FeedStylesheets/rss.xsl" media="screen"?><rss version="2.0" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:slash="http://purl.org/rss/1.0/modules/slash/" xmlns:wfw="http://wellformedweb.org/CommentAPI/"><channel><title>Yet Another Language Geek</title><link>http://blogs.msdn.com/wesdyer/default.aspx</link><description /><dc:language>en-US</dc:language><generator>CommunityServer 2.1 SP1 (Build: 61025.2)</generator><item><title>A Brief Introduction to the Reactive Extensions for .NET, Rx</title><link>http://blogs.msdn.com/wesdyer/archive/2009/11/18/a-brief-introduction-to-the-reactive-extensions-for-net-rx.aspx</link><pubDate>Wed, 18 Nov 2009 23:26:31 GMT</pubDate><guid isPermaLink="false">91d46819-8472-40ad-a661-2c78acb4018c:9924867</guid><dc:creator>wesdyer</dc:creator><slash:comments>17</slash:comments><comments>http://blogs.msdn.com/wesdyer/comments/9924867.aspx</comments><wfw:commentRss>http://blogs.msdn.com/wesdyer/commentrss.aspx?PostID=9924867</wfw:commentRss><description>&lt;p&gt;Wow, it has been a long time since I have blogged.&amp;#160; Yesterday, we made the first official public release of Rx on &lt;a href="http://msdn.microsoft.com/en-us/devlabs/ee794896.aspx"&gt;devlabs&lt;/a&gt;.&amp;#160; And that means that I can now talk about what has been on my mind for the past while: Rx.&amp;#160; What is Rx?&amp;#160; Rx is short for the Reactive Extensions for .NET.&amp;#160; Think of it as a prescription strength library for writing reactive programs in your favorite .NET language.&lt;/p&gt;  &lt;p&gt;Today, I want to give you a brief introduction to Rx that complements my &lt;a href="http://channel9.msdn.com/posts/J.Van.Gogh/Writing-your-first-Rx-Application/"&gt;screencast&lt;/a&gt;.&amp;#160; In subsequent posts, I will dive deep into the semantics of Rx providing detailed explanations and examples.&amp;#160; Hopefully, this will positively impact your day to day work and allow you to have a lot of fun in the process.&amp;#160; Please feel free to ask any questions that you may have or &lt;a href="http://social.msdn.microsoft.com/Forums/en-US/rx/threads"&gt;provide feedback about Rx&lt;/a&gt;.&amp;#160; This first release is a sort of preview of the technology.&amp;#160; We will provide regular updates that both extend and refine the library and we want you to be a part of that process.&lt;/p&gt;  &lt;p&gt;&lt;strong&gt;First Steps&lt;/strong&gt;&lt;/p&gt;  &lt;p&gt;Rx is currently available for &lt;a href="http://download.microsoft.com/download/6/2/A/62A3E195-254C-445A-8109-6AE77A28AB63/Rx_Net35_SP1.exe"&gt;.NET Framework 3.5 SP1&lt;/a&gt;, &lt;a href="http://download.microsoft.com/download/4/B/9/4B91A290-925C-4E2E-BEF3-996CF4B50661/Rx_Net4_Beta2.exe"&gt;.NET Framework 4 Beta 2&lt;/a&gt;, and &lt;a href="http://download.microsoft.com/download/9/6/B/96BE463C-F261-45CE-A4FA-D1052339505F/Rx_SL3.exe"&gt;Silverlight 3&lt;/a&gt;.&amp;#160; Download and install one of these versions and then open Visual Studio.&lt;/p&gt;  &lt;p&gt;&lt;a href="http://blogs.msdn.com/blogfiles/wesdyer/WindowsLiveWriter/AGentleIntroductiontotheReactiveEx.NETRx_B78F/image_2.png"&gt;&lt;img style="border-bottom: 0px; border-left: 0px; display: inline; border-top: 0px; border-right: 0px" title="image" border="0" alt="image" src="http://blogs.msdn.com/blogfiles/wesdyer/WindowsLiveWriter/AGentleIntroductiontotheReactiveEx.NETRx_B78F/image_thumb.png" width="244" height="65" /&gt;&lt;/a&gt; &lt;/p&gt;  &lt;p&gt;Create a WPF Application or a Silverlight Application.&lt;/p&gt;  &lt;p&gt;&lt;a href="http://blogs.msdn.com/blogfiles/wesdyer/WindowsLiveWriter/AGentleIntroductiontotheReactiveEx.NETRx_B78F/image_6.png"&gt;&lt;img style="border-bottom: 0px; border-left: 0px; display: inline; border-top: 0px; border-right: 0px" title="image" border="0" alt="image" src="http://blogs.msdn.com/blogfiles/wesdyer/WindowsLiveWriter/AGentleIntroductiontotheReactiveEx.NETRx_B78F/image_thumb_2.png" width="245" height="84" /&gt;&lt;/a&gt; &lt;/p&gt;  &lt;p&gt;&lt;a href="http://blogs.msdn.com/blogfiles/wesdyer/WindowsLiveWriter/AGentleIntroductiontotheReactiveEx.NETRx_B78F/image_8.png"&gt;&lt;img style="border-bottom: 0px; border-left: 0px; display: inline; border-top: 0px; border-right: 0px" title="image" border="0" alt="image" src="http://blogs.msdn.com/blogfiles/wesdyer/WindowsLiveWriter/AGentleIntroductiontotheReactiveEx.NETRx_B78F/image_thumb_3.png" width="319" height="196" /&gt;&lt;/a&gt; &lt;/p&gt;  &lt;p&gt;&lt;strong&gt;The Chrome&lt;/strong&gt;&lt;/p&gt;  &lt;p&gt;&lt;/p&gt;  &lt;p&gt;&lt;/p&gt;  &lt;p&gt;&lt;/p&gt;  &lt;p&gt;When the designer opens, replace the existing Grid control with the following XAML.&lt;/p&gt;  &lt;blockquote&gt;   &lt;p&gt;&lt;font color="#0000ff" face="Courier New"&gt;&amp;lt;&lt;font color="#800040"&gt;Canvas&lt;/font&gt;&amp;gt;        &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &amp;lt;&lt;font color="#800000"&gt;TextBlock&lt;/font&gt;        &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;font color="#ff0000"&gt;x&lt;/font&gt;:&lt;font color="#ff0000"&gt;Name&lt;/font&gt;=&amp;quot;textBlock&amp;quot;        &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;font color="#ff0000"&gt;Text&lt;/font&gt;=&amp;quot;Rx Rocks!&amp;quot; /&amp;gt;        &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &amp;lt;&lt;font color="#800000"&gt;Image         &lt;br /&gt;&lt;/font&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;font color="#ff0000"&gt;x&lt;/font&gt;:&lt;font color="#ff0000"&gt;Name&lt;/font&gt;=&amp;quot;image&amp;quot;        &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;font color="#ff0000"&gt;Source&lt;/font&gt;=&amp;quot;&lt;/font&gt;&lt;a href="http://upload.wikimedia.org/wikipedia/commons/7/7a/Rx_symbol.png&amp;quot;"&gt;&lt;font color="#0000ff" face="Courier New"&gt;http://upload.wikimedia.org/wikipedia/commons/7/7a/Rx_symbol.png&amp;quot;&lt;/font&gt;&lt;/a&gt;      &lt;br /&gt;&lt;font color="#0000ff" face="Courier New"&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;font color="#ff0000"&gt;Width&lt;/font&gt;=&amp;quot;100&amp;quot;        &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;font color="#ff0000"&gt;Height&lt;/font&gt;=&amp;quot;100&amp;quot;        &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;font color="#ff0000"&gt;Canvas.Left&lt;/font&gt;=&amp;quot;0&amp;quot;        &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;font color="#ff0000"&gt;Canvas.Top&lt;/font&gt;=&amp;quot;25&amp;quot; /&amp;gt;        &lt;br /&gt;&amp;lt;/&lt;font color="#800000"&gt;Canvas&lt;/font&gt;&amp;gt; &lt;/font&gt;&lt;/p&gt; &lt;/blockquote&gt;  &lt;p&gt;Then switch to the code view.&lt;/p&gt;  &lt;p&gt;&lt;a href="http://blogs.msdn.com/blogfiles/wesdyer/WindowsLiveWriter/AGentleIntroductiontotheReactiveEx.NETRx_B78F/image_10.png"&gt;&lt;img style="border-bottom: 0px; border-left: 0px; display: inline; border-top: 0px; border-right: 0px" title="image" border="0" alt="image" src="http://blogs.msdn.com/blogfiles/wesdyer/WindowsLiveWriter/AGentleIntroductiontotheReactiveEx.NETRx_B78F/image_thumb_4.png" width="216" height="64" /&gt;&lt;/a&gt; &lt;/p&gt;  &lt;p&gt;&lt;strong&gt;Starting with Rx&lt;/strong&gt;&lt;/p&gt;  &lt;p&gt;To begin using Rx, first add a reference to &lt;strong&gt;System.Reactive&lt;/strong&gt; and &lt;strong&gt;System.CoreEx&lt;/strong&gt;.&amp;#160; The two other assemblies included with this release are System.Threading (task parallel library) and System.Interactive (more enumerable goodness).&lt;/p&gt;  &lt;p&gt;&lt;a href="http://blogs.msdn.com/blogfiles/wesdyer/WindowsLiveWriter/AGentleIntroductiontotheReactiveEx.NETRx_B78F/image_12.png"&gt;&lt;img style="border-bottom: 0px; border-left: 0px; display: inline; border-top: 0px; border-right: 0px" title="image" border="0" alt="image" src="http://blogs.msdn.com/blogfiles/wesdyer/WindowsLiveWriter/AGentleIntroductiontotheReactiveEx.NETRx_B78F/image_thumb_5.png" width="244" height="70" /&gt;&lt;/a&gt; &lt;/p&gt;  &lt;p&gt;&lt;a href="http://blogs.msdn.com/blogfiles/wesdyer/WindowsLiveWriter/AGentleIntroductiontotheReactiveEx.NETRx_B78F/image_14.png"&gt;&lt;img style="border-bottom: 0px; border-left: 0px; display: inline; border-top: 0px; border-right: 0px" title="image" border="0" alt="image" src="http://blogs.msdn.com/blogfiles/wesdyer/WindowsLiveWriter/AGentleIntroductiontotheReactiveEx.NETRx_B78F/image_thumb_6.png" width="290" height="253" /&gt;&lt;/a&gt; &lt;/p&gt;  &lt;p&gt;&lt;a href="http://blogs.msdn.com/blogfiles/wesdyer/WindowsLiveWriter/AGentleIntroductiontotheReactiveEx.NETRx_B78F/image_16.png"&gt;&lt;img style="border-bottom: 0px; border-left: 0px; display: inline; border-top: 0px; border-right: 0px" title="image" border="0" alt="image" src="http://blogs.msdn.com/blogfiles/wesdyer/WindowsLiveWriter/AGentleIntroductiontotheReactiveEx.NETRx_B78F/image_thumb_7.png" width="294" height="256" /&gt;&lt;/a&gt;&amp;#160;&lt;/p&gt;  &lt;p&gt;Once you have added a reference to System.Reactive and System.CoreEx, then you can use the reactive operators found in Observable.&lt;/p&gt;  &lt;p&gt;&lt;strong&gt;Observable Sequences&lt;/strong&gt;&lt;/p&gt;  &lt;p&gt;Observables, like enumerables, are sequences.&amp;#160; The only difference is that the latter is pull-based and the former is push-based.&amp;#160; Both sequences are a possibly empty sequence of values optionally followed by either normal termination or abnormal termination.&lt;/p&gt;  &lt;p&gt;When you want to enumerate an enumerable:&lt;/p&gt;  &lt;blockquote&gt;   &lt;p&gt;1.&amp;#160; Get the enumerator from the enumerable&lt;/p&gt;    &lt;p&gt;2.&amp;#160; Call MoveNext and call Current on the enumerator for each value in the sequence&lt;/p&gt;    &lt;p&gt;3.&amp;#160; The sequence ends when MoveNext returns false (normal termination) or MoveNext or Current throws an exception (abnormal termination)&lt;/p&gt; &lt;/blockquote&gt;  &lt;p&gt;The user writes a foreach statement over an enumerable sequence.&lt;/p&gt;  &lt;blockquote&gt;   &lt;p&gt;&lt;font face="Courier New"&gt;&lt;font color="#0000ff"&gt;foreach&lt;/font&gt; (&lt;font color="#0000ff"&gt;var&lt;/font&gt; x &lt;font color="#0000ff"&gt;in&lt;/font&gt; xs)        &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; F(x); &lt;/font&gt;&lt;/p&gt; &lt;/blockquote&gt;  &lt;p&gt;With enumerables, each value is pulled out of the source and bound to the iteration variable before executing the user code.&amp;#160; Note that the consumer controls this process.&lt;/p&gt;  &lt;p&gt;When you want to observe an observable sequence:&lt;/p&gt;  &lt;blockquote&gt;   &lt;p&gt;1.&amp;#160; Subscribe an observer to the observable&lt;/p&gt;    &lt;p&gt;2.&amp;#160; OnNext is called on the observer for each value in the sequence&lt;/p&gt;    &lt;p&gt;3.&amp;#160; The sequence ends when OnCompleted (normal termination) or OnError (abnormal termination) is called on the observer&lt;/p&gt; &lt;/blockquote&gt;  &lt;p&gt;The user writes a subscribe statement over an observable sequence.&lt;/p&gt;  &lt;blockquote&gt;   &lt;p&gt;&lt;font face="Courier New"&gt;xs.Subscribe(x =&amp;gt; F(x));&lt;/font&gt;&lt;/p&gt; &lt;/blockquote&gt;  &lt;p&gt;With observables, each value is pushed out of the source and bound to the handler variable before executing the user code.&amp;#160; Note that the producer controls this process.&lt;/p&gt;  &lt;p&gt;&lt;strong&gt;Hello, World!&lt;/strong&gt;&lt;/p&gt;  &lt;p&gt;Let’s write our first Rx application, the obligatory “Hello, World!” application.&lt;/p&gt;  &lt;p&gt;Remember all those times that you wrote UI applications with asynchronous operations and got the dreaded Cross-Thread operation exception.&lt;/p&gt;  &lt;p&gt;&lt;a href="http://blogs.msdn.com/blogfiles/wesdyer/WindowsLiveWriter/AGentleIntroductiontotheReactiveEx.NETRx_B78F/image_18.png"&gt;&lt;img style="border-bottom: 0px; border-left: 0px; display: inline; border-top: 0px; border-right: 0px" title="image" border="0" alt="image" src="http://blogs.msdn.com/blogfiles/wesdyer/WindowsLiveWriter/AGentleIntroductiontotheReactiveEx.NETRx_B78F/image_thumb_8.png" width="337" height="189" /&gt;&lt;/a&gt; &lt;/p&gt;  &lt;p&gt;Well Rx, makes this simpler despite the fact that it has &lt;strong&gt;a lot&lt;/strong&gt; of asynchronous and event-based operations going on at once.&lt;/p&gt;  &lt;p&gt;The user may specify the default SynchronizationContext to which to send Rx messages.&amp;#160; By default, it uses a reactive event loop except in Silverlight where it uses the dispatcher by default.&amp;#160; The user can change this by setting Observable.Context to the appropriate SynchronizationContext.&amp;#160; Rx provides a few commonly used synchronization contexts in the class SynchronizationContexts.&lt;/p&gt;  &lt;p&gt;Since we are using WPF, we should set the default context to the dispatcher context.&lt;/p&gt;  &lt;blockquote&gt;   &lt;p&gt;&lt;font face="Courier New"&gt;&lt;font color="#008080"&gt;Observable&lt;/font&gt;.Context = &lt;font color="#008080"&gt;SynchronizationContexts&lt;/font&gt;.CurrentDispatcher;&lt;/font&gt; &lt;/p&gt; &lt;/blockquote&gt;  &lt;p&gt;Now, we can use the UI without getting cross-thread exceptions.&lt;/p&gt;  &lt;p&gt;Rx includes a number of basic operations for constructing observable sequences.&amp;#160; For example, Return creates a singleton sequence that contains an OnNext message with the specified value followed by an OnCompleted message.&amp;#160; We can then subscribe to the observable using a value handler which specifies what to do with each OnNext message from the observable sequence.&lt;/p&gt;  &lt;p&gt;&lt;/p&gt;  &lt;p&gt;&lt;/p&gt;  &lt;p&gt;&lt;/p&gt;  &lt;blockquote&gt;   &lt;p&gt;&lt;font face="Courier New"&gt;&lt;font color="#0000ff"&gt;var&lt;/font&gt; helloWorld = &lt;font color="#008080"&gt;Observable&lt;/font&gt;.Return(&lt;font color="#800000"&gt;&amp;quot;Hello, World!&amp;quot;&lt;/font&gt;); &lt;/font&gt;&lt;/p&gt;    &lt;p&gt;&lt;font face="Courier New"&gt;helloWorld.Subscribe(value =&amp;gt; textBlock.Text = value);&lt;/font&gt;&lt;/p&gt; &lt;/blockquote&gt;  &lt;p&gt;When we run the application, we see that the text is set to “Hello, World!”.&lt;/p&gt;  &lt;p&gt;&lt;a href="http://blogs.msdn.com/blogfiles/wesdyer/WindowsLiveWriter/AGentleIntroductiontotheReactiveEx.NETRx_B78F/image_20.png"&gt;&lt;img style="border-bottom: 0px; border-left: 0px; display: inline; border-top: 0px; border-right: 0px" title="image" border="0" alt="image" src="http://blogs.msdn.com/blogfiles/wesdyer/WindowsLiveWriter/AGentleIntroductiontotheReactiveEx.NETRx_B78F/image_thumb_9.png" width="244" height="244" /&gt;&lt;/a&gt; &lt;/p&gt;  &lt;p&gt;&lt;strong&gt;A Second Step&lt;/strong&gt;&lt;/p&gt;  &lt;p&gt;Another basic operation for constructing observable sequences, is the Interval operator.&amp;#160; It creates an observable sequence that repeatedly sends an OnNext message after the specified time interval.&amp;#160; For example, we can create an observable sequence that sends a message after every second.&lt;/p&gt;  &lt;blockquote&gt;   &lt;p&gt;&lt;font face="Courier New"&gt;&lt;font color="#0000ff"&gt;var&lt;/font&gt; timer = &lt;font color="#008080"&gt;Observable&lt;/font&gt;.Interval(&lt;font color="#008080"&gt;TimeSpan&lt;/font&gt;.FromSeconds(1)); &lt;/font&gt;&lt;/p&gt;    &lt;p&gt;&lt;font face="Courier New"&gt;timer.Subscribe(value =&amp;gt; textBlock.Text = value.ToString());&lt;/font&gt; &lt;/p&gt; &lt;/blockquote&gt;  &lt;p&gt;&lt;a href="http://blogs.msdn.com/blogfiles/wesdyer/WindowsLiveWriter/AGentleIntroductiontotheReactiveEx.NETRx_B78F/image_22.png"&gt;&lt;img style="border-bottom: 0px; border-left: 0px; display: inline; border-top: 0px; border-right: 0px" title="image" border="0" alt="image" src="http://blogs.msdn.com/blogfiles/wesdyer/WindowsLiveWriter/AGentleIntroductiontotheReactiveEx.NETRx_B78F/image_thumb_10.png" width="244" height="244" /&gt;&lt;/a&gt;&amp;#160;&lt;/p&gt;  &lt;p&gt;&lt;strong&gt;Wrapping .NET Events&lt;/strong&gt;&lt;/p&gt;  &lt;p&gt;Another source of observable sequences is existing .NET events and asynchronous computations.&amp;#160; We can bring these existing reactive sources into Rx by using conversions.&amp;#160; For example, we can convert .NET events to observable sequences using the FromEvent operator.&amp;#160; The user must specify the type of EventArgs for the event, the target, and the event name.&amp;#160; We can use this to convert the MouseDown event on the image to an observable sequence of events&lt;/p&gt;  &lt;blockquote&gt;   &lt;p&gt;&lt;font face="Courier New"&gt;&lt;font color="#0000ff"&gt;var&lt;/font&gt; mouseDown = &lt;font color="#008080"&gt;Observable&lt;/font&gt;.FromEvent&amp;lt;&lt;font color="#008080"&gt;MouseButtonEventArgs&lt;/font&gt;&amp;gt;(image, &lt;font color="#800000"&gt;&amp;quot;MouseDown&amp;quot;&lt;/font&gt;);&lt;/font&gt; &lt;/p&gt; &lt;/blockquote&gt;  &lt;p&gt;&lt;strong&gt;LINQ to Rx&lt;/strong&gt;&lt;/p&gt;  &lt;p&gt;Observable contains an implementation of the standard query operators for observable sequences and that means that we can use LINQ to write queries over observable sequences.&amp;#160; For example, we can modify our mouseDown observable sequence to contain a sequence of position values by projecting each event to the current mouse position relative to the image.&lt;/p&gt;  &lt;blockquote&gt;   &lt;p&gt;&lt;font face="Courier New"&gt;&lt;font color="#0000ff"&gt;var&lt;/font&gt; mouseDown = &lt;font color="#0000ff"&gt;from&lt;/font&gt; evt &lt;font color="#0000ff"&gt;in &lt;/font&gt;&lt;/font&gt;&lt;font face="Courier New"&gt;&lt;font color="#008080"&gt;Observable&lt;/font&gt;.FromEvent&amp;lt;&lt;font color="#008080"&gt;MouseButtonEventArgs&lt;/font&gt;&amp;gt;(image, &lt;font color="#800000"&gt;&amp;quot;MouseDown&amp;quot;&lt;/font&gt;)        &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;font color="#0000ff"&gt;select&lt;/font&gt; evt.EventArgs.GetPosition(image);&lt;/font&gt; &lt;/p&gt; &lt;/blockquote&gt;  &lt;p&gt;&lt;strong&gt;Composition&lt;/strong&gt;&lt;/p&gt;  &lt;p&gt;Rx also contains a number of operators to compose together observable sequences in a way very similar to how Linq to Objects composes together enumerable sequences. For example, the operator Until takes all of the messages from the left source until an OnNext message occurs on the right source at which time it will unsubscribe from the left source and the right source.&lt;/p&gt;  &lt;blockquote&gt;   &lt;p&gt;&lt;font face="Courier New"&gt;&lt;font color="#0000ff"&gt;var &lt;/font&gt;q = timer.Until(mouseDown); &lt;/font&gt;&lt;/p&gt;    &lt;p&gt;&lt;font face="Courier New"&gt;q.Subscribe(value =&amp;gt; textBlock.Text = value.ToString()); &lt;/font&gt;&lt;/p&gt; &lt;/blockquote&gt;  &lt;p&gt;&lt;strong&gt;Drag and Drop&lt;/strong&gt;&lt;/p&gt;  &lt;p&gt;We can put together these simple pieces and build drag and drop.&amp;#160; In the screencast, I wrote drag and drop using the mouse deltas, here I will write it using the mouse offset to show another way to do the same thing.&amp;#160; As you begin to use Rx, you will find that often you can simplify your queries repeatedly and if you do it right then at the end you will get a query that looks remarkably like the specification of the problem.&lt;/p&gt;  &lt;p&gt;What is the specification of drag and drop?&amp;#160; Every time the user clicks down on the image, we want to move the image relative to where she clicked down until the mouse button goes up.&lt;/p&gt;  &lt;p&gt;Therefore, we need three events: the mouse down on the image, the mouse move on the window, and the mouse up on the window.&amp;#160; For the mouse down, we need the position relative to the image, for the mouse move, we need the position relative to the window, and for the mouse up we do not need the position.&lt;/p&gt;  &lt;blockquote&gt;   &lt;p&gt;&lt;font face="Courier New"&gt;&lt;font color="#0000ff"&gt;var&lt;/font&gt; mouseDown = &lt;font color="#0000ff"&gt;from&lt;/font&gt; evt &lt;font color="#0000ff"&gt;in&lt;/font&gt; &lt;font color="#008080"&gt;Observable&lt;/font&gt;.FromEvent&amp;lt;&lt;font color="#008080"&gt;MouseButtonEventArgs&lt;/font&gt;&amp;gt;(image, &lt;font color="#800000"&gt;&amp;quot;MouseDown&amp;quot;&lt;/font&gt;)        &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;font color="#0000ff"&gt;select&lt;/font&gt; evt.EventArgs.GetPosition(image); &lt;/font&gt;&lt;/p&gt;    &lt;p&gt;&lt;font face="Courier New"&gt;&lt;font color="#0000ff"&gt;var&lt;/font&gt; mouseUp = &lt;font color="#008080"&gt;Observable&lt;/font&gt;.FromEvent&amp;lt;&lt;font color="#008080"&gt;MouseButtonEventArgs&lt;/font&gt;&amp;gt;(image, &lt;font color="#800000"&gt;&amp;quot;MouseUp&amp;quot;&lt;/font&gt;); &lt;/font&gt;&lt;/p&gt;    &lt;p&gt;&lt;font face="Courier New"&gt;&lt;font color="#0000ff"&gt;var&lt;/font&gt; mouseMove = &lt;font color="#0000ff"&gt;from&lt;/font&gt; evt &lt;font color="#0000ff"&gt;in&lt;/font&gt; &lt;font color="#008080"&gt;Observable&lt;/font&gt;.FromEvent&amp;lt;&lt;font color="#008080"&gt;MouseEventArgs&lt;/font&gt;&amp;gt;(image, &amp;quot;MouseMove&amp;quot;)        &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;font color="#0000ff"&gt;select&lt;/font&gt; evt.EventArgs.GetPosition(&lt;font color="#0000ff"&gt;this&lt;/font&gt;); &lt;/font&gt;&lt;/p&gt; &lt;/blockquote&gt;  &lt;p&gt;Now, we can write a query that expresses our intent.&amp;#160; When the mouse goes down grab the offset of the mouse relative to the image, and then listen to the mouse moves relative to the window until the mouse goes up.&amp;#160; For each mouse move during this time, compute the image position as the mouse position subtracted by the original offset relative to the image.&lt;/p&gt;  &lt;blockquote&gt;   &lt;p&gt;&lt;font face="Courier New"&gt;&lt;font color="#0000ff"&gt;var&lt;/font&gt; q = &lt;font color="#0000ff"&gt;from&lt;/font&gt; imageOffset &lt;font color="#0000ff"&gt;in&lt;/font&gt; mouseDown        &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;font color="#0000ff"&gt;from&lt;/font&gt; pos &lt;font color="#0000ff"&gt;in&lt;/font&gt; mouseMove.Until(mouseUp)        &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;font color="#0000ff"&gt;select new &lt;/font&gt;{ X = pos.X - imageOffset.X, Y = pos.Y - imageOffset.Y }; &lt;/font&gt;&lt;/p&gt; &lt;/blockquote&gt;  &lt;p&gt;Finally, we can subscribe to the observable sequence of positions and update the position of the image.&lt;/p&gt;  &lt;blockquote&gt;   &lt;p&gt;&lt;font face="Courier New"&gt;q.Subscribe(value =&amp;gt;       &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; {        &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;font color="#008080"&gt;Canvas&lt;/font&gt;.SetLeft(image, value.X);        &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;font color="#008080"&gt;Canvas&lt;/font&gt;.SetTop(image, value.Y);        &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; });&lt;/font&gt;&lt;/p&gt; &lt;/blockquote&gt;  &lt;p&gt;&lt;a href="http://blogs.msdn.com/blogfiles/wesdyer/WindowsLiveWriter/AGentleIntroductiontotheReactiveEx.NETRx_B78F/image_24.png"&gt;&lt;img style="border-bottom: 0px; border-left: 0px; display: inline; border-top: 0px; border-right: 0px" title="image" border="0" alt="image" src="http://blogs.msdn.com/blogfiles/wesdyer/WindowsLiveWriter/AGentleIntroductiontotheReactiveEx.NETRx_B78F/image_thumb_11.png" width="244" height="244" /&gt;&lt;/a&gt;&amp;#160;&lt;/p&gt;  &lt;p&gt;&lt;strong&gt;Looking Forward&lt;/strong&gt;&lt;/p&gt;  &lt;p&gt;&lt;/p&gt;  &lt;p&gt;Drag and drop is fun, but it is only one small example of the power of Rx.&amp;#160; Next time, we will start our deep dive into the semantics of Rx.&amp;#160; Until then take the time to download it and take it for a test drive.&lt;/p&gt;&lt;img src="http://blogs.msdn.com/aggbug.aspx?PostID=9924867" width="1" height="1"&gt;</description><category domain="http://blogs.msdn.com/wesdyer/archive/tags/Rx/default.aspx">Rx</category></item><item><title>The Marvels of Monads</title><link>http://blogs.msdn.com/wesdyer/archive/2008/01/11/the-marvels-of-monads.aspx</link><pubDate>Fri, 11 Jan 2008 03:06:13 GMT</pubDate><guid isPermaLink="false">91d46819-8472-40ad-a661-2c78acb4018c:7064392</guid><dc:creator>wesdyer</dc:creator><slash:comments>34</slash:comments><comments>http://blogs.msdn.com/wesdyer/comments/7064392.aspx</comments><wfw:commentRss>http://blogs.msdn.com/wesdyer/commentrss.aspx?PostID=7064392</wfw:commentRss><description>&lt;p&gt;If the word &lt;a href="http://blogs.msdn.com/wesdyer/archive/2007/12/22/continuation-passing-style.aspx"&gt;&amp;quot;continuation&amp;quot;&lt;/a&gt; causes eyes to glaze over, then the word &amp;quot;monad&amp;quot; induces mental paralysis.&amp;#160; Perhaps, this is why some have begun inventing more benign names for monads.&lt;/p&gt;  &lt;p&gt;These days, monads are the celebrities of programming language theory.&amp;#160; They gloss the cover of blogs and have been &lt;a href="http://www.loria.fr/~kow/monads/index.html"&gt;compared to everything&lt;/a&gt; from &lt;a href="http://www.haskell.org/haskellwiki/Monads_as_containers"&gt;boxes of fruit&lt;/a&gt; to &lt;a href="http://www.haskell.org/haskellwiki/Meet_Bob_The_Monadic_Lover"&gt;love affairs&lt;/a&gt;.&amp;#160; Nerds everywhere are exclaiming that the experience of understanding monads causes a &lt;a href="http://groups.google.com/group/comp.lang.functional/browse_thread/thread/346dd6767ecb3851"&gt;pleasantly&lt;/a&gt; &lt;a href="http://koweycode.blogspot.com/2006/08/does-haskell-hurt-your-brain.html"&gt;painful&lt;/a&gt; &lt;a href="http://lambda-the-ultimate.org/node/724"&gt;mental sensation&lt;/a&gt;.&lt;/p&gt;  &lt;p&gt;Like continuations, monads are simpler than they sound and are very useful in many situations.&amp;#160; In fact, programmers write code in a variety of languages that implicitly use common monads without even breaking a sweat.&lt;/p&gt;  &lt;p&gt;&lt;a href="http://lambda-the-ultimate.org/node/92"&gt;With&lt;/a&gt; &lt;a href="http://james-iry.blogspot.com/2007/09/monads-are-elephants-part-1.html"&gt;all&lt;/a&gt; &lt;a href="http://www.haskell.org/tutorial/monads.html"&gt;of&lt;/a&gt; &lt;a href="http://moonbase.rydia.net/mental/writings/programming/monads-in-ruby/00introduction.html"&gt;the&lt;/a&gt; &lt;a href="http://sigfpe.blogspot.com/2006/08/you-could-have-invented-monads-and.html"&gt;attention&lt;/a&gt; &lt;a href="http://www.alpheccar.org/en/posts/show/60"&gt;that&lt;/a&gt; &lt;a href="http://patryshev.com/monad/m-intro.html"&gt;monads&lt;/a&gt; &lt;a href="http://www.engr.mun.ca/~theo/Misc/haskell_and_monads.htm"&gt;get&lt;/a&gt;, why am I writing yet another explanation of monads?&amp;#160; Not to compare them to some everyday occurrence or to chronicle my journey to understanding.&amp;#160; I explain monads because I need monads.&amp;#160; They elegantly solve programming problems in a number of languages and contexts.&lt;/p&gt;  &lt;p&gt;&lt;strong&gt;Introducing Monads&lt;/strong&gt;&lt;/p&gt;  &lt;p&gt;&lt;a href="http://en.wikipedia.org/wiki/Monad_%28category_theory%29"&gt;Monads&lt;/a&gt; come from &lt;a href="http://en.wikipedia.org/wiki/Category_theory"&gt;category theory&lt;/a&gt;.&amp;#160; &lt;a href="http://www.disi.unige.it/person/MoggiE/ftp/ic91.pdf"&gt;Moggi introduced them&lt;/a&gt; to computer scientists to aid in the analysis of the semantics of computations.&amp;#160; In an excellent paper, &lt;em&gt;&lt;a href="http://coblitz.codeen.org:3125/citeseer.ist.psu.edu/cache/papers/cs/4583/http:zSzzSzcm.bell-labs.comzSzwhozSzwadlerzSztopicszSz..zSzpaperszSzessencezSzessence.pdf/wadler92essence.pdf"&gt;The Essence of Functional Programming&lt;/a&gt;&lt;/em&gt;, Wadler showed that monads are generally useful in computer programs to compose together functions which operate on amplified values rather than values.&amp;#160; &lt;a href="http://en.wikipedia.org/wiki/Monads_in_functional_programming"&gt;Monads&lt;/a&gt; became &lt;a href="http://www.haskell.org/all_about_monads/html/index.html"&gt;an important part&lt;/a&gt; of the programming language Haskell where they tackle &lt;a href="http://research.microsoft.com/~simonpj/papers/marktoberdorf/mark.pdf"&gt;the awkward squad&lt;/a&gt;: IO, concurrency, exceptions, and foreign-function calls.&lt;/p&gt;  &lt;p&gt;Monads enjoy tremendous success in Haskell, but like an actor who does well in a particular role, monads are now stereotyped in the minds of most programmers as useful only in pure lazy functional languages.&amp;#160; This is unfortunate, because monads are more broadly applicable.&lt;/p&gt;  &lt;p&gt;&lt;strong&gt;Controlling Complexity&lt;/strong&gt;&lt;/p&gt;  &lt;p&gt;Composition is the key to controlling complexity in software.&amp;#160; In &lt;em&gt;&lt;a href="http://mitpress.mit.edu/sicp/"&gt;The Structure and Interpretation of Computer Programs&lt;/a&gt;&lt;/em&gt;, Abelson and Sussman argue that composition beautifully expresses complex systems from simple patterns.&lt;/p&gt;  &lt;blockquote&gt;   &lt;p&gt;In our study of program design, we have seen that expert programmers control the complexity of their designs with the same general techniques used by designers of all complex systems. They combine primitive elements to form compound objects, they abstract compound objects to form higher-level building blocks, and they preserve modularity by adopting appropriate large-scale views of system structure.&lt;/p&gt; &lt;/blockquote&gt;  &lt;p&gt;One form of composition, function composition, succinctly describes the dependencies between function calls.&amp;#160; Function composition takes two functions and plumbs the result from the second function into the input of the first function, thereby forming one function.&lt;/p&gt;  &lt;blockquote&gt;   &lt;pre class="code"&gt;&lt;span style="color: blue"&gt;public static &lt;/span&gt;&lt;span style="color: #2b91af"&gt;Func&lt;/span&gt;&amp;lt;T, V&amp;gt; Compose&amp;lt;T, U, V&amp;gt;(&lt;span style="color: blue"&gt;this &lt;/span&gt;&lt;span style="color: #2b91af"&gt;Func&lt;/span&gt;&amp;lt;U, V&amp;gt; f, &lt;span style="color: #2b91af"&gt;Func&lt;/span&gt;&amp;lt;T, U&amp;gt; g)
{
    &lt;span style="color: blue"&gt;return &lt;/span&gt;x =&amp;gt; f(g(x));
}&lt;/pre&gt;
&lt;/blockquote&gt;
&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;

&lt;p&gt;For example, instead of applying &lt;em&gt;g&lt;/em&gt; to the value &lt;em&gt;x&lt;/em&gt; and then applying &lt;em&gt;f&lt;/em&gt; to the result, compose &lt;em&gt;f&lt;/em&gt; with &lt;em&gt;g&lt;/em&gt; and then apply the result to the value &lt;em&gt;x&lt;/em&gt;.&amp;#160; The key difference is the abstraction of the dependency between &lt;em&gt;f&lt;/em&gt; and &lt;em&gt;g&lt;/em&gt;.&lt;/p&gt;

&lt;blockquote&gt;
  &lt;pre class="code"&gt;&lt;span style="color: blue"&gt;var &lt;/span&gt;r = f(g(x));         &lt;font color="#008000"&gt;// without function composition&lt;/font&gt;
&lt;span style="color: blue"&gt;var &lt;/span&gt;r = f.Compose(g)(x); &lt;font color="#008000"&gt;// with function composition&lt;/font&gt;&lt;/pre&gt;
&lt;/blockquote&gt;
&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;

&lt;p&gt;Given the function &lt;em&gt;Identity&lt;/em&gt;, function composition must obey three laws.&lt;/p&gt;

&lt;blockquote&gt;
  &lt;pre class="code"&gt;&lt;span style="color: blue"&gt;public static &lt;/span&gt;T Identity&amp;lt;T&amp;gt;(&lt;span style="color: blue"&gt;this &lt;/span&gt;T value)
{
    &lt;span style="color: blue"&gt;return &lt;/span&gt;value;
}&lt;/pre&gt;
&lt;/blockquote&gt;

&lt;blockquote&gt;
  &lt;p&gt;&lt;strong&gt;1.&amp;#160; Left identity&lt;/strong&gt;&lt;/p&gt;

  &lt;p&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160; Identity.Compose(f) = f&lt;/p&gt;

  &lt;p&gt;&lt;strong&gt;2.&amp;#160; Right identity&lt;/strong&gt;&lt;/p&gt;

  &lt;p&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160; f.Compose(Identity) = f&lt;/p&gt;

  &lt;p&gt;&lt;strong&gt;3.&amp;#160; Associative&lt;/strong&gt;&lt;/p&gt;

  &lt;p&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160; f.Compose(g.Compose(h)) = (f.Compose(g)).Compose(h)&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;Often, values are not enough.&amp;#160; Constructed types amplify values.&amp;#160; The type &lt;em&gt;IEnumerable&amp;lt;T&amp;gt;&lt;/em&gt; represents a lazily computed list of values of type &lt;em&gt;T&lt;/em&gt;.&amp;#160; The type &lt;em&gt;Nullable&amp;lt;T&amp;gt;&lt;/em&gt; represents a possibly missing value of type &lt;em&gt;T&lt;/em&gt;.&amp;#160; The type &lt;em&gt;Func&amp;lt;Func&amp;lt;T, Answer&amp;gt;, Answer&amp;gt; &lt;/em&gt;represents a function, which returns an &lt;em&gt;Answer&lt;/em&gt; given a continuation, which takes a &lt;em&gt;T &lt;/em&gt;and returns an &lt;em&gt;Answer&lt;/em&gt;.&amp;#160; Each of these types amplifies the type &lt;em&gt;T&lt;/em&gt;.&lt;/p&gt;

&lt;p&gt;Suppose that instead of composing functions which return values, we compose functions which take values and return amplified values.&amp;#160; Let &lt;em&gt;M&amp;lt;T&amp;gt;&lt;/em&gt; denote the type of the amplified values.&lt;/p&gt;

&lt;blockquote&gt;
  &lt;pre class="code"&gt;&lt;span style="color: blue"&gt;public static &lt;/span&gt;&lt;span style="color: #2b91af"&gt;Func&lt;/span&gt;&amp;lt;T, &lt;span style="color: #2b91af"&gt;M&lt;/span&gt;&amp;lt;V&amp;gt;&amp;gt; Compose&amp;lt;T, U, V&amp;gt;(&lt;span style="color: blue"&gt;this &lt;/span&gt;&lt;span style="color: #2b91af"&gt;Func&lt;/span&gt;&amp;lt;U, &lt;span style="color: #2b91af"&gt;M&lt;/span&gt;&amp;lt;V&amp;gt;&amp;gt; f, &lt;span style="color: #2b91af"&gt;Func&lt;/span&gt;&amp;lt;T, &lt;span style="color: #2b91af"&gt;M&lt;/span&gt;&amp;lt;U&amp;gt;&amp;gt; g)
{
    &lt;span style="color: blue"&gt;return &lt;/span&gt;x =&amp;gt; f(g(x)); &lt;span style="color: green"&gt;// error, g(x) returns M&amp;lt;U&amp;gt; and f takes U
&lt;/span&gt;}&lt;/pre&gt;
&lt;/blockquote&gt;
&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;

&lt;p&gt;Function composition fails, because the return and input types do not match.&amp;#160; Composition with amplified values requires a function that accesses the underlying value and feeds it to the next function.&amp;#160; Call that function &amp;quot;Bind&amp;quot; and use it to define function composition.&lt;/p&gt;

&lt;blockquote&gt;
  &lt;pre class="code"&gt;&lt;span style="color: blue"&gt;public static &lt;/span&gt;&lt;span style="color: #2b91af"&gt;Func&lt;/span&gt;&amp;lt;T, &lt;span style="color: #2b91af"&gt;M&lt;/span&gt;&amp;lt;V&amp;gt;&amp;gt; Compose&amp;lt;T, U, V&amp;gt;(&lt;span style="color: blue"&gt;this &lt;/span&gt;&lt;span style="color: #2b91af"&gt;Func&lt;/span&gt;&amp;lt;U, &lt;span style="color: #2b91af"&gt;M&lt;/span&gt;&amp;lt;V&amp;gt;&amp;gt; f, &lt;span style="color: #2b91af"&gt;Func&lt;/span&gt;&amp;lt;T, &lt;span style="color: #2b91af"&gt;M&lt;/span&gt;&amp;lt;U&amp;gt;&amp;gt; g)
{
    &lt;span style="color: blue"&gt;return &lt;/span&gt;x =&amp;gt; Bind(g(x), f);
}&lt;/pre&gt;
&lt;/blockquote&gt;
&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;

&lt;p&gt;The input and output types determine the signature of &lt;em&gt;Bind.&lt;/em&gt;&amp;#160; Therefore, &lt;em&gt;Bind&lt;/em&gt; takes an amplified value, M&amp;lt;&lt;em&gt;U&amp;gt;,&lt;/em&gt; and a function from &lt;em&gt;U&lt;/em&gt;&amp;#160; to &lt;em&gt;M&amp;lt;V&amp;gt;&lt;/em&gt;, and returns an amplified value, &lt;em&gt;M&amp;lt;V&amp;gt;&lt;/em&gt;.&lt;/p&gt;

&lt;blockquote&gt;
  &lt;pre class="code"&gt;&lt;span style="color: blue"&gt;public static &lt;/span&gt;&lt;span style="color: #2b91af"&gt;M&lt;/span&gt;&amp;lt;V&amp;gt; Bind&amp;lt;U, V&amp;gt;(&lt;span style="color: blue"&gt;this &lt;/span&gt;&lt;span style="color: #2b91af"&gt;M&lt;/span&gt;&amp;lt;U&amp;gt; m, &lt;span style="color: #2b91af"&gt;Func&lt;/span&gt;&amp;lt;U, &lt;span style="color: #2b91af"&gt;M&lt;/span&gt;&amp;lt;V&amp;gt;&amp;gt; k)&lt;/pre&gt;
&lt;/blockquote&gt;
&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;

&lt;p&gt;The body of &lt;em&gt;Bind&lt;/em&gt; depends on the mechanics of the amplified values, &lt;em&gt;M&amp;lt;T&amp;gt;&lt;/em&gt;.&amp;#160; Each amplified type will need a distinct definition of &lt;em&gt;Bind&lt;/em&gt;.&lt;/p&gt;

&lt;p&gt;In addition to &lt;em&gt;Bind&lt;/em&gt;, define a function which takes an unamplified value and amplifies it.&amp;#160; Call this function &amp;quot;Unit&amp;quot;.&lt;/p&gt;

&lt;blockquote&gt;
  &lt;pre class="code"&gt;&lt;span style="color: blue"&gt;public static &lt;/span&gt;&lt;span style="color: #2b91af"&gt;M&lt;/span&gt;&amp;lt;T&amp;gt; Unit&amp;lt;T&amp;gt;(&lt;span style="color: blue"&gt;this &lt;/span&gt;T value)&lt;/pre&gt;
&lt;/blockquote&gt;

&lt;p&gt;Together the amplified type, &lt;em&gt;M&amp;lt;T&amp;gt;&lt;/em&gt;, the function &lt;em&gt;Bind&lt;/em&gt;, and the function &lt;em&gt;Unit&lt;/em&gt; enable function composition with amplified values.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Meet the Monads&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Viola, we have invented monads.&lt;/p&gt;

&lt;p&gt;Monads are a triple consisting of a type, a &lt;em&gt;Unit&lt;/em&gt; function, and a &lt;em&gt;Bind&lt;/em&gt; function.&amp;#160; Furthermore, to be a monad, the triple must satisfy three laws:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;&lt;strong&gt;1.&amp;#160; Left Identity&lt;/strong&gt;&lt;/p&gt;

  &lt;p&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160; Bind(Unit(e), k) = k(e)&lt;/p&gt;

  &lt;p&gt;&lt;strong&gt;2.&amp;#160; Right Identity&lt;/strong&gt;&lt;/p&gt;

  &lt;p&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160; Bind(m, Unit) = m&lt;/p&gt;

  &lt;p&gt;&lt;strong&gt;3.&amp;#160; Associative&lt;/strong&gt;&lt;/p&gt;

  &lt;p&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160; Bind(m, x =&amp;gt; Bind(k(x), y =&amp;gt; h(y)) = Bind(Bind(m, x =&amp;gt; k(x)), y =&amp;gt; h(y))&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;The laws are similar to those of function composition.&amp;#160; This is not a coincidence.&amp;#160; They guarantee that the monad is well behaved and composition works properly.&lt;/p&gt;

&lt;p&gt;To define a particular monad, the writer supplies the triple, thereby specifying the mechanics of the amplified values.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;The Identity Monad&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;The simplest monad is the &lt;em&gt;Identity&lt;/em&gt; monad.&amp;#160; The type represents a wrapper containing a value.&lt;/p&gt;

&lt;blockquote&gt;
  &lt;pre class="code"&gt;&lt;span style="color: blue"&gt;class &lt;/span&gt;&lt;span style="color: #2b91af"&gt;Identity&lt;/span&gt;&amp;lt;T&amp;gt;
{
    &lt;span style="color: blue"&gt;public &lt;/span&gt;T Value { &lt;span style="color: blue"&gt;get&lt;/span&gt;; &lt;span style="color: blue"&gt;private set&lt;/span&gt;; }
    &lt;span style="color: blue"&gt;public &lt;/span&gt;Identity(T value) { &lt;span style="color: blue"&gt;this&lt;/span&gt;.Value = value; }
}&lt;/pre&gt;
&lt;/blockquote&gt;
&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;

&lt;p&gt;The &lt;em&gt;Unit&lt;/em&gt; function takes a value and returns a new instance of &lt;em&gt;Identity&lt;/em&gt;, which wraps the value.&lt;/p&gt;

&lt;blockquote&gt;
  &lt;pre class="code"&gt;&lt;span style="color: blue"&gt;static &lt;/span&gt;&lt;span style="color: #2b91af"&gt;Identity&lt;/span&gt;&amp;lt;T&amp;gt; Unit&amp;lt;T&amp;gt;(T value)
{
    &lt;span style="color: blue"&gt;return new &lt;/span&gt;&lt;span style="color: #2b91af"&gt;Identity&lt;/span&gt;&amp;lt;T&amp;gt;(value);
}&lt;/pre&gt;
&lt;/blockquote&gt;
&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;

&lt;p&gt;The bind function takes an instance of &lt;em&gt;Identity&lt;/em&gt;, unwraps the value, and invokes the delegate, &lt;em&gt;k&lt;/em&gt;, with the&lt;em&gt; &lt;/em&gt;unwrapped value.&amp;#160; The result is a new instance of &lt;em&gt;Identity&lt;/em&gt;. &lt;/p&gt;

&lt;blockquote&gt;
  &lt;pre class="code"&gt;&lt;span style="color: blue"&gt;static &lt;/span&gt;&lt;span style="color: #2b91af"&gt;Identity&lt;/span&gt;&amp;lt;U&amp;gt; Bind&amp;lt;T,U&amp;gt;(&lt;span style="color: #2b91af"&gt;Identity&lt;/span&gt;&amp;lt;T&amp;gt; id, &lt;span style="color: #2b91af"&gt;Func&lt;/span&gt;&amp;lt;T,&lt;span style="color: #2b91af"&gt;Identity&lt;/span&gt;&amp;lt;U&amp;gt;&amp;gt; k)
{
    &lt;span style="color: blue"&gt;return &lt;/span&gt;k(id.Value);
}&lt;/pre&gt;
&lt;/blockquote&gt;
&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;

&lt;p&gt;Consider a simple program that creates two &lt;em&gt;Identity &lt;/em&gt;wrappers and performs an operation on the wrapped values.&amp;#160; First, bind &lt;em&gt;x&lt;/em&gt; to the value within the wrapper containing the value five.&amp;#160; Then, bind &lt;em&gt;y &lt;/em&gt;to the value within the wrapper containing the value six.&amp;#160; Finally, add the values,&lt;em&gt; x&lt;/em&gt; and &lt;em&gt;y,&lt;/em&gt; together.&amp;#160; The result is an instance of &lt;em&gt;Identity&lt;/em&gt; wrapping the value eleven.&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;&lt;font face="Courier New"&gt;&lt;span style="color: blue"&gt;var &lt;/span&gt;r = Bind(Unit(5), x =&amp;gt; 

      &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; Bind(Unit(6), y =&amp;gt; 

      &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; Unit(x + y))); 

      &lt;br /&gt;

      &lt;br /&gt;&lt;span style="color: #2b91af"&gt;Console&lt;/span&gt;.WriteLine(r.Value);&lt;/font&gt;&lt;/p&gt;
&lt;/blockquote&gt;
&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;

&lt;p&gt;While this works, it is rather clumsy.&amp;#160; It would be nice to have syntax for dealing with the monad.&amp;#160; Fortunately, we do.&lt;/p&gt;

&lt;p&gt;C# 3.0 introduced query comprehensions which are actually monad comprehensions in disguise.&amp;#160; We can rewrite the identity monad to use LINQ.&amp;#160; Perhaps, it should have been called LINM (Language INtegrated Monads), but it just doesn't have the same ring to it.&lt;/p&gt;

&lt;p&gt;Rename the method &lt;em&gt;Unit&lt;/em&gt; to &lt;em&gt;ToIdentity &lt;/em&gt;and &lt;em&gt;Bind&lt;/em&gt; to &lt;em&gt;SelectMany&lt;/em&gt;.&amp;#160; Then, make them both extension methods.&lt;/p&gt;

&lt;blockquote&gt;
  &lt;pre class="code"&gt;&lt;span style="color: blue"&gt;public static &lt;/span&gt;&lt;span style="color: #2b91af"&gt;Identity&lt;/span&gt;&amp;lt;T&amp;gt; ToIdentity&amp;lt;T&amp;gt;(&lt;span style="color: blue"&gt;this &lt;/span&gt;T value)
{
    &lt;span style="color: blue"&gt;return new &lt;/span&gt;&lt;span style="color: #2b91af"&gt;Identity&lt;/span&gt;&amp;lt;T&amp;gt;(value);
}

&lt;span style="color: blue"&gt;public static &lt;/span&gt;&lt;span style="color: #2b91af"&gt;Identity&lt;/span&gt;&amp;lt;U&amp;gt; SelectMany&amp;lt;T, U&amp;gt;(&lt;span style="color: blue"&gt;this &lt;/span&gt;&lt;span style="color: #2b91af"&gt;Identity&lt;/span&gt;&amp;lt;T&amp;gt; id, &lt;span style="color: #2b91af"&gt;Func&lt;/span&gt;&amp;lt;T, &lt;span style="color: #2b91af"&gt;Identity&lt;/span&gt;&amp;lt;U&amp;gt;&amp;gt; k)
{
    &lt;span style="color: blue"&gt;return &lt;/span&gt;k(id.Value);
}&lt;/pre&gt;
&lt;/blockquote&gt;
&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;

&lt;p&gt;The changes impact the calling code.&lt;/p&gt;

&lt;blockquote&gt;
  &lt;pre class="code"&gt;&lt;span style="color: blue"&gt;var &lt;/span&gt;r = 5.ToIdentity().SelectMany(
            x =&amp;gt; 6.ToIdentity().SelectMany(
                y =&amp;gt; (x + y).ToIdentity()));

&lt;span style="color: #2b91af"&gt;Console&lt;/span&gt;.WriteLine(r.Value);&lt;/pre&gt;
&lt;/blockquote&gt;
&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;

&lt;p&gt;Equivalent methods are part of the standard query operators defined for LINQ.&amp;#160; However, the standard query operators also include a slightly different version of &lt;em&gt;SelectMany&lt;/em&gt; for performance reasons.&amp;#160; It combines &lt;em&gt;Bind&lt;/em&gt; with &lt;em&gt;Unit&lt;/em&gt;, so that lambdas are not deeply nested.&amp;#160; The signature is the same except for an extra argument that is a delegate which takes two arguments and returns a value.&amp;#160; The delegate combines the two values together.&amp;#160; This version of &lt;em&gt;SelectMany&lt;/em&gt; binds &lt;em&gt;x &lt;/em&gt;to the wrapped value, applies &lt;em&gt;k&lt;/em&gt; to &lt;em&gt;x&lt;/em&gt;, binds the result to &lt;em&gt;y&lt;/em&gt;, and then applies the combining function, &lt;em&gt;s,&lt;/em&gt; to &lt;em&gt;x&lt;/em&gt; and &lt;em&gt;y.&amp;#160; &lt;/em&gt;The resultant value is wrapped and returned.&lt;/p&gt;

&lt;blockquote&gt;
  &lt;pre class="code"&gt;&lt;span style="color: blue"&gt;public static &lt;/span&gt;&lt;span style="color: #2b91af"&gt;Identity&lt;/span&gt;&amp;lt;V&amp;gt; SelectMany&amp;lt;T, U, V&amp;gt;(&lt;span style="color: blue"&gt;this &lt;/span&gt;&lt;span style="color: #2b91af"&gt;Identity&lt;/span&gt;&amp;lt;T&amp;gt; id, &lt;span style="color: #2b91af"&gt;Func&lt;/span&gt;&amp;lt;T, &lt;span style="color: #2b91af"&gt;Identity&lt;/span&gt;&amp;lt;U&amp;gt;&amp;gt; k, &lt;span style="color: #2b91af"&gt;Func&lt;/span&gt;&amp;lt;T,U,V&amp;gt; s)
{
    &lt;span style="color: blue"&gt;return &lt;/span&gt;id.SelectMany(x =&amp;gt; k(x).SelectMany(y =&amp;gt; s(x, y).ToIdentity()));
}&lt;/pre&gt;
  &lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;&lt;/blockquote&gt;
&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;

&lt;p&gt;Of course, we can remove some of the code from the generalized solution by using our knowledge of the &lt;em&gt;Identity&lt;/em&gt; monad.&lt;/p&gt;

&lt;blockquote&gt;
  &lt;pre class="code"&gt;&lt;span style="color: blue"&gt;public static &lt;/span&gt;&lt;span style="color: #2b91af"&gt;Identity&lt;/span&gt;&amp;lt;V&amp;gt; SelectMany&amp;lt;T, U, V&amp;gt;(&lt;span style="color: blue"&gt;this &lt;/span&gt;&lt;span style="color: #2b91af"&gt;Identity&lt;/span&gt;&amp;lt;T&amp;gt; id, &lt;span style="color: #2b91af"&gt;Func&lt;/span&gt;&amp;lt;T, &lt;span style="color: #2b91af"&gt;Identity&lt;/span&gt;&amp;lt;U&amp;gt;&amp;gt; k, &lt;span style="color: #2b91af"&gt;Func&lt;/span&gt;&amp;lt;T,U,V&amp;gt; s)
{
    &lt;span style="color: blue"&gt;return &lt;/span&gt;s(id.Value, k(id.Value).Value).ToIdentity();
}&lt;/pre&gt;
&lt;/blockquote&gt;
&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;

&lt;p&gt;The call-site does not need to nest lambdas.&lt;/p&gt;

&lt;blockquote&gt;
  &lt;pre class="code"&gt;&lt;span style="color: blue"&gt;var &lt;/span&gt;r = 5.ToIdentity()
         .SelectMany(x =&amp;gt; 6.ToIdentity(), (x, y) =&amp;gt; x + y);

&lt;span style="color: #2b91af"&gt;Console&lt;/span&gt;.WriteLine(r.Value);&lt;/pre&gt;
&lt;/blockquote&gt;
&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;

&lt;p&gt;With the new definition of &lt;em&gt;SelectMany&lt;/em&gt;, programmers can use C#'s query comprehension syntax.&amp;#160; The &lt;em&gt;from &lt;/em&gt;notation binds the introduced variable to the value wrapped by the expression on the right.&amp;#160; This allows subsequent expressions to use the wrapped values without directly calling &lt;em&gt;SelectMany&lt;/em&gt;.&lt;/p&gt;

&lt;blockquote&gt;
  &lt;pre class="code"&gt;&lt;span style="color: blue"&gt;var &lt;/span&gt;r = &lt;span style="color: blue"&gt;from &lt;/span&gt;x &lt;span style="color: blue"&gt;in &lt;/span&gt;5.ToIdentity()
        &lt;span style="color: blue"&gt;from &lt;/span&gt;y &lt;span style="color: blue"&gt;in &lt;/span&gt;6.ToIdentity()
        &lt;span style="color: blue"&gt;select &lt;/span&gt;x + y;&lt;/pre&gt;
&lt;/blockquote&gt;
&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;

&lt;p&gt;Since the original &lt;em&gt;SelectMany&lt;/em&gt; definition corresponds directly to the monadic &lt;em&gt;Bind&lt;/em&gt; function and because the existence of a generalized transformation has been demonstrated, the remainder of the post will use the original signature.&amp;#160; But, keep in mind that the second definition is the one used by the query syntax.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;The Maybe Monad&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;The &lt;em&gt;Identity&lt;/em&gt; monad is an example of a monadic container type where the &lt;em&gt;Identity&lt;/em&gt; monad wrapped a value.&amp;#160; If we change the definition to contain either a value or a missing value then we have the &lt;em&gt;Maybe&lt;/em&gt; monad.&lt;/p&gt;

&lt;p&gt;Again, we need a type definition.&amp;#160; The &lt;em&gt;Maybe&lt;/em&gt; type is similar to the &lt;em&gt;Identity&lt;/em&gt; type but adds a property denoting whether a value is missing.&amp;#160; It also has a predefined instance, &lt;em&gt;Nothing&lt;/em&gt;, representing all instances lacking a value.&lt;/p&gt;

&lt;blockquote&gt;
  &lt;pre class="code"&gt;&lt;span style="color: blue"&gt;class &lt;/span&gt;&lt;span style="color: #2b91af"&gt;Maybe&lt;/span&gt;&amp;lt;T&amp;gt;
{
    &lt;span style="color: blue"&gt;public readonly static &lt;/span&gt;&lt;span style="color: #2b91af"&gt;Maybe&lt;/span&gt;&amp;lt;T&amp;gt; Nothing = &lt;span style="color: blue"&gt;new &lt;/span&gt;&lt;span style="color: #2b91af"&gt;Maybe&lt;/span&gt;&amp;lt;T&amp;gt;();
    &lt;span style="color: blue"&gt;public &lt;/span&gt;T Value { &lt;span style="color: blue"&gt;get&lt;/span&gt;; &lt;span style="color: blue"&gt;private set&lt;/span&gt;; }
    &lt;span style="color: blue"&gt;public bool &lt;/span&gt;HasValue { &lt;span style="color: blue"&gt;get&lt;/span&gt;; &lt;span style="color: blue"&gt;private set&lt;/span&gt;; }
    Maybe()
    {
        HasValue = &lt;span style="color: blue"&gt;false&lt;/span&gt;;
    }
    &lt;span style="color: blue"&gt;public &lt;/span&gt;Maybe(T value)
    {
        Value = value;
        HasValue = &lt;span style="color: blue"&gt;true&lt;/span&gt;;
    }
}&lt;/pre&gt;
&lt;/blockquote&gt;

&lt;p&gt;The &lt;em&gt;Unit&lt;/em&gt; function takes a value and constructs a &lt;em&gt;Maybe&lt;/em&gt; instance, which wraps the value.&lt;/p&gt;

&lt;blockquote&gt;
  &lt;pre class="code"&gt;&lt;span style="color: blue"&gt;public static &lt;/span&gt;&lt;span style="color: #2b91af"&gt;Maybe&lt;/span&gt;&amp;lt;T&amp;gt; ToMaybe&amp;lt;T&amp;gt;(&lt;span style="color: blue"&gt;this &lt;/span&gt;T value)
{
    &lt;span style="color: blue"&gt;return new &lt;/span&gt;&lt;span style="color: #2b91af"&gt;Maybe&lt;/span&gt;&amp;lt;T&amp;gt;(value);
}&lt;/pre&gt;
&lt;/blockquote&gt;
&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;

&lt;p&gt;The &lt;em&gt;Bind&lt;/em&gt; function takes a &lt;em&gt;Maybe&lt;/em&gt; instance and if there is a value then it applies the delegate to the contained value.&amp;#160; Otherwise, it returns &lt;em&gt;Nothing&lt;/em&gt;.&lt;/p&gt;

&lt;blockquote&gt;
  &lt;pre class="code"&gt;&lt;span style="color: blue"&gt;public static &lt;/span&gt;&lt;span style="color: #2b91af"&gt;Maybe&lt;/span&gt;&amp;lt;U&amp;gt; SelectMany&amp;lt;T, U&amp;gt;(&lt;span style="color: blue"&gt;this &lt;/span&gt;&lt;span style="color: #2b91af"&gt;Maybe&lt;/span&gt;&amp;lt;T&amp;gt; m, &lt;span style="color: #2b91af"&gt;Func&lt;/span&gt;&amp;lt;T, &lt;span style="color: #2b91af"&gt;Maybe&lt;/span&gt;&amp;lt;U&amp;gt;&amp;gt; k)
{
    &lt;span style="color: blue"&gt;if &lt;/span&gt;(!m.HasValue)
        &lt;span style="color: blue"&gt;return &lt;/span&gt;&lt;span style="color: #2b91af"&gt;Maybe&lt;/span&gt;&amp;lt;U&amp;gt;.Nothing;
    &lt;span style="color: blue"&gt;return &lt;/span&gt;k(m.Value);
}&lt;/pre&gt;
&lt;/blockquote&gt;
&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;

&lt;p&gt;The programmer can use the comprehension syntax to work with the &lt;em&gt;Maybe&lt;/em&gt; monad.&amp;#160; For example, create an instance of &lt;em&gt;Maybe&lt;/em&gt; containing the value five and add it to &lt;em&gt;Nothing&lt;/em&gt;.&lt;/p&gt;

&lt;blockquote&gt;
  &lt;pre class="code"&gt;&lt;span style="color: blue"&gt;var &lt;/span&gt;r = &lt;span style="color: blue"&gt;from &lt;/span&gt;x &lt;span style="color: blue"&gt;in &lt;/span&gt;5.ToMaybe()
        &lt;span style="color: blue"&gt;from &lt;/span&gt;y &lt;span style="color: blue"&gt;in &lt;/span&gt;&lt;span style="color: #2b91af"&gt;Maybe&lt;/span&gt;&amp;lt;&lt;span style="color: blue"&gt;int&lt;/span&gt;&amp;gt;.Nothing
        &lt;span style="color: blue"&gt;select &lt;/span&gt;x + y;

&lt;span style="color: #2b91af"&gt;Console&lt;/span&gt;.WriteLine(r.HasValue ? r.Value.ToString() : &lt;span style="color: #a31515"&gt;&amp;quot;Nothing&amp;quot;&lt;/span&gt;);&lt;/pre&gt;
&lt;/blockquote&gt;
&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;

&lt;p&gt;The result is &amp;quot;Nothing&amp;quot;.&amp;#160; We have implemented the null propagation of nullables without explicit language support.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;The List Monad&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Another important container type is the list type.&amp;#160; In fact, the list monad is at the heart of LINQ.&amp;#160; The type &lt;em&gt;IEnumerable&amp;lt;T&amp;gt; &lt;/em&gt;denotes a lazily computed list.&lt;/p&gt;

&lt;p&gt;The &lt;em&gt;Unit&lt;/em&gt; function takes a value and returns a list, which contains only that value.&lt;/p&gt;

&lt;blockquote&gt;
  &lt;pre class="code"&gt;&lt;span style="color: blue"&gt;public static &lt;/span&gt;&lt;span style="color: #2b91af"&gt;IEnumerable&lt;/span&gt;&amp;lt;T&amp;gt; ToList&amp;lt;T&amp;gt;(&lt;span style="color: blue"&gt;this &lt;/span&gt;T value)
{
    &lt;span style="color: blue"&gt;yield return &lt;/span&gt;value;
}&lt;/pre&gt;
&lt;/blockquote&gt;
&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;

&lt;p&gt;The &lt;em&gt;Bind&lt;/em&gt; function takes an &lt;em&gt;IEnumerable&amp;lt;T&amp;gt;&lt;/em&gt;, a delegate, which takes a &lt;em&gt;T&lt;/em&gt; and returns an &lt;em&gt;IEnumerable&amp;lt;U&amp;gt;&lt;/em&gt;, and returns an &lt;em&gt;IEnumerable&amp;lt;U&amp;gt;&lt;/em&gt;.&lt;/p&gt;

&lt;blockquote&gt;
  &lt;pre class="code"&gt;&lt;span style="color: blue"&gt;public static &lt;/span&gt;&lt;span style="color: #2b91af"&gt;IEnumerable&lt;/span&gt;&amp;lt;U&amp;gt; SelectMany&amp;lt;T, U&amp;gt;(&lt;span style="color: blue"&gt;this &lt;/span&gt;&lt;span style="color: #2b91af"&gt;IEnumerable&lt;/span&gt;&amp;lt;T&amp;gt; m, &lt;span style="color: #2b91af"&gt;Func&lt;/span&gt;&amp;lt;T, &lt;span style="color: #2b91af"&gt;IEnumerable&lt;/span&gt;&amp;lt;U&amp;gt;&amp;gt; k)
{
    &lt;span style="color: blue"&gt;foreach &lt;/span&gt;(&lt;span style="color: blue"&gt;var &lt;/span&gt;x &lt;span style="color: blue"&gt;in &lt;/span&gt;m)
        &lt;span style="color: blue"&gt;foreach &lt;/span&gt;(&lt;span style="color: blue"&gt;var &lt;/span&gt;y &lt;span style="color: blue"&gt;in &lt;/span&gt;k(x))
            &lt;span style="color: blue"&gt;yield return &lt;/span&gt;y;
}&lt;/pre&gt;
&lt;/blockquote&gt;
&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;

&lt;p&gt;Now, the programmer can write the familiar query expressions with &lt;em&gt;IEnumerable&amp;lt;T&amp;gt;.&lt;/em&gt;&lt;/p&gt;

&lt;blockquote&gt;
  &lt;pre class="code"&gt;&lt;span style="color: blue"&gt;var &lt;/span&gt;r = &lt;span style="color: blue"&gt;from &lt;/span&gt;x &lt;span style="color: blue"&gt;in new&lt;/span&gt;[] { 0, 1, 2 }
        &lt;span style="color: blue"&gt;from &lt;/span&gt;y &lt;span style="color: blue"&gt;in new&lt;/span&gt;[] { 0, 1, 2 }
        &lt;span style="color: blue"&gt;select &lt;/span&gt;x + y;

&lt;span style="color: blue"&gt;foreach &lt;/span&gt;(&lt;span style="color: blue"&gt;var &lt;/span&gt;i &lt;span style="color: blue"&gt;in &lt;/span&gt;r)
    &lt;span style="color: #2b91af"&gt;Console&lt;/span&gt;.WriteLine(i);&lt;/pre&gt;
&lt;/blockquote&gt;
&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;

&lt;p&gt;Remember that it is the monad that enables the magic.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;The Continuation Monad&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;The continuation monad answers &lt;a href="http://blogs.msdn.com/wesdyer/archive/2007/12/22/continuation-passing-style.aspx"&gt;the question that was posed at the end of the last post&lt;/a&gt;: how can a programmer write CPS code in a more palatable way?&lt;/p&gt;

&lt;p&gt;The type of the continuation monad, &lt;em&gt;K&lt;/em&gt;, is a delegate which when given a continuation, which takes an argument and returns an answer, will return an answer.&lt;/p&gt;

&lt;blockquote&gt;
  &lt;pre class="code"&gt;&lt;span style="color: blue"&gt;delegate &lt;/span&gt;Answer &lt;span style="color: #2b91af"&gt;K&lt;/span&gt;&amp;lt;T,Answer&amp;gt;(&lt;span style="color: #2b91af"&gt;Func&lt;/span&gt;&amp;lt;T,Answer&amp;gt; k);&lt;/pre&gt;
&lt;/blockquote&gt;

&lt;p&gt;The type &lt;em&gt;K&lt;/em&gt; fundamentally differs from types &lt;em&gt;Identity&amp;lt;T&amp;gt;&lt;/em&gt;, &lt;em&gt;Maybe&amp;lt;T&amp;gt;&lt;/em&gt;, and &lt;em&gt;IEnumerable&amp;lt;T&amp;gt;&lt;/em&gt;.&amp;#160; All the other monads represent container types and allow computations to be specified in terms of the values rather than the containers, but the continuation monad contains nothing.&amp;#160; Rather, it composes together continuations the user writes.&lt;/p&gt;

&lt;p&gt;To be a monad, there must be a &lt;em&gt;Unit&lt;/em&gt; function which takes a &lt;em&gt;T &lt;/em&gt;and returns a &lt;em&gt;K&amp;lt;T&lt;/em&gt;,&lt;em&gt;Answer&amp;gt;&lt;/em&gt; for some answer type.&lt;/p&gt;

&lt;blockquote&gt;
  &lt;pre class="code"&gt;&lt;span style="color: blue"&gt;public static &lt;/span&gt;&lt;span style="color: #2b91af"&gt;K&lt;/span&gt;&amp;lt;T, Answer&amp;gt; ToContinuation&amp;lt;T, Answer&amp;gt;(&lt;span style="color: blue"&gt;this &lt;/span&gt;T value)&lt;/pre&gt;
&lt;/blockquote&gt;
&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;

&lt;p&gt;What should it do?&amp;#160; When in doubt, look to the types.&amp;#160;&amp;#160; The method takes a &lt;em&gt;T&lt;/em&gt; and returns a function, which takes a function from &lt;em&gt;T&lt;/em&gt; to &lt;em&gt;Answer&lt;/em&gt;, and returns an &lt;em&gt;Answer&lt;/em&gt;.&amp;#160; Therefore, the method must return a function and the only argument of that function must be a function from &lt;em&gt;T&lt;/em&gt; to &lt;em&gt;Answer&lt;/em&gt;.&amp;#160; Call the argument &lt;em&gt;c&lt;/em&gt;.&lt;/p&gt;

&lt;blockquote&gt;
  &lt;pre class="code"&gt;&lt;span style="color: blue"&gt;return &lt;/span&gt;(&lt;span style="color: #2b91af"&gt;Func&lt;/span&gt;&amp;lt;T, Answer&amp;gt; c) =&amp;gt; ...&lt;/pre&gt;
&lt;/blockquote&gt;
&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;

&lt;p&gt;The body of the lambda must return a value of type &lt;em&gt;Answer&lt;/em&gt;.&amp;#160; Values of type &lt;em&gt;Func&amp;lt;T,Answer&amp;gt;&lt;/em&gt; and a &lt;em&gt;T&lt;/em&gt; are&lt;em&gt;&amp;#160;&lt;/em&gt;available.&amp;#160; Apply &lt;em&gt;c&lt;/em&gt; to &lt;em&gt;value&lt;/em&gt; and the result is of type &lt;em&gt;Answer.&lt;/em&gt;&lt;/p&gt;

&lt;blockquote&gt;
  &lt;pre class="code"&gt;&lt;span style="color: blue"&gt;return &lt;/span&gt;(&lt;span style="color: #2b91af"&gt;Func&lt;/span&gt;&amp;lt;T, Answer&amp;gt; c) =&amp;gt; c(value);&lt;/pre&gt;
&lt;/blockquote&gt;
&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;

&lt;p&gt;To be a monad, &lt;em&gt;Bind&lt;/em&gt; must take a &lt;em&gt;K&amp;lt;T,Answer&amp;gt;&lt;/em&gt; and a function from &lt;em&gt;T &lt;/em&gt;to &lt;em&gt;K&amp;lt;U, Answer&amp;gt;&lt;/em&gt; and return a &lt;em&gt;K&amp;lt;U, Answer&amp;gt;&lt;/em&gt;.&lt;/p&gt;

&lt;blockquote&gt;
  &lt;pre class="code"&gt;&lt;span style="color: blue"&gt;public static &lt;/span&gt;&lt;span style="color: #2b91af"&gt;K&lt;/span&gt;&amp;lt;U, Answer&amp;gt; SelectMany&amp;lt;T, U, Answer&amp;gt;(&lt;span style="color: blue"&gt;this &lt;/span&gt;&lt;span style="color: #2b91af"&gt;K&lt;/span&gt;&amp;lt;T, Answer&amp;gt; m, &lt;span style="color: #2b91af"&gt;Func&lt;/span&gt;&amp;lt;T, &lt;span style="color: #2b91af"&gt;K&lt;/span&gt;&amp;lt;U, Answer&amp;gt;&amp;gt; k)&lt;/pre&gt;
&lt;/blockquote&gt;
&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;

&lt;p&gt;But what about the body?&amp;#160; The result must be of type &lt;em&gt;K&amp;lt;U, Answer&amp;gt;&lt;/em&gt;, but how is a result of the correct type formed?&lt;/p&gt;

&lt;p&gt;Expand &lt;em&gt;K&lt;/em&gt;'s definition to gain some insight.&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;&lt;strong&gt;return type&lt;/strong&gt;&lt;/p&gt;

  &lt;p&gt;&lt;strong&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;/strong&gt;&lt;font face="Courier New"&gt;&lt;span style="color: blue"&gt;&lt;font color="#008080"&gt;Func&lt;/font&gt;&lt;/span&gt;&amp;lt;&lt;font color="#008080"&gt;Func&lt;/font&gt;&amp;lt;U, Answer&amp;gt;, Answer&amp;gt;&lt;/font&gt;&lt;/p&gt;

  &lt;p&gt;&lt;strong&gt;&lt;em&gt;m&lt;/em&gt;'s type&lt;/strong&gt;&lt;/p&gt;

  &lt;p&gt;&lt;strong&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;/strong&gt;&lt;font face="Courier New"&gt;&lt;span style="color: blue"&gt;&lt;font color="#008080"&gt;Func&lt;/font&gt;&lt;/span&gt;&amp;lt;&lt;font color="#008080"&gt;Func&lt;/font&gt;&amp;lt;T, Answer&amp;gt;, Answer&amp;gt;&lt;/font&gt;&lt;/p&gt;

  &lt;p&gt;&lt;strong&gt;&lt;em&gt;k&lt;/em&gt;'s type&lt;/strong&gt;&lt;/p&gt;

  &lt;p&gt;&lt;strong&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160; &lt;/strong&gt;&lt;font face="Courier New"&gt;&lt;span style="color: #2b91af"&gt;Func&lt;/span&gt;&amp;lt;T, &lt;font color="#2b91af"&gt;Func&lt;/font&gt;&amp;lt;&lt;font color="#008080"&gt;Func&lt;/font&gt;&amp;lt;U, Answer&amp;gt;, Answer&amp;gt;&amp;gt;&lt;/font&gt;&lt;/p&gt;
&lt;/blockquote&gt;
&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;

&lt;p&gt;Applying &lt;em&gt;k&lt;/em&gt; to a value of type &lt;em&gt;T&lt;/em&gt; results in a value of type &lt;em&gt;K&amp;lt;U,Answer&amp;gt;&lt;/em&gt;, but no value of type &lt;em&gt;T&lt;/em&gt; is available.&amp;#160; Build the return type directly by constructing a function, which takes a function from &lt;em&gt;U&lt;/em&gt; to &lt;em&gt;Answer&lt;/em&gt;.&amp;#160; Call the parameter &lt;em&gt;c&lt;/em&gt;.&lt;/p&gt;

&lt;blockquote&gt;
  &lt;pre class="code"&gt;&lt;span style="color: blue"&gt;return &lt;/span&gt;(&lt;span style="color: #2b91af"&gt;Func&lt;/span&gt;&amp;lt;U,Answer&amp;gt; c) =&amp;gt; ...&lt;/pre&gt;
&lt;/blockquote&gt;
&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;

&lt;p&gt;The body must be type of &lt;em&gt;Answer &lt;/em&gt;so that the return type of &lt;em&gt;Bind&lt;/em&gt; is &lt;em&gt;K&amp;lt;U,Answer&amp;gt;&lt;/em&gt;.&amp;#160; Perhaps, &lt;em&gt;m&lt;/em&gt; could be applied to a function from &lt;em&gt;T&lt;/em&gt; to &lt;em&gt;Answer&lt;/em&gt;.&amp;#160; The result is a value of type &lt;em&gt;Answer&lt;/em&gt;.&lt;/p&gt;

&lt;blockquote&gt;
  &lt;pre class="code"&gt;&lt;span style="color: blue"&gt;return &lt;/span&gt;(&lt;span style="color: #2b91af"&gt;Func&lt;/span&gt;&amp;lt;U,Answer&amp;gt; c) =&amp;gt; m(...)&lt;/pre&gt;
&lt;/blockquote&gt;
&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;

&lt;p&gt;The expression inside the invocation of &lt;em&gt;m&lt;/em&gt; must be of type &lt;em&gt;Func&amp;lt;T,Answer&amp;gt;&lt;/em&gt;.&amp;#160; Since there is nothing of that type, construct the function by creating a lambda with one parameter, &lt;em&gt;x&lt;/em&gt;, of type &lt;em&gt;T.&lt;/em&gt;&lt;/p&gt;

&lt;blockquote&gt;
  &lt;pre class="code"&gt;&lt;span style="color: blue"&gt;return &lt;/span&gt;(&lt;span style="color: #2b91af"&gt;Func&lt;/span&gt;&amp;lt;U,Answer&amp;gt; c) =&amp;gt; m((T x) =&amp;gt; ...)&lt;/pre&gt;
&lt;/blockquote&gt;
&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;

&lt;p&gt;The body of this lambda must be of type &lt;em&gt;Answer&lt;/em&gt;.&amp;#160; Values of type &lt;em&gt;T, &lt;/em&gt;&lt;em&gt;Func&amp;lt;U,Answer&amp;gt;, &lt;/em&gt;and &lt;em&gt;Func&amp;lt;T,Func&amp;lt;Func&amp;lt;U,Answer&amp;gt;, Answer&amp;gt;&amp;gt;&lt;/em&gt; haven't been used yet.&amp;#160; Apply &lt;em&gt;k&lt;/em&gt; to &lt;em&gt;x&lt;/em&gt;.&lt;/p&gt;

&lt;blockquote&gt;
  &lt;pre class="code"&gt;&lt;span style="color: blue"&gt;return &lt;/span&gt;(&lt;span style="color: #2b91af"&gt;Func&lt;/span&gt;&amp;lt;U,Answer&amp;gt; c) =&amp;gt; m((T x) =&amp;gt; k(x)...)&lt;/pre&gt;
&lt;/blockquote&gt;
&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;

&lt;p&gt;The result is a value of type &lt;em&gt;Func&amp;lt;Func&amp;lt;U,Answer&amp;gt;,Answer&amp;gt;&lt;/em&gt;.&amp;#160; Apply the result to &lt;em&gt;c&lt;/em&gt;.&lt;/p&gt;

&lt;blockquote&gt;
  &lt;pre class="code"&gt;&lt;span style="color: blue"&gt;return &lt;/span&gt;(&lt;span style="color: #2b91af"&gt;Func&lt;/span&gt;&amp;lt;U,Answer&amp;gt; c) =&amp;gt; m((T x) =&amp;gt; k(x)(c));&lt;/pre&gt;
&lt;/blockquote&gt;
&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;

&lt;p&gt;The continuation monad turns the computation inside out.&amp;#160; The comprehension syntax can be used to construct continuations.&lt;/p&gt;

&lt;p&gt;Construct a computation, which invokes a continuation with the value seven.&amp;#160; Pass this computation to another computation, which invokes a continuation with the value six.&amp;#160;&amp;#160; Pass this computation to another computation, which invokes a continuation with the result of adding the results of the first two continuations together.&amp;#160; Finally, pass a continuation, which replaces &amp;quot;1&amp;quot;s with &amp;quot;a&amp;quot;s, to the result.&lt;/p&gt;

&lt;blockquote&gt;
  &lt;pre class="code"&gt;&lt;span style="color: blue"&gt;var &lt;/span&gt;r = &lt;span style="color: blue"&gt;from &lt;/span&gt;x &lt;span style="color: blue"&gt;in &lt;/span&gt;7.ToContinuation&amp;lt;&lt;span style="color: blue"&gt;int&lt;/span&gt;,&lt;span style="color: blue"&gt;string&lt;/span&gt;&amp;gt;()
        &lt;span style="color: blue"&gt;from &lt;/span&gt;y &lt;span style="color: blue"&gt;in &lt;/span&gt;6.ToContinuation&amp;lt;&lt;span style="color: blue"&gt;int&lt;/span&gt;,&lt;span style="color: blue"&gt;string&lt;/span&gt;&amp;gt;()
        &lt;span style="color: blue"&gt;select &lt;/span&gt;x + y;

&lt;span style="color: #2b91af"&gt;Console&lt;/span&gt;.WriteLine(r(z =&amp;gt; z.ToString().Replace(&lt;span style="color: #a31515"&gt;'1'&lt;/span&gt;, &lt;span style="color: #a31515"&gt;'a'&lt;/span&gt;))); &lt;font color="#008000"&gt;// displays a3&lt;/font&gt;&lt;/pre&gt;
&lt;/blockquote&gt;

&lt;p&gt;The continuation monad does the heavy-lifting of constructing the continuations.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Monadic Magic&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Beautiful composition of amplified values requires monads.&amp;#160; The &lt;em&gt;Identity&lt;/em&gt;, &lt;em&gt;Maybe&lt;/em&gt;, and &lt;em&gt;IEnumerable&lt;/em&gt; monads demonstrate the power of monads as container types.&amp;#160; The continuation monad, &lt;em&gt;K&lt;/em&gt;, shows how monads can readily express complex computation.&lt;/p&gt;

&lt;p&gt;Stay tuned for more with monads.&amp;#160; Until then, see what monads can do for you.&lt;/p&gt;&lt;img src="http://blogs.msdn.com/aggbug.aspx?PostID=7064392" width="1" height="1"&gt;</description><category domain="http://blogs.msdn.com/wesdyer/archive/tags/Functional+Programming/default.aspx">Functional Programming</category><category domain="http://blogs.msdn.com/wesdyer/archive/tags/Theory/default.aspx">Theory</category></item><item><title>Continuation-Passing Style</title><link>http://blogs.msdn.com/wesdyer/archive/2007/12/22/continuation-passing-style.aspx</link><pubDate>Sat, 22 Dec 2007 09:51:58 GMT</pubDate><guid isPermaLink="false">91d46819-8472-40ad-a661-2c78acb4018c:6833509</guid><dc:creator>wesdyer</dc:creator><slash:comments>9</slash:comments><comments>http://blogs.msdn.com/wesdyer/comments/6833509.aspx</comments><wfw:commentRss>http://blogs.msdn.com/wesdyer/commentrss.aspx?PostID=6833509</wfw:commentRss><description>&lt;p&gt;There are some technical words that cause quite a stir even amongst geeks.&amp;#160; When someone says the word &lt;a href="http://en.wikipedia.org/wiki/Continuation"&gt;&amp;quot;continuation&amp;quot;&lt;/a&gt;, people's eyes glaze over and they seek the first opportunity to change the subject.&amp;#160; The stir is caused because most people don't understand what a continuation is or why someone would want to use one.&amp;#160; This is unfortunate, because they really are rather more simple than they sound. &lt;/p&gt;  &lt;p&gt;&lt;strong&gt;Defining Continuations&lt;/strong&gt;&lt;/p&gt;  &lt;p&gt;A continuation represents the remainder of a computation given a point in that computation.&amp;#160; For example, suppose that two methods are defined: &lt;em&gt;M&lt;/em&gt; and &lt;em&gt;Main&lt;/em&gt;.&amp;#160; The method &lt;em&gt;Main&lt;/em&gt; invokes &lt;em&gt;M&lt;/em&gt; and then writes &amp;quot;Done&amp;quot; to the console.&amp;#160; The method &lt;em&gt;M&lt;/em&gt; assigns &lt;em&gt;x &lt;/em&gt;the value five, invokes &lt;em&gt;F&lt;/em&gt;, increments &lt;em&gt;x&lt;/em&gt;, and writes &lt;em&gt;x&lt;/em&gt; to the console.&lt;/p&gt;  &lt;blockquote&gt;   &lt;pre class="code"&gt;&lt;span style="color: blue"&gt;static void &lt;/span&gt;M()
{
    &lt;span style="color: blue"&gt;var &lt;/span&gt;x = 5;
    F();  &lt;span style="color: green"&gt;// &amp;lt;----------- Point in the computation
    &lt;/span&gt;++x;
    &lt;span style="color: #2b91af"&gt;Console&lt;/span&gt;.WriteLine(x);
}

&lt;span style="color: blue"&gt;static void &lt;/span&gt;Main()
{
    M();
    &lt;span style="color: #2b91af"&gt;Console&lt;/span&gt;.WriteLine(&lt;span style="color: #a31515"&gt;&amp;quot;Done&amp;quot;&lt;/span&gt;);
}&lt;/pre&gt;
&lt;/blockquote&gt;
&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;

&lt;p&gt;The continuation of the computation at the invocation of &lt;em&gt;F &lt;/em&gt;is the remainder of the program execution beginning with incrementing &lt;em&gt;x&lt;/em&gt; in the method &lt;em&gt;M&lt;/em&gt;.&amp;#160; In this case, the continuation includes incrementing &lt;em&gt;x&lt;/em&gt;, writing &lt;em&gt;x&lt;/em&gt;, returning to &lt;em&gt;Main&lt;/em&gt;, and writing &amp;quot;Done&amp;quot; to the console.&lt;/p&gt;

&lt;p&gt;Some languages give programmers explicit access to continuations.&amp;#160; For example, Scheme has a function which calls a function passing a function representing the current continuation.&amp;#160; The function is aptly named &lt;a href="http://community.schemewiki.org/?call-with-current-continuation"&gt;call with current continuation&lt;/a&gt; or &lt;em&gt;call/cc&lt;/em&gt;.&amp;#160; If such a function existed in .NET it might return a T given a delegate that returns a T given a delegate from T to T.&lt;/p&gt;

&lt;blockquote&gt;
  &lt;pre class="code"&gt;T CallCC&amp;lt;T&amp;gt;(&lt;span style="color: #2b91af"&gt;Func&lt;/span&gt;&amp;lt;&lt;font color="#2b91af"&gt;Func&lt;/font&gt;&amp;lt;T,T&amp;gt;, T&amp;gt; f)&lt;/pre&gt;
&lt;/blockquote&gt;

&lt;p&gt;Continuations are the functional counterparts of GOTOs both in power and inscrutability.&amp;#160; They can express arbitrary control flow like coroutines and exceptions while bewildering some of the brightest programmers.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Returning Values with Continuations&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;The simplest use of a continuation is to simulate returning out of a function.&amp;#160; Suppose that .NET had the function &lt;em&gt;CallCC&lt;/em&gt;.&amp;#160; If &lt;em&gt;Main&lt;/em&gt; calls a function &lt;em&gt;Foo&lt;/em&gt; passing the value four and if &lt;em&gt;Foo&lt;/em&gt; immediately invokes &lt;em&gt;CallCC&lt;/em&gt; with a lambda that binds &lt;em&gt;Return&lt;/em&gt; to the continuation at the point of the call to &lt;em&gt;CallCC, &lt;/em&gt;then when &lt;em&gt;Return&lt;/em&gt; is invoked inside of the lambda with the value four, computation will immediately jump out of the lambda to the point after &lt;em&gt;CallCC&lt;/em&gt; but before the return with the value four on the stack.&amp;#160; This happens regardless what of occurs after the invocation of &lt;em&gt;Return&lt;/em&gt; inside the lambda.&lt;/p&gt;

&lt;blockquote&gt;
  &lt;pre class="code"&gt;&lt;span style="color: blue"&gt;static int &lt;/span&gt;Foo(&lt;span style="color: blue"&gt;int &lt;/span&gt;n)
{
    &lt;span style="color: blue"&gt;return &lt;/span&gt;CallCC&amp;lt;&lt;span style="color: blue"&gt;int&lt;/span&gt;&amp;gt;(Return =&amp;gt;
        {
            Return(n);
            &lt;span style="color: blue"&gt;return &lt;/span&gt;n + 1;
        });
}

&lt;span style="color: blue"&gt;static void &lt;/span&gt;Main()
{
    Foo(4);
}&lt;/pre&gt;
  &lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;&lt;/blockquote&gt;

&lt;p&gt;The result of running the program is therefore four and not five.&lt;/p&gt;

&lt;p&gt;All of this demonstrates that returning from a function is equivalent to invoking the continuation defined at the function's call-site.&amp;#160; When a function &amp;quot;returns&amp;quot;, it implicitly invokes the continuation of its call-site.&lt;/p&gt;

&lt;p&gt;When people explain continuations, they usually discuss stack frames and instruction pointers.&amp;#160; It is easy to see why.&amp;#160; The implicit invocation of the &amp;quot;return&amp;quot; continuation restores the stack frame at the call-site and sets the instruction pointer to the instruction immediately after the call-site.&amp;#160; This is what invoking a continuation does: restore the appropriate stack frame and set the instruction pointer.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Continuation-Passing Style&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;It is still possible to use continuations if a language does not support a function like &lt;em&gt;call/cc&lt;/em&gt;.&amp;#160; A programmer can explicitly construct the continuation of a computation and pass it directly to a function.&lt;/p&gt;

&lt;p&gt;To illustrate this transformation, suppose that a function, &lt;em&gt;Identity,&lt;/em&gt; is defined that returns the value it is given. &lt;/p&gt;

&lt;blockquote&gt;
  &lt;pre class="code"&gt;&lt;span style="color: blue"&gt;static &lt;/span&gt;T Identity&amp;lt;T&amp;gt;(T value)
{
    &lt;span style="color: blue"&gt;return &lt;/span&gt;value;
}&lt;/pre&gt;
&lt;/blockquote&gt;

&lt;p&gt;The return statement in &lt;em&gt;Identity&lt;/em&gt; implicitly invokes the continuation of the call-site causing computation to leave &lt;em&gt;Identity&lt;/em&gt; and resume at the point immediately after the invocation of &lt;em&gt;Identity&lt;/em&gt; at the call-site.&amp;#160; If &lt;em&gt;Main&lt;/em&gt; contains only a call to &lt;em&gt;WriteLine&lt;/em&gt; passing the result of the call to &lt;em&gt;Identity,&lt;/em&gt; then computation resumes with the call to &lt;em&gt;WriteLine&lt;/em&gt;.&lt;/p&gt;

&lt;blockquote&gt;
  &lt;pre class="code"&gt;&lt;span style="color: blue"&gt;static void &lt;/span&gt;Main()
{
    &lt;span style="color: #2b91af"&gt;Console&lt;/span&gt;.WriteLine(Identity(&lt;span style="color: #a31515"&gt;&amp;quot;foo&amp;quot;&lt;/span&gt;));
}&lt;/pre&gt;
&lt;/blockquote&gt;
&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;

&lt;p&gt;However, instead of implicitly invoking &lt;em&gt;Identity's&lt;/em&gt; continuation, the programmer can pass the continuation to &lt;em&gt;Identity &lt;/em&gt;explicitly.&amp;#160; An extra argument is added to &lt;em&gt;Identity&lt;/em&gt; which is a void-returning delegate with one parameter that is the same type as the return type of the former &lt;em&gt;Identity&lt;/em&gt; function.&lt;/p&gt;

&lt;blockquote&gt;
  &lt;pre class="code"&gt;&lt;span style="color: blue"&gt;static void &lt;/span&gt;Main()
{
    Identity(&lt;span style="color: #a31515"&gt;&amp;quot;foo&amp;quot;&lt;/span&gt;, s =&amp;gt; &lt;span style="color: #2b91af"&gt;Console&lt;/span&gt;.WriteLine(s));
}

&lt;span style="color: blue"&gt;static void &lt;/span&gt;Identity&amp;lt;T&amp;gt;(T value, &lt;span style="color: #2b91af"&gt;Action&lt;/span&gt;&amp;lt;T&amp;gt; k)
{
    k(value);
}&lt;/pre&gt;
&lt;/blockquote&gt;
&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;

&lt;p&gt;At the call-site, the remainder of the computation has moved into the lambda passed to &lt;em&gt;Identity&lt;/em&gt;.&amp;#160; The continuation is explicitly passed.&amp;#160; On the callee's side, the return statement is replaced by the invocation of the continuation parameter, &lt;em&gt;k&lt;/em&gt;, with the return value.&lt;/p&gt;

&lt;p&gt;This pattern is called &lt;a href="http://en.wikipedia.org/wiki/Continuation-passing_style"&gt;continuation-passing style&lt;/a&gt; or CPS.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Converting to CPS&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Now that we know enough to be dangerous, let's see what we can do.&amp;#160; Consider the typical &lt;em&gt;Max&lt;/em&gt; function.&lt;/p&gt;

&lt;blockquote&gt;
  &lt;pre class="code"&gt;&lt;span style="color: blue"&gt;static int &lt;/span&gt;Max(&lt;span style="color: blue"&gt;int &lt;/span&gt;n, &lt;span style="color: blue"&gt;int &lt;/span&gt;m)
{
    &lt;span style="color: blue"&gt;if &lt;/span&gt;(n &amp;gt; m)
        &lt;span style="color: blue"&gt;return &lt;/span&gt;n;
    &lt;span style="color: blue"&gt;else
        return &lt;/span&gt;m;
}&lt;/pre&gt;
&lt;/blockquote&gt;

&lt;p&gt;To convert this function to CPS, follow these steps:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;1.&amp;#160; Change the return type to void&lt;/p&gt;

  &lt;p&gt;2.&amp;#160; Add an extra argument of type &lt;em&gt;Action&amp;lt;T&amp;gt;&lt;/em&gt; where &lt;em&gt;T&lt;/em&gt; is the original return type&lt;/p&gt;

  &lt;p&gt;3.&amp;#160; Replace all return statements with invocations of the new continuation argument passing the expression used in the return statement&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;Applying these steps to the integer version of &lt;em&gt;Max&lt;/em&gt;, the function now returns void, takes an extra parameter, &lt;em&gt;k&lt;/em&gt;, of type &lt;em&gt;Action&amp;lt;int&amp;gt;&lt;/em&gt;, and invokes &lt;em&gt;k&lt;/em&gt; everywhere a return statement appeared.&lt;/p&gt;

&lt;blockquote&gt;
  &lt;pre class="code"&gt;&lt;span style="color: blue"&gt;static void &lt;/span&gt;Max(&lt;span style="color: blue"&gt;int &lt;/span&gt;n, &lt;span style="color: blue"&gt;int &lt;/span&gt;m, &lt;span style="color: #2b91af"&gt;Action&lt;/span&gt;&amp;lt;&lt;span style="color: blue"&gt;int&lt;/span&gt;&amp;gt; k)
{
    &lt;span style="color: blue"&gt;if &lt;/span&gt;(n &amp;gt; m)
        k(n);
    &lt;span style="color: blue"&gt;else
        &lt;/span&gt;k(m);
}&lt;/pre&gt;
&lt;/blockquote&gt;
&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;

&lt;p&gt;To convert the call-site to CPS:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;1.&amp;#160; Remove all of the remaining computation after the call-site&lt;/p&gt;

  &lt;p&gt;2.&amp;#160; Put the remaining computation in the body of the lambda corresponding to the continuation argument&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;For example, suppose the user defined a method &lt;em&gt;Main&lt;/em&gt; which invokes &lt;em&gt;WriteLine&lt;/em&gt; with the result of applying &lt;em&gt;Max&lt;/em&gt; to three and four.&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;&lt;font face="Courier New"&gt;&lt;span style="color: blue"&gt;&lt;font face="Verdana"&gt;&lt;/font&gt;static void &lt;/span&gt;Main()

      &lt;br /&gt;{

      &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; &lt;span style="color: #2b91af"&gt;Console&lt;/span&gt;.WriteLine(Max(3, 4));

      &lt;br /&gt;}&lt;/font&gt;&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;The remaining computation after the invocation of &lt;em&gt;Max &lt;/em&gt;is the call to &lt;em&gt;WriteLine&lt;/em&gt;.&amp;#160; Therefore, the call to &lt;em&gt;WriteLine &lt;/em&gt;is moved into the lambda representing the continuation passed to &lt;em&gt;Max&lt;/em&gt;.&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;&lt;font face="Courier New"&gt;&lt;span style="color: blue"&gt;static void &lt;/span&gt;Main()

      &lt;br /&gt;{

      &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; Max(3, 4, x =&amp;gt; &lt;span style="color: #2b91af"&gt;Console&lt;/span&gt;.WriteLine(x));

      &lt;br /&gt;}&lt;/font&gt;&lt;/p&gt;
&lt;/blockquote&gt;
&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;

&lt;p&gt;The steps for converting the call-site skirted the issue of what to do with return statements in the continuation.&amp;#160; For example, suppose there are three methods &lt;em&gt;Main&lt;/em&gt;, &lt;em&gt;F&lt;/em&gt;, and &lt;em&gt;G&lt;/em&gt; where &lt;em&gt;Main &lt;/em&gt;calls &lt;em&gt;F&lt;/em&gt; and &lt;em&gt;F&lt;/em&gt; calls &lt;em&gt;G.&amp;#160; &lt;/em&gt;To convert &lt;em&gt;F&lt;/em&gt; and &lt;em&gt;G &lt;/em&gt;to CPS, follow the same transformation steps as with &lt;em&gt;Max&lt;/em&gt;.&lt;/p&gt;

&lt;blockquote&gt;
  &lt;pre class="code"&gt;&lt;span style="color: blue"&gt;static void &lt;/span&gt;Main()
{
    &lt;span style="color: #2b91af"&gt;Console&lt;/span&gt;.WriteLine(F(1) + 1);
}

&lt;span style="color: blue"&gt;static int &lt;/span&gt;F(&lt;span style="color: blue"&gt;int &lt;/span&gt;n)
{
    &lt;span style="color: blue"&gt;return &lt;/span&gt;G(n + 1) + 1;
}

&lt;span style="color: blue"&gt;static int &lt;/span&gt;G(&lt;span style="color: blue"&gt;int &lt;/span&gt;n)
{
    &lt;span style="color: blue"&gt;return &lt;/span&gt;n + 1;
}&lt;/pre&gt;
&lt;/blockquote&gt;
&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;

&lt;p&gt;However, what should the transformation do with the return statement in &lt;em&gt;F&lt;/em&gt;?&amp;#160; The continuation passed to &lt;em&gt;G&lt;/em&gt; should definitely not attempt to return a result because the continuation is a void-returning delegate.&lt;/p&gt;

&lt;blockquote&gt;
  &lt;pre class="code"&gt;&lt;span style="color: blue"&gt;static void &lt;/span&gt;F(&lt;span style="color: blue"&gt;int &lt;/span&gt;n, &lt;span style="color: #2b91af"&gt;Action&lt;/span&gt;&amp;lt;&lt;span style="color: blue"&gt;int&lt;/span&gt;&amp;gt; k)
{
    G(n + 1, x =&amp;gt; { &lt;span style="color: blue"&gt;return &lt;/span&gt;x + 1; });  &lt;span style="color: green"&gt;// error, Action&amp;lt;int&amp;gt; cannot return a value
&lt;/span&gt;}&lt;/pre&gt;
  &lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;&lt;/blockquote&gt;
&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;

&lt;p&gt;That wouldn't make any sense.&amp;#160; Delegates with void return-types cannot return values.&amp;#160; Furthermore, the code completely ignores &lt;em&gt;k&lt;/em&gt;.&lt;/p&gt;

&lt;p&gt;Instead, the return statement should be transformed into an invocation of &lt;em&gt;k&lt;/em&gt;.&lt;/p&gt;

&lt;blockquote&gt;
  &lt;pre class="code"&gt;&lt;span style="color: blue"&gt;static void &lt;/span&gt;Main()
{
    F(1, x =&amp;gt; &lt;span style="color: #2b91af"&gt;Console&lt;/span&gt;.WriteLine(x + 1));
}

&lt;span style="color: blue"&gt;static void &lt;/span&gt;F(&lt;span style="color: blue"&gt;int &lt;/span&gt;n, &lt;span style="color: #2b91af"&gt;Action&lt;/span&gt;&amp;lt;&lt;span style="color: blue"&gt;int&lt;/span&gt;&amp;gt; k)
{
    G(n + 1, x =&amp;gt; k(x + 1));
}

&lt;span style="color: blue"&gt;static void &lt;/span&gt;G(&lt;span style="color: blue"&gt;int &lt;/span&gt;n, &lt;span style="color: #2b91af"&gt;Action&lt;/span&gt;&amp;lt;&lt;span style="color: blue"&gt;int&lt;/span&gt;&amp;gt; k)
{
    k(n + 1);
}&lt;/pre&gt;
  &lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;&lt;/blockquote&gt;
&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;

&lt;p&gt;This is how functions that use explicit continuations are composed together.&lt;/p&gt;

&lt;p&gt;What about recursive functions like Factorial?&lt;/p&gt;

&lt;blockquote&gt;
  &lt;pre class="code"&gt;&lt;span style="color: blue"&gt;static void &lt;/span&gt;Main()
{
    &lt;span style="color: #2b91af"&gt;Console&lt;/span&gt;.WriteLine(Factorial(5));
}

&lt;span style="color: blue"&gt;static int &lt;/span&gt;Factorial(&lt;span style="color: blue"&gt;int &lt;/span&gt;n)
{
    &lt;span style="color: blue"&gt;if &lt;/span&gt;(n == 0)
        &lt;span style="color: blue"&gt;return &lt;/span&gt;1;
    &lt;span style="color: blue"&gt;else
        return &lt;/span&gt;n * Factorial(n - 1);
}&lt;/pre&gt;
&lt;/blockquote&gt;
&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;

&lt;p&gt;Recursive functions can be transformed just as easily following the same steps.&lt;/p&gt;

&lt;blockquote&gt;
  &lt;pre class="code"&gt;&lt;span style="color: blue"&gt;static void &lt;/span&gt;Main()
{
    Factorial(5, x =&amp;gt; &lt;span style="color: #2b91af"&gt;Console&lt;/span&gt;.WriteLine(x));
}

&lt;span style="color: blue"&gt;static void &lt;/span&gt;Factorial(&lt;span style="color: blue"&gt;int &lt;/span&gt;n, &lt;span style="color: #2b91af"&gt;Action&lt;/span&gt;&amp;lt;&lt;span style="color: blue"&gt;int&lt;/span&gt;&amp;gt; k)
{
    &lt;span style="color: blue"&gt;if &lt;/span&gt;(n == 0)
        k(1);
    &lt;span style="color: blue"&gt;else
        &lt;/span&gt;Factorial(n - 1, x =&amp;gt; k(n * x));
}&lt;/pre&gt;
&lt;/blockquote&gt;
&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;

&lt;p&gt;CPS turns a program inside-out.&amp;#160; In the process, the programmer may feel that his brain has been turned inside-out as well.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Why CPS?&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;What exactly can a programmer do with CPS besides showoff at parties?&lt;/p&gt;

&lt;p&gt;Compilers use a more thorough CPS transformation to produce an intermediate form amenable to many analyses.&amp;#160; UI frameworks use CPS to keep the UI responsive while allowing nonlinear program interaction.&amp;#160; Web servers use CPS to allow computation to flow asynchronously across pages.&lt;/p&gt;

&lt;p&gt;Most programmers have used functions which take a callback.&amp;#160; Often, the callback is the code that is invoked upon completion of the function.&amp;#160; In these cases, the callback is an explicitly-passed continuation.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Asynchronous Calls&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Hiding network latency requires asynchronous calls.&amp;#160; In the first technology preview, Volta allows programmers to add asynchronous versions of methods on tier boundaries.&lt;/p&gt;

&lt;blockquote&gt;
  &lt;pre class="code"&gt;[&lt;span style="color: #2b91af"&gt;RunAtOrigin&lt;/span&gt;]
&lt;span style="color: blue"&gt;static class &lt;/span&gt;&lt;span style="color: #2b91af"&gt;C
&lt;/span&gt;{
    &lt;span style="color: blue"&gt;public static int &lt;/span&gt;F(&lt;span style="color: blue"&gt;string &lt;/span&gt;s)
    {
        &lt;span style="color: blue"&gt;return &lt;/span&gt;s != &lt;span style="color: blue"&gt;null &lt;/span&gt;? s.Length : 0;
    }
}&lt;/pre&gt;
&lt;/blockquote&gt;

&lt;p&gt;To make a method asynchronous, define the CPS-equivalent method signature and annotate it with the &lt;em&gt;Async &lt;/em&gt;attribute.&amp;#160; Volta will generate the body and modify the call-sites accordingly.&lt;/p&gt;

&lt;blockquote&gt;
  &lt;pre class="code"&gt;[&lt;span style="color: #2b91af"&gt;Async&lt;/span&gt;]
&lt;span style="color: blue"&gt;public static void &lt;/span&gt;F(&lt;span style="color: blue"&gt;string &lt;/span&gt;s, &lt;span style="color: #2b91af"&gt;Action&lt;/span&gt;&amp;lt;&lt;span style="color: blue"&gt;int&lt;/span&gt;&amp;gt; k);&lt;/pre&gt;
&lt;/blockquote&gt;
&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;

&lt;p&gt;If the programmer invokes an asynchronous method &lt;em&gt;F, &lt;/em&gt;then Volta will launch the invocation on another thread and invoke the continuation upon completion of the call to &lt;em&gt;F.&lt;/em&gt;&lt;/p&gt;

&lt;blockquote&gt;
  &lt;pre class="code"&gt;&lt;span style="color: #2b91af"&gt;C&lt;/span&gt;.F(&lt;span style="color: #a31515"&gt;&amp;quot;foo&amp;quot;&lt;/span&gt;, x =&amp;gt; &lt;span style="color: #2b91af"&gt;Console&lt;/span&gt;.WriteLine(x));&lt;/pre&gt;
&lt;/blockquote&gt;
&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;

&lt;p&gt;&lt;strong&gt;Wrapping it Up&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Continuations are powerful.&amp;#160; CPS gives programmers a way to use continuations in their day-to-day work.&amp;#160; Perhaps, someday soon we'll discuss how to make CPS more palatable, but we will need to discuss the &amp;quot;M&amp;quot; word first.&lt;/p&gt;&lt;img src="http://blogs.msdn.com/aggbug.aspx?PostID=6833509" width="1" height="1"&gt;</description><category domain="http://blogs.msdn.com/wesdyer/archive/tags/C_2300_/default.aspx">C#</category><category domain="http://blogs.msdn.com/wesdyer/archive/tags/Functional+Programming/default.aspx">Functional Programming</category><category domain="http://blogs.msdn.com/wesdyer/archive/tags/Volta/default.aspx">Volta</category></item><item><title>Musings on Software Testing</title><link>http://blogs.msdn.com/wesdyer/archive/2007/12/07/musings-on-software-testing.aspx</link><pubDate>Fri, 07 Dec 2007 22:42:24 GMT</pubDate><guid isPermaLink="false">91d46819-8472-40ad-a661-2c78acb4018c:6696424</guid><dc:creator>wesdyer</dc:creator><slash:comments>15</slash:comments><comments>http://blogs.msdn.com/wesdyer/comments/6696424.aspx</comments><wfw:commentRss>http://blogs.msdn.com/wesdyer/commentrss.aspx?PostID=6696424</wfw:commentRss><description>&lt;p&gt;It was spring 2003, I had just finished a weekend camping in the southern Arizona desert.&amp;#160; I was dusty and physically exhausted from hours of playing paintball.&amp;#160; For those who have never been in those parts, imagine long straight roads with dry sage brush, painful cactus, and jagged mountains.&amp;#160; I needed a book to pass the time during the drive.&amp;#160; Fortunately, I had brought along &lt;a href="http://www.amazon.com/Extreme-Programming-Explained-Embrace-Change/dp/0321278658/ref=pd_bbs_sr_1/104-8800337-6061564?ie=UTF8&amp;amp;s=books&amp;amp;qid=1191966305&amp;amp;sr=8-1"&gt;&amp;quot;Extreme Programming Explained&amp;quot;&lt;/a&gt; by &lt;a href="http://en.wikipedia.org/wiki/Kent_Beck"&gt;Kent Beck&lt;/a&gt;.&amp;#160; After having spent too much time in projects that either completely lacked process or had way too much of it, Beck's position seemed like a revelation.&amp;#160; Over the next few months, I became acquainted with &lt;a href="http://www.amazon.com/Test-Driven-Development-Addison-Wesley-Signature/dp/0321146530/ref=pd_bxgy_b_img_b/104-8800337-6061564"&gt;test-driven development&lt;/a&gt;, &lt;a href="http://www.amazon.com/Design-Patterns-Object-Oriented-Addison-Wesley-Professional/dp/0201633612/ref=pd_sim_b_shvl_img_1/104-8800337-6061564"&gt;design patterns&lt;/a&gt;, &lt;a href="http://www.amazon.com/Refactoring-Improving-Design-Existing-Code/dp/0201485672/ref=pd_bxgy_b_img_b/104-8800337-6061564"&gt;refactoring&lt;/a&gt; and many of the other topics typically associated with &lt;a href="http://en.wikipedia.org/wiki/Agile_programming"&gt;agile programming&lt;/a&gt;. &lt;/p&gt;  &lt;p&gt;&lt;strong&gt;Test Driven Development&lt;/strong&gt; &lt;/p&gt;  &lt;p&gt;In the spring, I had a course that ended up just teaching agile programming concepts.&amp;#160; One of the things that the professor emphasized was following the test-driven development (TDD) process to the letter. &lt;/p&gt;  &lt;p&gt;&lt;a href="http://blogs.msdn.com/blogfiles/wesdyer/WindowsLiveWriter/EscapingtheFixedPointofDevelopment_D551/image_6.png"&gt;&lt;img style="border-top-width: 0px; border-left-width: 0px; border-bottom-width: 0px; border-right-width: 0px" height="335" alt="image" src="http://blogs.msdn.com/blogfiles/wesdyer/WindowsLiveWriter/EscapingtheFixedPointofDevelopment_D551/image_thumb_2.png" width="518" border="0" /&gt;&lt;/a&gt; &lt;/p&gt; &lt;a href="http://en.wikipedia.org/wiki/Test-driven_development"&gt;The TDD Process:&lt;/a&gt;   &lt;blockquote&gt;   &lt;p&gt;1.&amp;#160; Add a test &lt;/p&gt;    &lt;p&gt;2.&amp;#160; Run all tests and see the new one fail &lt;/p&gt;    &lt;p&gt;3.&amp;#160; Write some code &lt;/p&gt;    &lt;p&gt;4.&amp;#160; Run the automated tests and see them succeed&amp;#160; &lt;/p&gt;    &lt;p&gt;5.&amp;#160; &lt;a href="http://en.wikipedia.org/wiki/Refactor"&gt;Refactor&lt;/a&gt; code &lt;/p&gt;    &lt;p&gt;&lt;em&gt;Repeat&lt;/em&gt;&lt;/p&gt; &lt;/blockquote&gt;  &lt;p&gt;When I say refactor, I mean it in the strictest sense.&amp;#160; I mean changing how a program is arranged internally without changing the semantics of the program at all.&amp;#160; This of course ignores the fact that things like timing, working set, or stack size change which can be material to the run-time behavior of the program.&lt;/p&gt;  &lt;p&gt;During step three a programmer should remember, &amp;quot;It is important that the code written is &lt;i&gt;only&lt;/i&gt; designed to pass the test; no further (and therefore untested) functionality should be predicted and 'allowed for' at any stage&amp;quot;.&lt;/p&gt;  &lt;p&gt;&lt;strong&gt;Machine Learning&lt;/strong&gt; &lt;/p&gt;  &lt;p&gt; I fully bought into this rigorous approach to TDD until one summer day when I was reading through &lt;a href="http://www.cs.cmu.edu/~tom/"&gt;Tom Mitchell&lt;/a&gt;'s marvelous book &lt;a href="http://www.amazon.com/Machine-Learning-Tom-M-Mitchell/dp/0070428077/ref=sr_1_2/104-8800337-6061564?ie=UTF8&amp;amp;s=books&amp;amp;qid=1191967459&amp;amp;sr=1-2"&gt;&amp;quot;Machine Learning&amp;quot;&lt;/a&gt;.&amp;#160; The book begins by defining &lt;a href="http://en.wikipedia.org/wiki/Machine_learning"&gt;machine learning&lt;/a&gt;: &lt;/p&gt;  &lt;blockquote&gt;   &lt;p&gt;A computer program is said to &lt;strong&gt;learn&lt;/strong&gt; from experience &lt;em&gt;E&lt;/em&gt; with respect to some class of tasks &lt;em&gt;T&lt;/em&gt; and performance measure &lt;em&gt;P&lt;/em&gt;, if its performance at tasks in &lt;em&gt;T&lt;/em&gt;, as measured by &lt;em&gt;P&lt;/em&gt;, improves with experience &lt;em&gt;E.&lt;/em&gt;&lt;/p&gt; &lt;/blockquote&gt;  &lt;p&gt;Intuitively, the learning process is trying to learn some unknown concept.&amp;#160; The learner has access to its past experiences (the training data) and uses them to generate a hypothesis of the unknown concept.&amp;#160; This hypothesis is then evaluated and the new experiences are added to the training data.&amp;#160; The learning process then repeats itself as the learner forms a better approximation of the underlying concept.&amp;#160; &lt;/p&gt;  &lt;p&gt;TDD is a learning process.&amp;#160; Where the training experience &lt;em&gt;E&lt;/em&gt; is the automated tests, the task &lt;em&gt;T &lt;/em&gt;is improving the quality of the program, and the performance measure &lt;em&gt;P&lt;/em&gt; is the percentage of tests passed.&amp;#160; In this view of TDD, the programmer continues to hack away at his program generating hypotheses, where each hypothesis is a version of the code, until one satisfies the data.&amp;#160; Note that unless the tests exhaustively specify the desired behavior of a program, then the tests &lt;em&gt;are not&lt;/em&gt; the target concept that needs to be learned but rather a few data points where the target concept is manifest.&amp;#160; Furthermore, the program should not only do well against the tests but also against real world scenarios which may not be covered by the tests. &lt;/p&gt;  &lt;p&gt;&lt;a href="http://blogs.msdn.com/blogfiles/wesdyer/WindowsLiveWriter/EscapingtheFixedPointofDevelopment_D551/j0385807_2.jpg"&gt;&lt;img style="border-top-width: 0px; border-left-width: 0px; border-bottom-width: 0px; border-right-width: 0px" height="288" alt="j0385807" src="http://blogs.msdn.com/blogfiles/wesdyer/WindowsLiveWriter/EscapingtheFixedPointofDevelopment_D551/j0385807_thumb.jpg" width="404" border="0" /&gt;&lt;/a&gt; &lt;/p&gt;  &lt;p&gt;&lt;strong&gt;Bias and Learning&lt;/strong&gt; &lt;/p&gt;  &lt;p&gt;A learner is characterized by its hypothesis space and &lt;a href="http://jmvidal.cse.sc.edu/talks/conceptlearning/learningassearch.xml?style=White"&gt;how it searches through that space&lt;/a&gt;.&amp;#160; Notice that since each learner has a hypothesis space, a given concept may have not be in that space.&amp;#160; One solution to this problem is to make a learner's hypothesis space &lt;a href="http://jmvidal.cse.sc.edu/talks/conceptlearning/unbiasedlearner.xml?style=White"&gt;include all hypotheses&lt;/a&gt;, but this leads to a &lt;a href="http://jmvidal.cse.sc.edu/talks/conceptlearning/futilityofnobias.xml?style=White"&gt;fundamental problem&lt;/a&gt;: &amp;quot;a learner that makes no a priori assumptions regarding the identity of the target concept has no rational basis for classifying any unseen instances.&amp;quot;&amp;#160; The only thing that an unbiased learner can do is regurgitate the training data because it has no ability to make the assumptions and logical leaps necessary to deal with unseen data. &lt;/p&gt;  &lt;p&gt;For example, suppose that I am trying to learn to classify animals as either mammals or non-mammals and suppose that I make no assumptions whatsoever in the process of learning this task.&amp;#160; If I am told that giraffes, lions, mice, bats, and whales are mammals but snakes, butterflies, frogs, lobsters, and&amp;#160; penguins are not, then I only have the ability to answer questions regarding those animals for which I already know the answer.&amp;#160; I could have done much better by trying to guess at what makes an animal a mammal even if I got it wrong! &lt;/p&gt;  &lt;p&gt;Returning to TDD, note that at no time is a programmer supposed to write code that generalizes to the target concept.&amp;#160; The programmer should only write either the minimal code to make a test pass or refactor the code and not change the semantics.&amp;#160; So according to the pure TDD approach, the program would only learn to regurgitate the training data and do who knows what against new examples.&amp;#160; A critic might respond that more test cases are needed.&amp;#160; In some cases where the input space is finite and small, this might well help, but in general this is impractical. &lt;/p&gt;  &lt;p&gt;&lt;strong&gt;Sufficiently Large Projects&lt;/strong&gt; &lt;/p&gt;  &lt;p&gt;A similar situation arises in projects that are sufficiently large.&amp;#160; These projects are characterized by the fact that they cannot be held inside any one person's head.&amp;#160; This means that when someone is making a change, they cannot know all of the consequences of their change.&amp;#160; Often in projects of this size, when people ask if a particular change is good, the response is, &amp;quot;It passed the tests.&amp;quot;&amp;#160; This leads to a state where the development process as a whole is a learning process that uses the test cases as the training data and generates programs as hypotheses that are evaluated against the training data.&amp;#160; Most likely, the target concept is not normally fully determined by the tests. &lt;/p&gt;  &lt;p&gt;You know the projects that I am talking about, and chances are that you have seen some code that was added in just to satisfy some test but didn't really capture the essence of what the test was originally trying to make the program do.&amp;#160; While tests are invaluable to programmers for debugging purposes, it would be better if programmers returned to the specification in order to understand what they are supposed to develop instead of returning to the tests.&lt;/p&gt;  &lt;p&gt;Testing practices like clean-room testing and various forms of white box testing address address the programmer bias deficiency, but it can also be addressed automatically.&lt;/p&gt;  &lt;p&gt;&lt;strong&gt;Testing an Infinite Space&lt;/strong&gt; &lt;/p&gt;  &lt;p&gt;I had a development lead who liked to say that testing is just sampling.&amp;#160; In a sense he is right, since a test is a particular input sequence given to a program from the set of all possible input sequences.&amp;#160; Think of a program as a state machine encoded in your &lt;a href="http://en.wikipedia.org/wiki/Process_calculus"&gt;favorite process calculus&lt;/a&gt;.&amp;#160; A test then verifies that a particular path of edges corresponding to the transitions based on the input ends in a particular state.&amp;#160; Most interesting programs have an infinite number of possible input sequences because of their recursive nature and so the set of tests must be sampled from an infinite input space. &lt;/p&gt;  &lt;p&gt;Testing creates tests by drawing input sequences out of the input sequence space.&amp;#160; It is easy to imagine that tests could be generated randomly by selecting random input sequences.&amp;#160; Random selection has several advantages.&amp;#160; First, it enables statistical measures of quality.&amp;#160; For example, if we sample uniformly then the pass/fail rate should be representative of the whole given a large enough sample.&amp;#160; We could also keep generating more and more tests to improve our confidence that the program is indeed correct.&amp;#160; Second, random tests have the added benefit of not allowing the programmers to just &amp;quot;pass the tests&amp;quot; since the programmers cannot anticipate what tests will be run.&amp;#160; This forces the programmers to generate a hypothesis that more closely matches the target concept instead of the training data. &lt;/p&gt;  &lt;p&gt;There are however some disadvantages.&amp;#160; The first apparent problem is repeatability of the tests.&amp;#160; This can be remedied by storing the seed that generates a set of tests.&amp;#160; A second more serious problem is that a uniform random sample doesn't necessarily deliver the best results. &lt;/p&gt;  &lt;p&gt;&lt;strong&gt;On Bugs&lt;/strong&gt; &lt;/p&gt;  &lt;p&gt;Not all bugs are created equal.&amp;#160; Practices such as testing the boundary conditions and integration testing are based on that fact.&amp;#160; Various testing practices explore parts of the input space that are richer in bugs or are more likely to contain serious bugs. &lt;/p&gt;  &lt;p&gt;&lt;a href="http://blogs.msdn.com/blogfiles/wesdyer/WindowsLiveWriter/EscapingtheFixedPointofDevelopment_D551/image_8.png"&gt;&lt;img style="border-top-width: 0px; border-left-width: 0px; border-bottom-width: 0px; border-right-width: 0px" height="168" alt="image" src="http://blogs.msdn.com/blogfiles/wesdyer/WindowsLiveWriter/EscapingtheFixedPointofDevelopment_D551/image_thumb_3.png" width="628" border="0" /&gt;&lt;/a&gt;&lt;/p&gt;  &lt;p&gt;The cost of a bug can be quantified as the total monetary loss due to the presence of that bug in the software.&amp;#160; This includes all sorts of things like lost sales through negative customer perception, cost of software patches, legal action, etc.&amp;#160; While this is an accurate measure of cost, it is not very practical because it is very hard to estimate.&lt;/p&gt;  &lt;p&gt;A more practical measure for estimating the relative cost of a bug might be the probability that users will find it multiplied by the severity of the bug.&amp;#160; The first part of the equation is interesting because it indicates that those bugs that customers never find are not important for testing to find. &lt;/p&gt;  &lt;p&gt;&lt;strong&gt;Back to Training&lt;/strong&gt;&lt;/p&gt;  &lt;p&gt;The testing ideal is to minimize the total cost of bugs.&amp;#160; There are many good methods for writing test cases.&amp;#160; In addition to these, we could also select input sequences based upon the probability that a user would select such an input sequence.&lt;/p&gt;  &lt;p&gt;Imagine if it were possible to collect all of the input sequences that would ever be given to a program including duplicates.&amp;#160; Then our problem would be reduced to uniformly selecting input sequences out of this collection.&amp;#160; Obviously, this collection is unavailable but if we use the same machine learning principles which we have been discussing then we could develop a program that could learn to generate test cases according to some distribution by using a representative set of user input sequences as training data.&lt;/p&gt;  &lt;p&gt;&lt;strong&gt;Markov Chains&lt;/strong&gt;&lt;/p&gt;  &lt;p&gt;One way that this could be done is by returning to the formulation of a computer program as a state machine.&amp;#160; The object is to learn the probability that a user would take some transition given a particular state and a sequence of previous states and transitions.&amp;#160; This can be formulated as a &lt;a href="http://en.wikipedia.org/wiki/Markov_chain"&gt;Markov chain&lt;/a&gt;.&lt;/p&gt;  &lt;p&gt;Consider generating random test cases for a parser.&amp;#160; A straightforward approach is to randomly derive a &lt;a href="http://en.wikipedia.org/wiki/String_%28computer_science%29"&gt;string&lt;/a&gt; in the &lt;a href="http://en.wikipedia.org/wiki/Formal_language"&gt;language&lt;/a&gt; from the root &lt;a href="http://en.wikipedia.org/wiki/Nonterminal_symbol"&gt;non-terminal&lt;/a&gt;; however, it will quickly become apparent that the least used parts of your language are getting undue attention.&amp;#160; Some more sophisticated tools allow productions in the &lt;a href="http://en.wikipedia.org/wiki/Formal_grammar"&gt;grammar&lt;/a&gt; to be attributed with weights.&amp;#160; This works better but forces the tester to learn the proper weights manually and it doesn't accurately describe the weights since the probability that a particular &lt;a href="http://en.wikipedia.org/wiki/Production_%28computer_science%29"&gt;production&lt;/a&gt; for a non-terminal will be used is also based on the history of previously expanded productions.&lt;/p&gt;  &lt;p&gt;A better approach is to learn weights for the Markov chain corresponding to the &lt;a href="http://en.wikipedia.org/wiki/Pushdown_automata"&gt;pushdown automata&lt;/a&gt;.&amp;#160; Since a parser for an arbitrary &lt;a href="http://en.wikipedia.org/wiki/Context-free_grammar"&gt;context-free grammar&lt;/a&gt; can be expressed by a pushdown automaton, we can instrument the automaton to collect data on the probability of some transition given a state and a history of states and transitions.&amp;#160; The instrumented automaton can then be fed a large number of user-written programs.&amp;#160; Finally, a generator can be created that uses the data to generate programs that syntactically look like user-written programs.&lt;/p&gt;  &lt;p&gt;Another approach might be to instrument branches and event sequences in a program and then train against user input.&amp;#160; The learner could then build a Markov chain that can be used to generate input sequences roughly like user input.&lt;/p&gt;  &lt;p&gt;&lt;strong&gt;Conclusion&lt;/strong&gt;&lt;/p&gt;  &lt;p&gt;Next time you find yourself in a project that is devolving into an unbiased learning process, restore the sanity by using the specification and not the tests to decide what to implement. &lt;/p&gt;&lt;img src="http://blogs.msdn.com/aggbug.aspx?PostID=6696424" width="1" height="1"&gt;</description><category domain="http://blogs.msdn.com/wesdyer/archive/tags/Programming/default.aspx">Programming</category></item><item><title>Volta and You</title><link>http://blogs.msdn.com/wesdyer/archive/2007/12/06/volta-and-you.aspx</link><pubDate>Thu, 06 Dec 2007 20:37:27 GMT</pubDate><guid isPermaLink="false">91d46819-8472-40ad-a661-2c78acb4018c:6682387</guid><dc:creator>wesdyer</dc:creator><slash:comments>19</slash:comments><comments>http://blogs.msdn.com/wesdyer/comments/6682387.aspx</comments><wfw:commentRss>http://blogs.msdn.com/wesdyer/commentrss.aspx?PostID=6682387</wfw:commentRss><description>&lt;p&gt;Yesterday, Volta was made publicly available for the first time.&amp;#160; It is an &lt;em&gt;experimental&lt;/em&gt; project in the early stages of development.&amp;#160; The team decided to release an early technology preview so that developers everywhere can help guide the project through experience and feedback.&amp;#160; We want your feedback.&lt;/p&gt;  &lt;p&gt;The first release provides the basic feature set that will be improved upon with time.&amp;#160; It has some obvious shortcomings that we are aware of and are actively addressing.&amp;#160; But really, at this stage, the preview is more concerned with sparking your imagination about what is possible than ironing out all of the details.&lt;/p&gt;  &lt;p&gt;Perhaps you disagree.&amp;#160; Maybe the most important feature to you is the completeness of a final product.&amp;#160; If that is the case, then say so and we will seriously consider making it a higher priority for the upcoming early experimental releases.&lt;/p&gt;  &lt;p&gt;At some point, Volta may become, feed into, or inform a product, but that is a little way off yet.&amp;#160; So let's enjoy the unique opportunity of working together to make something great.&lt;/p&gt;  &lt;p&gt;In the coming months, I will alternate between three types of posts:&lt;/p&gt;  &lt;blockquote&gt;   &lt;p&gt;1.&amp;#160; Volta focused posts: explaining the motivation, features, and technical details&lt;/p&gt;    &lt;p&gt;2.&amp;#160; C#: this includes both 3.0 and eventually 4.0 features&lt;/p&gt;    &lt;p&gt;3.&amp;#160; Random thoughts: like it says; two that will be discussed soon are programmer tests and continuations&lt;/p&gt; &lt;/blockquote&gt;  &lt;p&gt;I hope you enjoy the posts and I look forward to engaging with you in discussion.&lt;/p&gt;&lt;img src="http://blogs.msdn.com/aggbug.aspx?PostID=6682387" width="1" height="1"&gt;</description><category domain="http://blogs.msdn.com/wesdyer/archive/tags/Volta/default.aspx">Volta</category></item><item><title>Volta: Redefining Web Development</title><link>http://blogs.msdn.com/wesdyer/archive/2007/12/05/volta-redefining-web-development.aspx</link><pubDate>Wed, 05 Dec 2007 22:14:36 GMT</pubDate><guid isPermaLink="false">91d46819-8472-40ad-a661-2c78acb4018c:6669478</guid><dc:creator>wesdyer</dc:creator><slash:comments>25</slash:comments><comments>http://blogs.msdn.com/wesdyer/comments/6669478.aspx</comments><wfw:commentRss>http://blogs.msdn.com/wesdyer/commentrss.aspx?PostID=6669478</wfw:commentRss><description>&lt;p&gt;Anyone who writes web applications knows that web development is not easy.&amp;#160; Developers wrangle with a soup of technologies distributed across multiple tiers.&amp;#160; We live in a world where programmers accept the fact that they need to know &lt;a href="http://en.wikipedia.org/wiki/Web_development"&gt;four or five different languages, tools, and environments&lt;/a&gt; just to get a site up and running.&amp;#160; In ancient times, the Egyptians built marvelous structures despite &lt;a href="http://books.google.com/books?id=MXaR-s9N4uEC&amp;amp;pg=PA136&amp;amp;lpg=PA136&amp;amp;dq=copper+chisels&amp;amp;source=web&amp;amp;ots=nanvWmY6qx&amp;amp;sig=LA6IC5LOR6pMssDO6OH3m_MzGc0#PPP1,M1"&gt;the primitive tools&lt;/a&gt; that &lt;a href="http://books.google.com/books?id=-sFpPTDMyrMC&amp;amp;pg=PA211&amp;amp;lpg=PA211&amp;amp;dq=copper+chisels&amp;amp;source=web&amp;amp;ots=P5yoKMAI01&amp;amp;sig=xAtHpZye37I-OerXxStPD3PZbvI"&gt;the workmen used&lt;/a&gt;.&amp;#160; Building a pyramid took most of the national resources of wealth and labor.&amp;#160; Today, we build structures which are vastly more complicated and yet require only a tiny fraction of the resources.&amp;#160; The difference is in the tools and the infrastructure.&lt;/p&gt;  &lt;p&gt;In a similar way, Volta significantly improves web development.&amp;#160; Programmers write web applications using familiar .NET languages, libraries, and tools.&amp;#160; Volta splits the application into multiple parts potentially running on different tiers, say, client and server.&amp;#160; Client code needs only a minimal, JavaScript-enabled browser, though Volta will take advantage of additional runtimes that may be present.&lt;/p&gt;  &lt;p&gt;Programmers simply refactor classes that need to run on tiers other than the client and Volta injects the boilerplate code for communication, serialization, synchronization -- all the remoting code.&amp;#160; The developer enjoys all of the benefits of .NET: a great debugger, test tools, profiling, intellisense, refactorings, etc.&lt;/p&gt;  &lt;p&gt;Just how simple is Volta?&amp;#160; Let's write an application that uses a button to query the server for a string and displays that string to the client: the hello world web application.&lt;/p&gt;  &lt;p&gt;&lt;a href="http://blogs.msdn.com/blogfiles/wesdyer/WindowsLiveWriter/VoltaRedefiningWebDevelopment_D283/image_4.png"&gt;&lt;img style="border-top-width: 0px; border-left-width: 0px; border-bottom-width: 0px; border-right-width: 0px" height="297" alt="image" src="http://blogs.msdn.com/blogfiles/wesdyer/WindowsLiveWriter/VoltaRedefiningWebDevelopment_D283/image_thumb_1.png" width="470" border="0" /&gt;&lt;/a&gt; &lt;/p&gt;  &lt;p&gt;Now, let's write the code for the web page.&amp;#160; We need a &lt;em&gt;Div&lt;/em&gt; for the output and an &lt;em&gt;Input &lt;/em&gt;for the interaction.&amp;#160; Of course, we could have constructed the page elements with HTML/CSS instead.&lt;/p&gt;  &lt;pre class="code"&gt;&lt;span style="color: blue"&gt;using &lt;/span&gt;System;
&lt;span style="color: blue"&gt;using &lt;/span&gt;Microsoft.LiveLabs.Volta.Html;
&lt;span style="color: blue"&gt;using &lt;/span&gt;Microsoft.LiveLabs.Volta.Xml;

&lt;span style="color: blue"&gt;namespace &lt;/span&gt;HelloWorld
{
    &lt;span style="color: blue"&gt;public partial class &lt;/span&gt;&lt;span style="color: #2b91af"&gt;VoltaPage1 &lt;/span&gt;: &lt;span style="color: #2b91af"&gt;Page
    &lt;/span&gt;{
        &lt;span style="color: blue"&gt;public &lt;/span&gt;VoltaPage1()
        {
            &lt;span style="color: blue"&gt;var &lt;/span&gt;output = &lt;span style="color: blue"&gt;new &lt;/span&gt;&lt;span style="color: #2b91af"&gt;Div&lt;/span&gt;();

            &lt;span style="color: blue"&gt;var &lt;/span&gt;b = &lt;span style="color: blue"&gt;new &lt;/span&gt;&lt;span style="color: #2b91af"&gt;Input&lt;/span&gt;();
            b.Type = &lt;span style="color: #a31515"&gt;&amp;quot;button&amp;quot;&lt;/span&gt;;
            b.Value = &lt;span style="color: #a31515"&gt;&amp;quot;Get Message&amp;quot;&lt;/span&gt;;
            b.Click += () =&amp;gt; output.InnerHtml = &lt;span style="color: #2b91af"&gt;C&lt;/span&gt;.GetMessage();

            Document.Body.AppendChild(output);
            Document.Body.AppendChild(b);
        }
    }

    &lt;span style="color: blue"&gt;class &lt;/span&gt;&lt;span style="color: #2b91af"&gt;C
    &lt;/span&gt;{
        &lt;span style="color: blue"&gt;public static string &lt;/span&gt;GetMessage()
        {
            &lt;span style="color: blue"&gt;return &lt;/span&gt;&lt;span style="color: #a31515"&gt;&amp;quot;Hello, World&amp;quot;&lt;/span&gt;;
        }
    }
}&lt;/pre&gt;
&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;

&lt;p&gt;But we want to produce the message on the server.&amp;#160; Time to refactor.&lt;/p&gt;

&lt;p&gt;&amp;#160;&lt;a href="http://blogs.msdn.com/blogfiles/wesdyer/WindowsLiveWriter/VoltaRedefiningWebDevelopment_D283/image8.png"&gt;&lt;img style="border-top-width: 0px; border-left-width: 0px; border-bottom-width: 0px; border-right-width: 0px" height="355" alt="image" src="http://blogs.msdn.com/blogfiles/wesdyer/WindowsLiveWriter/VoltaRedefiningWebDevelopment_D283/image8_thumb.png" width="484" border="0" /&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Browser clients call the server, the &amp;quot;Origin&amp;quot;, because this ensures the message will come from the same server that supplied the HTML.&lt;/p&gt;

&lt;pre class="code"&gt;[&lt;span style="color: #2b91af"&gt;RunAtOrigin&lt;/span&gt;]
&lt;span style="color: blue"&gt;class &lt;/span&gt;&lt;span style="color: #2b91af"&gt;C
&lt;/span&gt;{
    &lt;span style="color: blue"&gt;public static string &lt;/span&gt;GetMessage()
    {
        &lt;span style="color: blue"&gt;return &lt;/span&gt;&lt;span style="color: #a31515"&gt;&amp;quot;Hello, World&amp;quot;&lt;/span&gt;;
    }
} &lt;/pre&gt;

&lt;p&gt;That is it.&amp;#160; Try it out.&lt;/p&gt;

&lt;p&gt;&lt;a href="http://blogs.msdn.com/blogfiles/wesdyer/WindowsLiveWriter/VoltaRedefiningWebDevelopment_D283/image12.png"&gt;&lt;img style="border-top-width: 0px; border-left-width: 0px; border-bottom-width: 0px; border-right-width: 0px" height="252" alt="image" src="http://blogs.msdn.com/blogfiles/wesdyer/WindowsLiveWriter/VoltaRedefiningWebDevelopment_D283/image12_thumb.png" width="513" border="0" /&gt;&lt;/a&gt; &lt;/p&gt;

&lt;p&gt;Now, click &amp;quot;Get Message&amp;quot;.&lt;/p&gt;

&lt;p&gt;&lt;a href="http://blogs.msdn.com/blogfiles/wesdyer/WindowsLiveWriter/VoltaRedefiningWebDevelopment_D283/image16.png"&gt;&lt;img style="border-top-width: 0px; border-left-width: 0px; border-bottom-width: 0px; border-right-width: 0px" height="249" alt="image" src="http://blogs.msdn.com/blogfiles/wesdyer/WindowsLiveWriter/VoltaRedefiningWebDevelopment_D283/image16_thumb.png" width="506" border="0" /&gt;&lt;/a&gt; &lt;/p&gt;

&lt;p&gt;Great.&amp;#160; But is it cross-browser compatible?&lt;/p&gt;

&lt;p&gt;&lt;a href="http://blogs.msdn.com/blogfiles/wesdyer/WindowsLiveWriter/VoltaRedefiningWebDevelopment_D283/image20.png"&gt;&lt;img style="border-top-width: 0px; border-left-width: 0px; border-bottom-width: 0px; border-right-width: 0px" height="225" alt="image" src="http://blogs.msdn.com/blogfiles/wesdyer/WindowsLiveWriter/VoltaRedefiningWebDevelopment_D283/image20_thumb.png" width="499" border="0" /&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Yes.&amp;#160; And you can debug it. &lt;/p&gt;

&lt;p&gt;&amp;#160;&lt;a href="http://blogs.msdn.com/blogfiles/wesdyer/WindowsLiveWriter/VoltaRedefiningWebDevelopment_D283/image30.png"&gt;&lt;img style="border-top-width: 0px; border-left-width: 0px; border-bottom-width: 0px; border-right-width: 0px" height="759" alt="image" src="http://blogs.msdn.com/blogfiles/wesdyer/WindowsLiveWriter/VoltaRedefiningWebDevelopment_D283/image30_thumb.png" width="899" border="0" /&gt;&lt;/a&gt; &lt;/p&gt;

&lt;p&gt;You can even debug across tiers.&lt;/p&gt;

&lt;p&gt;&lt;a href="http://blogs.msdn.com/blogfiles/wesdyer/WindowsLiveWriter/VoltaRedefiningWebDevelopment_D283/image35.png"&gt;&lt;img style="border-top-width: 0px; border-left-width: 0px; border-bottom-width: 0px; border-right-width: 0px" height="761" alt="image" src="http://blogs.msdn.com/blogfiles/wesdyer/WindowsLiveWriter/VoltaRedefiningWebDevelopment_D283/image35_thumb.png" width="900" border="0" /&gt;&lt;/a&gt;&amp;#160;&lt;/p&gt;

&lt;p&gt;There is a lot more to Volta in the first technology preview which was made publicly available at 11 am PST today and there will be a lot more to come.&lt;/p&gt;

&lt;p&gt;Still skeptical?&amp;#160; Try it out for yourself.&lt;/p&gt;

&lt;p&gt;&lt;a href="http://labs.live.com/volta"&gt;http://labs.live.com/volta&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;a href="http://blogs.msdn.com/blogfiles/wesdyer/WindowsLiveWriter/VoltaRedefiningWebDevelopment_D283/image_2.png"&gt;&lt;img style="border-top-width: 0px; border-left-width: 0px; border-bottom-width: 0px; border-right-width: 0px" height="168" alt="image" src="http://blogs.msdn.com/blogfiles/wesdyer/WindowsLiveWriter/VoltaRedefiningWebDevelopment_D283/image_thumb.png" width="354" border="0" /&gt;&lt;/a&gt;&lt;/p&gt;&lt;img src="http://blogs.msdn.com/aggbug.aspx?PostID=6669478" width="1" height="1"&gt;</description><category domain="http://blogs.msdn.com/wesdyer/archive/tags/Volta/default.aspx">Volta</category></item><item><title>More on Partial Methods</title><link>http://blogs.msdn.com/wesdyer/archive/2007/05/31/more-on-partial-methods.aspx</link><pubDate>Thu, 31 May 2007 08:34:45 GMT</pubDate><guid isPermaLink="false">91d46819-8472-40ad-a661-2c78acb4018c:3001145</guid><dc:creator>wesdyer</dc:creator><slash:comments>16</slash:comments><comments>http://blogs.msdn.com/wesdyer/comments/3001145.aspx</comments><wfw:commentRss>http://blogs.msdn.com/wesdyer/commentrss.aspx?PostID=3001145</wfw:commentRss><description>&lt;p&gt;Thank you everyone for the feedback.&amp;nbsp; If you have any more to say then please do express your opinion (and yes it is valued ;).&amp;nbsp; I think there has been a bit of misunderstanding about what partial methods really are.&amp;nbsp; So let's set the matter straight.&amp;nbsp; Here is the current spec (quoting from here on out):&lt;/p&gt; &lt;p&gt;Partial methods are a new feature complementing partial classes with the option of declaring “hook” – or compile time events – in the code.  &lt;p&gt;Here is an example  &lt;blockquote&gt; &lt;p&gt;&lt;font face="Courier New"&gt;partial class Customer&lt;/font&gt;  &lt;p&gt;&lt;font face="Courier New"&gt;{&lt;/font&gt;  &lt;p&gt;&lt;font face="Courier New"&gt;&amp;nbsp; public string Name {&lt;/font&gt;  &lt;p&gt;&lt;font face="Courier New"&gt;&amp;nbsp; &amp;nbsp; get { … }&lt;/font&gt;  &lt;p&gt;&lt;font face="Courier New"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; set {&lt;/font&gt;  &lt;p&gt;&lt;font face="Courier New"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; OnNameChanging(value);&lt;/font&gt;  &lt;p&gt;&lt;font face="Courier New"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; _name = value;&lt;/font&gt;  &lt;p&gt;&lt;font face="Courier New"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; OnNameChanged();&lt;/font&gt;  &lt;p&gt;&lt;font face="Courier New"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; }&lt;/font&gt;  &lt;p&gt;&lt;font face="Courier New"&gt;&amp;nbsp; }&lt;/font&gt;  &lt;p&gt;&lt;font face="Courier New"&gt;&amp;nbsp; partial void OnNameChanging(string value);&lt;/font&gt;  &lt;p&gt;&lt;font face="Courier New"&gt;&amp;nbsp; partial void onNameChanged();&lt;/font&gt;  &lt;p&gt;&lt;font face="Courier New"&gt;}&lt;/font&gt;&lt;/p&gt;&lt;/blockquote&gt; &lt;p&gt;Partial methods are only allowed in partial types; either classes or structs. There are no other kinds of partial members.  &lt;p&gt;There are two parts of a partial method; the &lt;i&gt;defining&lt;/i&gt; and the &lt;i&gt;implementing&lt;/i&gt; partial method declaration. There can be at most one defining declaration, and at most one implementing declaration, and the implementing declaration is only allowed if there is a defining declaration. The defining declaration is distinguished by having a “;” instead of a method body. The two can both appear in the same partial type declaration.  &lt;p&gt;Partial methods must always return void. The contextual keyword partial has to appear right before void – that is how we recognize it. They can have ref but not out parameters; both params and this modifiers are allowed in the usual positions.  &lt;p&gt;Access modifiers on partial methods are not allowed, but partial instead implies private. The only modifiers allowed on a partial method declaration (apart from partial) are unsafe and static. Thus a partial method declaration cannot declare or override a virtual method. Also, partial methods cannot be extern, because the presence of the body determines whether they are defining or implementing.  &lt;p&gt;If both a defining and an implementing partial method declaration are given, all modifiers on parameters and the method declarations themselves must be given in both declarations, although not necessarily in the same order.  &lt;p&gt;Partial methods can be generic. Constraints are placed on the defining partial method declaration, and must be repeated on the implementing one. Parameter and type parameter names do not have to be the same in the implementing declaration and the defining one.  &lt;p&gt;Whether or not there is an implementing declaration, a partial method participates in overload resolution and type checking in the normal way. If there is no implementing declaration, however, the method will be removed. Furthermore calls to the method are removed, including evaluation of arguments to the call, in a manner similar to conditional methods.  &lt;p&gt;You can only make a delegate to a partial method if there is an implementing declaration; otherwise a compile time error occurs. Similarly, calls to a partial method occurring within the body of a lambda which is converted to an expression tree are only allowed if there is an implementing declaration of the partial method.  &lt;p&gt;Because partial methods are always private, they cannot implement interface methods, neither implicitly or explicitly.  &lt;p&gt;If both a defining and an implementing partial method declaration are given, attributes on the resulting method and its return type, parameters and type parameters are determined by assembling, in unspecified order, the attributes from both the defining and implementing declarations. Duplicates are not removed. Thus, for attributes that can only occur once on a given declaration, having that attribute on both declarations will result in a compile time error.  &lt;p&gt;Definite assignment is only checked after the possible removal of partial method calls and evaluation of the argument expressions. Thus, if assignments occur within these argument expressions, and the method is removed, they will not affect definite assignment. This can potentially lead to compile time errors.  &lt;p&gt;&lt;a&gt;&lt;/a&gt; &lt;p&gt;The Main method of a program can be a partial method, but will only be considered as the entry point for the program if there is an implementing declaration.  &lt;p&gt;XML doc comments are allowed on both defining and implementing partial method declarations, but only the ones that appear on the implementing declaration will be used by the compiler. Other tools may make use of the comments on defining declarations.&lt;/p&gt;&lt;img src="http://blogs.msdn.com/aggbug.aspx?PostID=3001145" width="1" height="1"&gt;</description></item><item><title>In Case You Haven't Heard</title><link>http://blogs.msdn.com/wesdyer/archive/2007/05/23/in-case-you-haven-t-heard.aspx</link><pubDate>Wed, 23 May 2007 21:19:06 GMT</pubDate><guid isPermaLink="false">91d46819-8472-40ad-a661-2c78acb4018c:2820432</guid><dc:creator>wesdyer</dc:creator><slash:comments>93</slash:comments><comments>http://blogs.msdn.com/wesdyer/comments/2820432.aspx</comments><wfw:commentRss>http://blogs.msdn.com/wesdyer/commentrss.aspx?PostID=2820432</wfw:commentRss><description>&lt;p&gt;It has been a while since I have posted.&amp;nbsp;&amp;nbsp;We have been&amp;nbsp;working hard to get Orcas beta 1 and beta 2 done.&amp;nbsp; So I apologize for the long interlude between posts but I hope that you are enjoying beta 1 and that you are looking forward to beta 2.&lt;/p&gt; &lt;p&gt;Now that beta 1 is out there, what do you all think of it?&amp;nbsp; Beta 1 has &lt;em&gt;most&lt;/em&gt; of the features that we intend to put into Orcas but not all of them.&amp;nbsp; Some notable differences you will see in later releases are improved performance, error messages, error recovery, stability, and a few refinements.&amp;nbsp; Basically the kind of polish that people expect as a product nears completion.&lt;/p&gt; &lt;p&gt;&lt;strong&gt;Partial Methods&lt;/strong&gt;&lt;/p&gt; &lt;p&gt;One feature that you may have not heard of yet is a feature called partial methods.&amp;nbsp; This is some of the work that I did in the last coding milestone a few months back.&amp;nbsp; Partial methods are methods that enable lightweight event handling.&amp;nbsp; Here is an example declaration:&lt;/p&gt; &lt;blockquote&gt; &lt;p&gt;&lt;font face="Courier New"&gt;&lt;/font&gt; &lt;p&gt;&lt;font face="Courier New"&gt;partial class C&lt;br&gt;{&lt;br&gt;&amp;nbsp; static partial void M(int i);&lt;br&gt;}&lt;/font&gt;&lt;/p&gt;&lt;/blockquote&gt; &lt;p&gt;There are a few notable things here:&lt;/p&gt; &lt;blockquote&gt; &lt;p&gt;1.&amp;nbsp; Partial methods must be declared within partial classes&lt;/p&gt; &lt;p&gt;2.&amp;nbsp; Partial methods are indicated by the partial modifier&lt;/p&gt; &lt;p&gt;3.&amp;nbsp; Partial methods do not always have a body (well look at this more below)&lt;/p&gt; &lt;p&gt;4.&amp;nbsp; Partial methods must return void&lt;/p&gt; &lt;p&gt;5.&amp;nbsp; Partial methods &lt;em&gt;can&lt;/em&gt; be static&lt;/p&gt; &lt;p&gt;6.&amp;nbsp; Partial methods can have arguments (including this, ref, and params modifiers)&lt;/p&gt; &lt;p&gt;&lt;strong&gt;7.&amp;nbsp; Partial methods &lt;em&gt;must&lt;/em&gt; be private&lt;/strong&gt;&lt;/p&gt;&lt;/blockquote&gt; &lt;p&gt;Now suppose that I make a call to C.M.&lt;/p&gt; &lt;blockquote&gt; &lt;p&gt;&lt;font face="Courier New"&gt;partial class C&lt;br&gt;{&lt;/font&gt;  &lt;p&gt;&lt;font face="Courier New"&gt;&amp;nbsp; static void Main()&lt;br&gt;&amp;nbsp; {&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; C.M(Calculation());&lt;br&gt;&amp;nbsp; }&lt;br&gt;}&lt;/font&gt;&lt;/p&gt;&lt;/blockquote&gt; &lt;p&gt;Since M has no body, all calls to C.M are removed at compile time &lt;em&gt;as well as the evaluation of the arguments&lt;/em&gt;.&amp;nbsp; So the above program is equivalent to:&lt;/p&gt; &lt;blockquote&gt; &lt;p&gt;&lt;font face="Courier New"&gt;partial class C&lt;br&gt;{&lt;/font&gt;  &lt;p&gt;&lt;font face="Courier New"&gt;&amp;nbsp; static void Main()&lt;br&gt;&amp;nbsp; {&lt;br&gt;&amp;nbsp; }&lt;br&gt;}&lt;/font&gt;&lt;/p&gt;&lt;/blockquote&gt; &lt;p&gt;In this sense, partial methods are the distant cousins of conditional methods which also sometimes remove the call and the evaluation of the arguments.&amp;nbsp; But partial methods go even further.&amp;nbsp; When a partial method has no body then the partial method is not even emitted to metadata.&lt;/p&gt; &lt;p&gt;So far this might seem a little confusing.&amp;nbsp; C# now allows users to declare methods for which the calls, the evaluation of the arguments, and the method itself are not emitted.&amp;nbsp; Fortunately, the story doesn't end there.&amp;nbsp; Partial methods allow users to define a body for the method so that the method, the calls, and the evaluation of the arguments are emitted.&lt;/p&gt; &lt;blockquote&gt; &lt;p&gt;&lt;font face="Courier New"&gt;partial class C&lt;br&gt;{&lt;br&gt;&amp;nbsp; static partial void M(int i); // defining declaration&lt;br&gt;&amp;nbsp; static partial void M(int i)&amp;nbsp; // implementing declaration&lt;br&gt;&amp;nbsp; {&lt;br&gt;&amp;nbsp; }&lt;br&gt;}&lt;/font&gt;&lt;/p&gt;&lt;/blockquote&gt; &lt;p&gt;In the code above, we see that there is a difference between a defining declaration of a partial method and an implementing declaration of a partial method and the difference is whether or not the method has a body.&amp;nbsp; These definitions don't have to be in the same partial class declaration.&amp;nbsp; There may only be one defining declaration and if a defining declaration exists then there may be an implementing declaration.&lt;/p&gt; &lt;p&gt;&lt;strong&gt;Why Partial Methods?&lt;/strong&gt;&lt;/p&gt; &lt;p&gt;So how are these partial methods used?&amp;nbsp; The common scenario is to use them to do lightweight event handling.&amp;nbsp; For example a tool that generates code may wish to have hooks for users to customize what code is run.&amp;nbsp; For example, imagine that a tool generated a bunch of code for a class representing a customer.&amp;nbsp; It might look like this:&lt;/p&gt; &lt;blockquote&gt; &lt;p&gt;&lt;font face="Courier New"&gt;partial class Customer&lt;br&gt;{&lt;br&gt;&amp;nbsp; string name; &lt;/font&gt; &lt;p&gt;&lt;font face="Courier New"&gt;&amp;nbsp; public string Name&lt;br&gt;&amp;nbsp; {&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; get&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; {&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; return name;&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;}&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; set&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; {&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; OnBeforeUpdateName();&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; OnUpdateName();&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; name = value;&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; OnAfterUpdateName();&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; }&lt;br&gt;&amp;nbsp;&amp;nbsp;} &lt;/font&gt; &lt;p&gt;&lt;font face="Courier New"&gt;&amp;nbsp; partial void OnBeforeUpdateName();&lt;br&gt;&amp;nbsp; partial void OnAfterUpdateName();&lt;br&gt;&amp;nbsp; partial void OnUpdateName();&lt;br&gt;}&lt;/font&gt;&lt;/p&gt;&lt;/blockquote&gt; &lt;p&gt;If the user doesn't add any implementing definitions then this code is equivalent to:&lt;/p&gt; &lt;blockquote&gt; &lt;p&gt;&lt;font face="Courier New"&gt;partial class Customer&lt;br&gt;{&lt;br&gt;&amp;nbsp; string name; &lt;/font&gt; &lt;p&gt;&lt;font face="Courier New"&gt;&amp;nbsp; public string Name&lt;br&gt;&amp;nbsp; {&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; get&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; {&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; return name;&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;}&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; set&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; {&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; name = value;&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; }&lt;br&gt;&amp;nbsp;&amp;nbsp;} &lt;/font&gt; &lt;p&gt;&lt;font face="Courier New"&gt;}&lt;/font&gt;&lt;/p&gt;&lt;/blockquote&gt; &lt;p&gt;No extra metadata for things that are not used and no extra instructions for useless operations.&amp;nbsp; On the other hand if the user listened to the OnUpdateName "event" like this:&lt;/p&gt; &lt;blockquote&gt; &lt;p&gt;&lt;font face="Courier New"&gt;partial class Customer&lt;br&gt;{&lt;br&gt;&amp;nbsp; partial void OnUpdateName()&lt;br&gt;&amp;nbsp; {&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; DoSomething();&lt;br&gt;&amp;nbsp; }&lt;br&gt;}&lt;/font&gt;&lt;/p&gt;&lt;/blockquote&gt; &lt;p&gt;Then the original definition is equivalent to:&lt;/p&gt; &lt;blockquote&gt; &lt;p&gt;&lt;font face="Courier New"&gt;partial class Customer&lt;br&gt;{&lt;br&gt;&amp;nbsp; string name; &lt;/font&gt; &lt;p&gt;&lt;font face="Courier New"&gt;&amp;nbsp; public string Name&lt;br&gt;&amp;nbsp; {&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; get&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; {&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; return name;&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;}&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; set&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; {&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; OnUpdateName();&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; name = value;&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; }&lt;br&gt;&amp;nbsp;&amp;nbsp;} &lt;/font&gt; &lt;p&gt;&lt;font face="Courier New"&gt;&amp;nbsp; partial void OnUpdateName();&lt;br&gt;}&lt;/font&gt;&lt;/p&gt;&lt;/blockquote&gt; &lt;p&gt;&lt;strong&gt;Comparing Partial Methods to the Alternatives&lt;/strong&gt;&lt;/p&gt; &lt;p&gt;At this point, it is sensible to ask why not just use subclassing and virtual methods?&amp;nbsp; Of course, this would also work but it does have the drawback that the calls, the methods, and the evaluation of the arguments will still be emitted even if the virtual methods are not overridden.&amp;nbsp; So in a system like Linq to SQL that has thousands of little events it allows these events to be very lightweight so that the user only pays for those events that she uses.&lt;/p&gt; &lt;p&gt;&lt;strong&gt;A Few Fine Points&lt;/strong&gt;&lt;/p&gt; &lt;p&gt;Consider the following program...&lt;/p&gt; &lt;blockquote&gt; &lt;p&gt;&lt;font face="Courier New"&gt;partial class C&lt;br&gt;{&lt;br&gt;&amp;nbsp; static void Main()&lt;br&gt;&amp;nbsp; {&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; int i = 3;&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; C.M(i = 5);&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; Console.WriteLine(i);&lt;br&gt;&amp;nbsp; }&lt;br&gt;}&lt;/font&gt;&lt;/p&gt;&lt;/blockquote&gt; &lt;p&gt;What does it write to the console?&amp;nbsp; 3, 5, ...?&lt;/p&gt; &lt;p&gt;Actually, it is impossible to tell from just this code.&amp;nbsp; If there is no implementing declaration then the program will display 3 because the i = 5 will never be evaluated, but if there is an implementing declaration then the program will display 5.&amp;nbsp; The same is true for conditional methods.&amp;nbsp; So if you want a side-effect to occur make sure you do not cause the side-effect to occur as an argument to a partial method.&amp;nbsp; Of course, the same trick can be used to hide expensive calculations.&lt;/p&gt; &lt;blockquote&gt; &lt;p&gt;&lt;font face="Courier New"&gt;partial class C&lt;br&gt;{&lt;br&gt;&amp;nbsp; static void Main()&lt;br&gt;&amp;nbsp; {&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; C.M(VeryVeryExpensiveCalculation());&lt;br&gt;&amp;nbsp; }&lt;br&gt;}&lt;/font&gt;&lt;/p&gt;&lt;/blockquote&gt; &lt;p&gt;If there is no implementing declaration then the very very expensive calculation will never be performed.&lt;/p&gt; &lt;p&gt;Now what about attributes, how does those work?&lt;/p&gt; &lt;blockquote&gt; &lt;p&gt;&lt;font face="Courier New"&gt;partial class D&lt;br&gt;{&lt;br&gt;&amp;nbsp; [W]&lt;br&gt;&amp;nbsp; [return:X]&lt;br&gt;&amp;nbsp; partial void M&amp;lt;[Y]T&amp;gt;([Z]int foo)&lt;br&gt;&amp;nbsp; {&lt;br&gt;&amp;nbsp; } &lt;/font&gt; &lt;p&gt;&lt;font face="Courier New"&gt;&amp;nbsp; [Z]&lt;br&gt;&amp;nbsp; [return:W]&lt;br&gt;&amp;nbsp; partial void M&amp;lt;[X]T&amp;gt;([Y]int foo);&lt;br&gt;}&lt;/font&gt;&lt;/p&gt;&lt;/blockquote&gt; &lt;p&gt;What attributes are actually emitted on M?&amp;nbsp; W and Z are the attributes on M; X and W are the attributes on the return type; Y and X are the attributes on the type parameter; Z and Y are the attributes on the parameter.&lt;/p&gt; &lt;p&gt;Enjoy!&lt;/p&gt;&lt;img src="http://blogs.msdn.com/aggbug.aspx?PostID=2820432" width="1" height="1"&gt;</description><category domain="http://blogs.msdn.com/wesdyer/archive/tags/C_2300_/default.aspx">C#</category></item><item><title>All About Iterators</title><link>http://blogs.msdn.com/wesdyer/archive/2007/03/23/all-about-iterators.aspx</link><pubDate>Fri, 23 Mar 2007 11:26:00 GMT</pubDate><guid isPermaLink="false">91d46819-8472-40ad-a661-2c78acb4018c:1935848</guid><dc:creator>wesdyer</dc:creator><slash:comments>16</slash:comments><comments>http://blogs.msdn.com/wesdyer/comments/1935848.aspx</comments><wfw:commentRss>http://blogs.msdn.com/wesdyer/commentrss.aspx?PostID=1935848</wfw:commentRss><description>&lt;p&gt;&lt;a href="http://en.wikipedia.org/wiki/Design_pattern_(computer_science)"&gt;Design patterns&lt;/a&gt; have been all of the rage for a number of years now.&amp;nbsp; We have design patterns for concurrency, user interfaces, data access, object creation, and so many other things.&amp;nbsp; The seminal work on the topic is the &lt;a href="http://en.wikipedia.org/wiki/Gang_of_Four_%28software%29"&gt;Gang of Four&lt;/a&gt;'s book, &lt;a href="http://www.amazon.com/Design-Patterns-Object-Oriented-Addison-Wesley-Professional/dp/0201633612/ref=pd_bbs_1/002-3886557-6494420?ie=UTF8&amp;amp;s=books&amp;amp;qid=1174622120&amp;amp;sr=8-1"&gt;Design Patterns&lt;/a&gt;.&amp;nbsp; When used appropriately they are a fantastic way to codify the wisdom gleaned from the battles we have fought building software systems.&lt;/p&gt; &lt;p&gt;&lt;a href="http://www.paulgraham.com/icad.html"&gt;One&lt;/a&gt; &lt;a href="http://perl.plover.com/yak/design/"&gt;of&lt;/a&gt; &lt;a href="http://discuss.joelonsoftware.com/default.asp?joel.3.219431.12"&gt;the&lt;/a&gt; &lt;a href="http://norvig.com/design-patterns/ppframe.htm"&gt;criticisms&lt;/a&gt; &lt;a href="http://www.parand.com/say/index.php/2005/07/18/i-hate-patterns/"&gt;leveled&lt;/a&gt; &lt;a href="http://citeseer.ist.psu.edu/felleisen90expressive.html"&gt;at&lt;/a&gt; &lt;a href="http://etymon.blogspot.com/2006/04/perils-of-avoiding-heresy-or-what-are.html"&gt;design&lt;/a&gt; &lt;a href="http://blog.plover.com/prog/design-patterns.html"&gt;patterns&lt;/a&gt; is that they are simply formalisms to address&amp;nbsp;weaknesses in&amp;nbsp;programming languages.&amp;nbsp; They require&amp;nbsp;the human compiler to generate code&amp;nbsp;whenever a&amp;nbsp;specific recurring problem is encountered that cannot be solved directly with language support.&amp;nbsp; Now this might sound like heresy to some, but&amp;nbsp;there is some truth to the criticism.&amp;nbsp; Programmers adapt to the shortcomings in the languages they use by generating pattern like code either by hand or with &lt;a href="http://en.wikipedia.org/wiki/Metaprogramming"&gt;metaprogramming&lt;/a&gt; (generics, dynamic code generation, reflection, expression trees, macros).&lt;/p&gt; &lt;p&gt;Let's take a look at one such example.&lt;/p&gt; &lt;p&gt;&lt;strong&gt;The Iterator Design Pattern&lt;/strong&gt;&lt;/p&gt; &lt;p&gt;Among the many patterns&amp;nbsp;in the literature is the &lt;a href="http://en.wikipedia.org/wiki/Iterator_pattern"&gt;iterator pattern&lt;/a&gt;.&lt;/p&gt; &lt;p&gt;&lt;img height="275" alt="Iterator Design Pattern" src="http://blogs.msdn.com/blogfiles/wesdyer/WindowsLiveWriter/TheCostofIterators_A895/image015.png" width="420"&gt;&amp;nbsp;&lt;/p&gt; &lt;p&gt;In .NET this pattern is embodied by &lt;a href="http://msdn2.microsoft.com/en-us/library/system.collections.ienumerable.aspx"&gt;IEnumerable&lt;/a&gt;/&lt;a href="http://msdn2.microsoft.com/en-us/library/9eekhta0.aspx"&gt;IEnumerable&amp;lt;T&amp;gt;&lt;t&gt;&lt;/a&gt; and &lt;a href="http://msdn2.microsoft.com/en-us/library/system.collections.ienumerator.aspx"&gt;IEnumerator&lt;/a&gt;/&lt;a href="http://msdn2.microsoft.com/en-us/library/78dfe2yb.aspx"&gt;IEnumerator&amp;lt;T&amp;gt;&lt;t&gt;&lt;/a&gt;.&lt;/p&gt; &lt;p&gt;&lt;img height="78" alt="IEnumerable&amp;lt;T&amp;gt; and IEnumerator&amp;lt;T&amp;gt;" src="http://blogs.msdn.com/blogfiles/wesdyer/WindowsLiveWriter/TheCostofIterators_A895/image014.png" width="425"&gt; &lt;/p&gt; &lt;p&gt;An IEnumerable&amp;lt;T&amp;gt; is something that can be enumerated (iterated) by calling GetEnumerator which will return an IEnumerator&amp;lt;T&amp;gt; (iterator).&amp;nbsp; The IEnumerator&amp;lt;T&amp;gt; is used to move a virtual cursor over the items that are iterated.&lt;/p&gt; &lt;p&gt;Implementing the iterator pattern is a bit onerous.&amp;nbsp; For example, here is the suggested iterator implementation for List&amp;lt;T&amp;gt;&amp;nbsp;from the Design Pattern book.&lt;/p&gt; &lt;blockquote&gt; &lt;p&gt;&lt;font face="Courier New"&gt;class ListIterator&amp;lt;T&amp;gt; : IEnumerator&amp;lt;T&amp;gt;&lt;br&gt;{&lt;br&gt;&amp;nbsp; List&amp;lt;T&amp;gt; list;&lt;br&gt;&amp;nbsp; int current; &lt;/font&gt; &lt;p&gt;&lt;font face="Courier New"&gt;&amp;nbsp; public ListIterator(List&amp;lt;T&amp;gt; list)&lt;br&gt;&amp;nbsp; {&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; this.list = list;&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; current = -1;&lt;br&gt;&amp;nbsp; } &lt;/font&gt; &lt;p&gt;&lt;font face="Courier New"&gt;&amp;nbsp; public T Current {&amp;nbsp;get { return list[current]; } } &lt;/font&gt; &lt;p&gt;&lt;font face="Courier New"&gt;&amp;nbsp; public bool MoveNext()&lt;br&gt;&amp;nbsp; {&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; return ++current &amp;lt; list.Count;&lt;br&gt;&amp;nbsp; } &lt;/font&gt; &lt;p&gt;&lt;font face="Courier New"&gt;&amp;nbsp; public void Reset()&lt;br&gt;&amp;nbsp; {&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; current = -1;&lt;br&gt;&amp;nbsp; }&lt;br&gt;}&lt;/font&gt;&lt;/p&gt;&lt;/blockquote&gt; &lt;p&gt;Since we can't change the list itself, we can introduce a ListIterable&amp;lt;T&amp;gt; that wraps a list.&lt;/p&gt; &lt;blockquote&gt; &lt;p&gt;&lt;font face="Courier New"&gt;class ListIterable&amp;lt;T&amp;gt; : IEnumerable&amp;lt;T&amp;gt;&lt;br&gt;{&lt;br&gt;&amp;nbsp; List&amp;lt;T&amp;gt; list; &lt;/font&gt; &lt;p&gt;&lt;font face="Courier New"&gt;&amp;nbsp; public ListIterable(List&amp;lt;T&amp;gt; list)&lt;br&gt;&amp;nbsp; {&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; this.list = list;&lt;br&gt;&amp;nbsp; } &lt;/font&gt; &lt;p&gt;&lt;font face="Courier New"&gt;&amp;nbsp; public IEnumerator&amp;lt;T&amp;gt; GetEnumerator()&lt;br&gt;&amp;nbsp; {&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; return new ListIterator&amp;lt;T&amp;gt;(list);&lt;br&gt;&amp;nbsp; } &lt;/font&gt; &lt;p&gt;&lt;font face="Courier New"&gt;} &lt;/font&gt;&lt;/p&gt;&lt;/blockquote&gt; &lt;p&gt;And finally, we can write a method called GetElements which returns an IEnumerable&amp;lt;T&amp;gt; over the elements of a List&amp;lt;T&amp;gt;.&lt;/p&gt; &lt;blockquote&gt; &lt;p&gt;&lt;font face="Courier New"&gt;static IEnumerable&amp;lt;T&amp;gt; GetElements&amp;lt;T&amp;gt;(this List&amp;lt;T&amp;gt; list)&lt;br&gt;{&lt;br&gt;&amp;nbsp; return new ListIterable&amp;lt;T&amp;gt;(list);&lt;br&gt;}&lt;/font&gt;&lt;/p&gt;&lt;/blockquote&gt; &lt;p&gt;&lt;strong&gt;Iterators in C#&lt;/strong&gt;&lt;/p&gt; &lt;p&gt;Fortunately in most cases programmers don't need to deal with the iterator design pattern directly since the introduction of iterators in C# 2.0.&amp;nbsp; Instead of writing the iterator above, we can simply write the following:&lt;/p&gt; &lt;blockquote&gt; &lt;p&gt;&lt;font face="Courier New"&gt;static IEnumerable&amp;lt;T&amp;gt; GetElements&amp;lt;T&amp;gt;(this List&amp;lt;T&amp;gt; list)&lt;br&gt;{&lt;br&gt;&amp;nbsp; for (int index = 0; index &amp;lt; list.Count; ++index)&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; yield return list[index];&lt;br&gt;}&lt;/font&gt;&lt;/p&gt;&lt;/blockquote&gt; &lt;p&gt;When the C# compiler sees this method, it translates it into something very similar to the ListIterator&amp;lt;T&amp;gt; and ListIterable&amp;lt;T&amp;gt;&amp;nbsp;above.&amp;nbsp; Using Reflector or ILDasm we can see that the GetElements method is rewritten as (the names have been changed for clarity as the compiler generates unspeakable names;):  &lt;blockquote&gt;&lt;pre&gt;&lt;/pre&gt;
&lt;p&gt;&lt;font face="Courier New"&gt;private static IEnumerable&amp;lt;T&amp;gt; GetElements&amp;lt;T&amp;gt;(this List&amp;lt;T&amp;gt; list)&lt;br&gt;{&lt;br&gt;&amp;nbsp; GetElementsIterator&amp;lt;T&amp;gt; temp = new GetElementsIterator&amp;lt;T&amp;gt;(-2);&lt;br&gt;&amp;nbsp; temp.listParameter = list;&lt;br&gt;&amp;nbsp; return temp;&lt;br&gt;}&lt;/font&gt;&lt;pre&gt;&lt;/pre&gt;&lt;/blockquote&gt;
&lt;p&gt;This is remarkably closer to the first GetElements&amp;nbsp;we wrote rather than the second.&amp;nbsp;&amp;nbsp;Like in the first GetElements, we create an object that implements IEnumerable&amp;lt;T&amp;gt; and parameterize this object with the list that was passed in.&amp;nbsp; The &lt;em&gt;only&lt;/em&gt; other thing that happens in this implementation that doesn't in the first GetElements method&amp;nbsp;is a -2 is passed into the object.&amp;nbsp; I'll come back to this later, but first let's take a look at the GetElementsIterator&amp;lt;T&amp;gt; class (I omitted a few details and changed names&amp;nbsp;for clarity). 
&lt;blockquote&gt;&lt;pre&gt;&lt;/pre&gt;
&lt;p&gt;&lt;font face="Courier New"&gt;private sealed class GetElementsIterator&amp;lt;T&amp;gt; : IEnumerable&amp;lt;T&amp;gt;, IEnumerator&amp;lt;T&amp;gt;&lt;br&gt;{&lt;br&gt;&amp;nbsp; int state;&lt;br&gt;&amp;nbsp; T current;&lt;br&gt;&amp;nbsp; public List&amp;lt;T&amp;gt; listParameter;&lt;br&gt;&amp;nbsp; int initialThreadId;&lt;br&gt;&amp;nbsp; public int index;&lt;br&gt;&amp;nbsp; public List&amp;lt;T&amp;gt; list; &lt;/font&gt;
&lt;p&gt;&lt;font face="Courier New"&gt;&amp;nbsp; public GetElementsIterator(int state);&lt;br&gt;&amp;nbsp; private bool MoveNext();&lt;br&gt;&amp;nbsp; IEnumerator&amp;lt;T&amp;gt; IEnumerable&amp;lt;T&amp;gt;.GetEnumerator();&lt;br&gt;&amp;nbsp; void IEnumerator.Reset(); &lt;/font&gt;
&lt;p&gt;&lt;font face="Courier New"&gt;&amp;nbsp; T IEnumerator&amp;lt;T&amp;gt;.Current { get; }&lt;br&gt;}&lt;/font&gt;&lt;/p&gt;&lt;/blockquote&gt;
&lt;p&gt;The most important thing to note at this time is that GetElementsIterator implements &lt;em&gt;both &lt;/em&gt;IEnumerable&amp;lt;T&amp;gt; and IEnumerator&amp;lt;T&amp;gt;.&amp;nbsp; A strange combination, but we will see why in a little while.&amp;nbsp; Now let's look at what actually happened when we ran the constructor.&amp;nbsp; &lt;pre&gt;&lt;/pre&gt;
&lt;p&gt;
&lt;blockquote&gt;
&lt;p&gt;&lt;font face="Courier New"&gt;public GetElementsIterator(int state)&lt;br&gt;{&lt;br&gt;&amp;nbsp; this.state = state;&lt;br&gt;&amp;nbsp; this.initialThreadId = Thread.CurrentThread.ManagedThreadId;&lt;br&gt;}&lt;/font&gt;&lt;/p&gt;&lt;/blockquote&gt;
&lt;p&gt;Did the constructor run the for loop?&amp;nbsp; No, it didn't.&amp;nbsp; It took some variable called state in and marked what thread created the iterator (if you look at Whidbey code the initialThreadId stuff won't be there...I'll get to that).&amp;nbsp; The state variable marks what state the GetElementsIterator is in.&amp;nbsp; The number -2 is the "I'm an IEnumerable&amp;lt;T&amp;gt;" state.&amp;nbsp; Now, let's look at the GetEnumerator method. 
&lt;blockquote&gt;&lt;pre&gt;&lt;/pre&gt;
&lt;p&gt;&lt;font face="Courier New"&gt;IEnumerator&amp;lt;T&amp;gt; IEnumerable&amp;lt;T&amp;gt;.GetEnumerator()&lt;br&gt;{&lt;br&gt;&amp;nbsp; GetElementsIterator&amp;lt;T&amp;gt; temp;&lt;br&gt;&amp;nbsp; if ((Thread.CurrentThread.ManagedThreadId == initialThreadId) &amp;amp;&amp;amp; (state == -2))&lt;br&gt;&amp;nbsp; {&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; state = 0;&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; temp = this;&lt;br&gt;&amp;nbsp; }&lt;br&gt;&amp;nbsp; else&lt;br&gt;&amp;nbsp; {&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; temp = new GetElementsIterator&amp;lt;T&amp;gt;(0);&lt;br&gt;&amp;nbsp; }&lt;br&gt;&amp;nbsp; temp.list = this.listParameter;&lt;br&gt;&amp;nbsp; return temp;&lt;br&gt;}&lt;/font&gt;&lt;/p&gt;&lt;/blockquote&gt;&lt;pre&gt;&lt;/pre&gt;
&lt;p&gt;The method first checks to see if the thread that is calling GetEnumerator is the same thread that created the GetElementsIterator object.&amp;nbsp; If it is the same thread and if the GetElementsIterator is in the "I'm an IEnumerable&amp;lt;T&amp;gt;" state then the state is changed to the "I'm an initialized IEnumerator&amp;lt;T&amp;gt;" state.&amp;nbsp; Otherwise, a new object of the same type is created but it is immediately put in the "I'm an initialized IEnumerator&amp;lt;T&amp;gt;" state so that thread safety is maintained.&amp;nbsp; Finally, in either case the list that was passed from the GetElements method is copied into the list field for consumption by the MoveNext method. 
&lt;p&gt;In Whidbey code, you will see that the if statement is different because an Interlock.Exchange was used to perform the same task.&amp;nbsp; The change was made to improve performance (especially for iterators that have 0 or 1 items to iterate over). 
&lt;p&gt;Now we have seen why GetElementsIterator implements both IEnumerable&amp;lt;T&amp;gt; and IEnumerator&amp;lt;T&amp;gt;, because it can morph from the IEnumerable&amp;lt;T&amp;gt; role into the IEnumerator&amp;lt;T&amp;gt; role without creating any new objects in most cases. 
&lt;p&gt;The Current property is very simple. 
&lt;blockquote&gt;&lt;pre&gt;&lt;/pre&gt;
&lt;p&gt;&lt;font face="Courier New"&gt;T IEnumerator&amp;lt;T&amp;gt;.Current&lt;br&gt;{&lt;br&gt;&amp;nbsp; get&lt;br&gt;&amp;nbsp; {&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; return current;&lt;br&gt;&amp;nbsp; }&lt;br&gt;}&lt;/font&gt;&lt;/p&gt;&lt;/blockquote&gt;&lt;pre&gt;&lt;/pre&gt;
&lt;p&gt;The Reset method simply throws a NotSupportedException. 
&lt;p&gt;This leaves us with only the MoveNext to examine.&amp;nbsp; We still haven't seen where the for loop went.&amp;nbsp; Hopefully, it is in the MoveNext.&amp;nbsp; The following code is produced with the /o+ compiler option (optimizations turned on). 
&lt;blockquote&gt;&lt;pre&gt;&lt;/pre&gt;
&lt;p&gt;&lt;font face="Courier New"&gt;private bool MoveNext()&lt;br&gt;{&lt;br&gt;&amp;nbsp; switch (state)&lt;br&gt;&amp;nbsp; {&lt;br&gt;&amp;nbsp; case 0:&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; state = -1;&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; index = 0;&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; break; &lt;/font&gt;
&lt;p&gt;&lt;font face="Courier New"&gt;&amp;nbsp; case 1:&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; state = -1;&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; index++;&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; break; &lt;/font&gt;
&lt;p&gt;&lt;font face="Courier New"&gt;&amp;nbsp; default:&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; goto Done;&lt;br&gt;&amp;nbsp; }&lt;br&gt;&amp;nbsp; if (index &amp;lt; list.Count)&lt;br&gt;&amp;nbsp; {&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; current = list[index];&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; state = 1;&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; return true;&lt;br&gt;&amp;nbsp; }&lt;br&gt;Done:&lt;br&gt;&amp;nbsp; return false;&lt;br&gt;}&lt;/font&gt;&lt;/p&gt;&lt;/blockquote&gt;&lt;pre&gt;&lt;/pre&gt;
&lt;p&gt;Hm...a switch statement over a variable called state with a number integer case labels.&amp;nbsp; It looks like a state machine and indeed it is.&amp;nbsp; When MoveNext is first called, state is equal to 0, so the state is set to -1 (the "I'm finished" state) and the index is set to 0.&amp;nbsp; Then we check to see if the index is less than the number of things in the list.&amp;nbsp; If so then we set current to the current list element based on the index and set the state to 1.&amp;nbsp; We return true indicating that there is something to consume. 
&lt;p&gt;The second call to MoveNext will run case 1 since the state is equal to 1.&amp;nbsp; It will again set the state to -1 and increment the index.&amp;nbsp; If we still have elements in the list then the current will be set appropriately and the state will be set to 1 (the "we need to check again" state) and true will be returned. 
&lt;p&gt;This continues until there nothing left to consume and false is returned. 
&lt;p&gt;Finally, we found our for loop.&amp;nbsp; It is encoded in the MoveNext.&amp;nbsp; But note that on each call to MoveNext is only computes the part of the for loop that is relevant to realize the next element.&amp;nbsp; It never computes more than it needs to.&amp;nbsp; This is why iterators are an example of deferred execution.&amp;nbsp; When the actual GetElements method was called, no elements were realized at all!&amp;nbsp; Later as MoveNext is called, one element at a time is realized.&amp;nbsp; This of course enables all of sorts of &lt;a href="http://blogs.msdn.com/wesdyer/archive/2007/02/13/the-virtues-of-laziness.aspx"&gt;great scenarios&lt;/a&gt; such as the pay-as-you-go model and the ability to have infinite lists. 
&lt;p&gt;&lt;strong&gt;The Cost of Iterators&lt;/strong&gt; 
&lt;p&gt;Iterators are very performant.&amp;nbsp; In almost all situations that I have encountered they are more than performant enough and they simplify the code drastically as we have seen.&amp;nbsp; But sometimes you can get into trouble. 
&lt;p&gt;Consider the definition of the Concat sequence operator in Linq to Objects.&amp;nbsp; It looks something like this: 
&lt;blockquote&gt;
&lt;p&gt;&lt;font face="Courier New"&gt;static IEnumerable&amp;lt;T&amp;gt; Concat&amp;lt;T&amp;gt;(this IEnumerable&amp;lt;T&amp;gt; sequence1, IEnumerable&amp;lt;T&amp;gt; sequence2)&lt;br&gt;{&lt;br&gt;&amp;nbsp; foreach (var item in sequence1)&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; yield return item;&lt;br&gt;&amp;nbsp; foreach (var item in sequence2)&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; yield return item;&lt;br&gt;}&lt;/font&gt;&lt;/p&gt;&lt;/blockquote&gt;
&lt;p&gt;Let's write a little benchmark to evaluate the performance of concat. 
&lt;blockquote&gt;
&lt;p&gt;&lt;font face="Courier New"&gt;var stopWatch = new Stopwatch();&lt;br&gt;for (int length = 0; length &amp;lt;= 10000; length += 1000)&lt;br&gt;{&lt;br&gt;&amp;nbsp; var list = new[] { 1 };&lt;br&gt;&amp;nbsp; IEnumerable&amp;lt;int&amp;gt; ones = list;&lt;br&gt;&amp;nbsp; for (int i = 0; i &amp;lt; length; ++i)&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; ones = ones.Concat(list); &lt;/font&gt;
&lt;p&gt;&lt;font face="Courier New"&gt;&amp;nbsp; stopWatch.Reset();&lt;br&gt;&amp;nbsp; stopWatch.Start(); &lt;/font&gt;
&lt;p&gt;&lt;font face="Courier New"&gt;&amp;nbsp; foreach (var item in ones) ; &lt;/font&gt;
&lt;p&gt;&lt;font face="Courier New"&gt;&amp;nbsp; stopWatch.Stop();&lt;br&gt;&amp;nbsp; Console.WriteLine("Length: {0} Time: {1}", length, stopWatch.ElapsedMilliseconds);&lt;br&gt;}&lt;/font&gt;&lt;/p&gt;&lt;/blockquote&gt;
&lt;p&gt;The results may be perhaps surprising.&amp;nbsp; The time to evalute the foreach statement is not linearly proportional to the number of concats that are composed together.&amp;nbsp; In fact it is proportional to the square of the number of concats composed together.&lt;/p&gt;&lt;a href="http://blogs.msdn.com/blogfiles/wesdyer/WindowsLiveWriter/TheCostofIterators_A895/image022.png" atomicselection="true"&gt;&lt;img style="border-top-width: 0px; border-left-width: 0px; border-bottom-width: 0px; border-right-width: 0px" height="307" src="http://blogs.msdn.com/blogfiles/wesdyer/WindowsLiveWriter/TheCostofIterators_A895/image0_thumb14.png" width="520" border="0"&gt;&lt;/a&gt; 
&lt;p&gt;Upon closer inspection the reason why is obvious.&amp;nbsp; The time complexity of Concat is O(m+n) where m is the number of items in the first sequence and n is the number of items in the second sequence.&amp;nbsp; But note that in this example, n is always 1.&amp;nbsp; The outermost call is O(m+1).&amp;nbsp; The next call has O((m-1)+1), then O((m-2)+1), ... O(1+1).&amp;nbsp; There are m of these calls so the running time should be O(m^2).&amp;nbsp; Essentially, composing concats together like this causes O(m^2) yield returns to be executed. 
&lt;p&gt;Of course, using a List&amp;lt;T&amp;gt; here and adding on the sequences would have been much more performant because it eliminates the redundant calculations but it would not have been evaluated lazily. 
&lt;p&gt;Iterators are even more fun if the data structure that is being enumerated is more complicated.&amp;nbsp; For example, consider iterating over n-ary trees.&amp;nbsp; Here is a quick definition of a n-ary tree. 
&lt;blockquote&gt;
&lt;p&gt;&lt;font face="Courier New"&gt;&lt;/font&gt;
&lt;p&gt;&lt;font face="Courier New"&gt;class Tree&amp;lt;T&amp;gt;&lt;br&gt;{&lt;br&gt;&amp;nbsp; public T Value { get; private set; }&lt;br&gt;&amp;nbsp; public Tree&amp;lt;T&amp;gt; NextSibling { get; private set; }&lt;br&gt;&amp;nbsp; public Tree&amp;lt;T&amp;gt; FirstChild { get; private set; } &lt;/font&gt;
&lt;p&gt;&lt;font face="Courier New"&gt;&amp;nbsp; public Tree(T value, Tree&amp;lt;T&amp;gt; nextSibling, Tree&amp;lt;T&amp;gt; firstChild)&lt;br&gt;&amp;nbsp; {&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; Value = value;&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; NextSibling = nextSibling;&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; FirstChild = firstChild;&lt;br&gt;&amp;nbsp; } &lt;/font&gt;
&lt;p&gt;&lt;font face="Courier New"&gt;&amp;nbsp; public IEnumerable&amp;lt;Tree&amp;lt;T&amp;gt;&amp;gt; GetChildren()&lt;br&gt;&amp;nbsp; {&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; for (var current = FirstChild; current != null; current = current.NextSibling)&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; yield return current;&lt;br&gt;&amp;nbsp; }&lt;br&gt;}&lt;/font&gt;&lt;/p&gt;&lt;/blockquote&gt;
&lt;p&gt;Now it is easy to define an iterator that performs a preorder traversal of a n-ary tree. 
&lt;blockquote&gt;
&lt;p&gt;&lt;font face="Courier New"&gt;&lt;/font&gt;
&lt;p&gt;&lt;font face="Courier New"&gt;static IEnumerable&amp;lt;T&amp;gt; PreOrderWalk&amp;lt;T&amp;gt;(this Tree&amp;lt;T&amp;gt; tree)&lt;br&gt;{&lt;br&gt;&amp;nbsp; if (tree == null)&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; yield break;&lt;br&gt;&amp;nbsp; yield return tree.Value;&lt;br&gt;&amp;nbsp; foreach (var subTree in tree.GetChildren())&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; foreach (var item in subTree.PreOrderWalk())&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; yield return item;&lt;br&gt;}&lt;/font&gt;&lt;/p&gt;&lt;/blockquote&gt;
&lt;p&gt;Just the way that I like code: clear and concise.&amp;nbsp; The only problem is that the iterator could be more efficient.&amp;nbsp; This may or may not be a problem.&amp;nbsp; In a library it will almost certainly be a problem. 
&lt;p&gt;We can improve the efficiency somewhat by changing the code: 
&lt;blockquote&gt;
&lt;p&gt;&lt;font face="Courier New"&gt;static IEnumerable&amp;lt;T&amp;gt; PreOrderWalk&amp;lt;T&amp;gt;(this Tree&amp;lt;T&amp;gt; tree)&lt;br&gt;{&lt;br&gt;&amp;nbsp; var stack = new Stack&amp;lt;Tree&amp;lt;T&amp;gt;&amp;gt;();&lt;br&gt;&amp;nbsp; if (tree != null)&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; stack.Push(tree);&lt;br&gt;&amp;nbsp; while (stack.Count &amp;gt; 0)&lt;br&gt;&amp;nbsp; {&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; for (var current = stack.Pop(); current != null; current = current.FirstChild)&lt;br&gt;&amp;nbsp; &amp;nbsp; {&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &amp;nbsp; yield return current.Value;&lt;br&gt;&amp;nbsp; &amp;nbsp;&amp;nbsp;&amp;nbsp; if (current.NextSibling != null)&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &amp;nbsp; stack.Push(current.NextSibling);&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; }&lt;br&gt;&amp;nbsp; }&lt;br&gt;}&lt;/font&gt;&lt;/p&gt;&lt;/blockquote&gt;
&lt;p&gt;This second iterator doesn't recursively call iterators thus&amp;nbsp;avoiding both the recursive call and the extra allocations.&amp;nbsp; Instead, it maintains a stack of work to do after the leftmost path has been exhausted.&amp;nbsp; Once the leftmost path has been exhausted then a node is popped off and the leftmost traversal is resumed at that node. 
&lt;p&gt;When we measure the difference, we see that the improvement is noticeable but that the number of nodes, O(b^d) where b is the branching factor and d is depth,&amp;nbsp;dominates the cost of the traversal.&amp;nbsp; In the graph below, the green line indicates the total number of nodes in the tree.&amp;nbsp; The trees have a branching factor of 2. 
&lt;p&gt;&lt;a href="http://blogs.msdn.com/blogfiles/wesdyer/WindowsLiveWriter/TheCostofIterators_A895/image026.png" atomicselection="true"&gt;&lt;img style="border-top-width: 0px; border-left-width: 0px; border-bottom-width: 0px; border-right-width: 0px" height="310" src="http://blogs.msdn.com/blogfiles/wesdyer/WindowsLiveWriter/TheCostofIterators_A895/image0_thumb16.png" width="517" border="0"&gt;&lt;/a&gt; 
&lt;p&gt;So the key takeaway here is that iterators have great performance but as always &lt;em&gt;measure the performance of your code&lt;/em&gt;.&amp;nbsp; If you find that performance is suffering, use a combination of profiling and analysis to find the problem.&amp;nbsp; If the problem is an iterator, you might be able to increase the performance by reworking the iterator as in the n-ary tree case.&amp;nbsp; In other cases, it might be the usage of the iterators as&amp;nbsp;with pathological Concats. 
&lt;p&gt;&lt;strong&gt;One Possibility for Language Improvement (not in Orcas)&lt;/strong&gt; 
&lt;p&gt;The Concat sequence operator is interesting because there is a lot of code that is seemingly redundant.&amp;nbsp; It takes two sequences and then has to iterate over them and yield their elements.&amp;nbsp; It's like it needs to expand their insides just to package them up together again.&amp;nbsp; As we have seen this doesn't lead to the best performance and the code is overly verbose. 
&lt;p&gt;Bart Jacobs, Erik Meijer, Frank Piessens, and Wolfram Shulte wrote &lt;a href="http://citeseer.ist.psu.edu/cache/papers/cs2/355/http:zSzzSzwww.cs.kuleuven.ac.bezSz~frankzSzPAPERSzSzFTfJP2005.pdf/iterators-revisited-proof-rules.pdf"&gt;a very interesting paper&lt;/a&gt; on a possible language improvement that would improve both the usability and the performance of iterators.&amp;nbsp; The second half of the paper details what they call nested iterators which avoid the multiple evaluation problem of the composed Concats and implicitly keep an internal stack like the modified n-ary tree iterator. 
&lt;p&gt;For example with this language feature, the Concat sequence operator would look something like this: 
&lt;blockquote&gt;
&lt;p&gt;&lt;font face="Courier New"&gt;static IEnumerable&amp;lt;T&amp;gt; Concat&amp;lt;T&amp;gt;(this IEnumerable&amp;lt;T&amp;gt; sequence1, IEnumerable&amp;lt;T&amp;gt; sequence2)&lt;br&gt;{&lt;br&gt;&amp;nbsp; yield foreach sequence1;&lt;br&gt;&amp;nbsp; yield foreach sequence2;&lt;br&gt;}&lt;/font&gt;&lt;/p&gt;&lt;/blockquote&gt;
&lt;p&gt;Notice that the code is simplier and it is also more performant. 
&lt;p&gt;A&amp;nbsp;programmer could use yield return, yield break, and yield foreach in the same iterator.&amp;nbsp; An iterator FromTo can be defined recursively as follows: 
&lt;blockquote&gt;
&lt;p&gt;&lt;font face="Courier New"&gt;static IEnumerable&amp;lt;int&amp;gt; FromTo(int b, int e)&lt;br&gt;{&lt;br&gt;&amp;nbsp; if (b &amp;gt; e)&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; yield break;&lt;br&gt;&amp;nbsp; yield return b;&lt;br&gt;&amp;nbsp; yield foreach FromTo(b + 1, e);&lt;br&gt;}&lt;/font&gt;&lt;/p&gt;&lt;/blockquote&gt;
&lt;p&gt;If instead of the yield foreach, there was the foreach expansion that yielded each result then the FromTo method would suffer from quadratic performance; however, with nested iterators the performance would be linear. 
&lt;p&gt;&lt;a href="http://blogs.msdn.com/blogfiles/wesdyer/WindowsLiveWriter/TheCostofIterators_A895/image031.png" atomicselection="true"&gt;&lt;img style="border-top-width: 0px; border-left-width: 0px; border-bottom-width: 0px; border-right-width: 0px" height="368" src="http://blogs.msdn.com/blogfiles/wesdyer/WindowsLiveWriter/TheCostofIterators_A895/image0_thumb19.png" width="558" border="0"&gt;&lt;/a&gt; 
&lt;p&gt;The next post will pick up on understanding the performance of Linq to objects queries. 
&lt;img src="http://blogs.msdn.com/aggbug.aspx?PostID=1935848" width="1" height="1"&gt;</description><category domain="http://blogs.msdn.com/wesdyer/archive/tags/Programming/default.aspx">Programming</category><category domain="http://blogs.msdn.com/wesdyer/archive/tags/C_2300_/default.aspx">C#</category><category domain="http://blogs.msdn.com/wesdyer/archive/tags/Design+Patterns/default.aspx">Design Patterns</category></item><item><title>Performance Engineering</title><link>http://blogs.msdn.com/wesdyer/archive/2007/03/20/performance-engineering.aspx</link><pubDate>Tue, 20 Mar 2007 12:52:56 GMT</pubDate><guid isPermaLink="false">91d46819-8472-40ad-a661-2c78acb4018c:1918500</guid><dc:creator>wesdyer</dc:creator><slash:comments>8</slash:comments><comments>http://blogs.msdn.com/wesdyer/comments/1918500.aspx</comments><wfw:commentRss>http://blogs.msdn.com/wesdyer/commentrss.aspx?PostID=1918500</wfw:commentRss><description>&lt;p&gt;Recently, many people have asked me about the performance of Linq.&amp;nbsp; The questions have ranged from the broad, "How can I analyze the performance of code using Linq?", to the very specific, "Why is the performance of this code sample not what I expected?"&lt;/p&gt; &lt;p&gt;I want to address these questions.&amp;nbsp;&amp;nbsp;So before I dive into some of them individually, I want to set up a framework for discussions about performance.&amp;nbsp; The framework consists of ideas that are well known and understood and yet often when people talk or think about performance they forget about them.&lt;/p&gt; &lt;p&gt;Performance&amp;nbsp;is&amp;nbsp;critical to the success of any application and &lt;em&gt;engineering&lt;/em&gt; performance is a fundamental part of what developers should be doing on a day to day basis.&amp;nbsp; Great performance doesn't just happen.&amp;nbsp; It must have requirements, be designed, implemented, and tested just like any other feature.&amp;nbsp; Individuals and teams must foster a culture of performance.&lt;/p&gt; &lt;p&gt;&lt;strong&gt;Performance Requirements&lt;/strong&gt;&lt;/p&gt; &lt;p&gt;Rico Mariani wrote a great post about why performance must be &lt;a href="http://blogs.msdn.com/ricom/archive/2006/12/21/do-performance-analysis-in-context.aspx"&gt;measured in context&lt;/a&gt;.&amp;nbsp; That means that performance goals should be made in relation to what the user sees and cares about.&amp;nbsp; Then when possible these goals should be translated into more low-level goals that are easier to quantify and directly measure, but never take your eye of the original goals.&amp;nbsp; Many times when performance is tuned in one dimension it can degrade in other dimensions.&amp;nbsp; It is like trying to cram a whole bunch of stuff into a tiny space, you may push it in here but it pops out over there.&amp;nbsp; So how does a programmer know which dimension is most important?&amp;nbsp; Consider the performance in context.&amp;nbsp; Furthermore, the performance tuning that a programmer makes might not even matter when considered in context.&amp;nbsp; So spend your time where in counts.&amp;nbsp;&amp;nbsp;Finally, it is much easier to consider trade-offs between performance requirements and other requirements when the performance requirements are in context.&amp;nbsp; Set up a performance budget in terms that are material and important&amp;nbsp;to the customer.&lt;/p&gt; &lt;p&gt;&lt;strong&gt;Designing for Performance&lt;/strong&gt;&lt;/p&gt; &lt;p&gt;Designing for performance is important.&amp;nbsp; Many performance problems can be fixed as they are identified later, but some are deeply rooted in poor design choices that were made early on that are difficult to resolve later.&amp;nbsp; However, care must be taken because often these poor design choices were made for the sake of "better performance".&amp;nbsp; For example, in an app where there is a lot of data parallelism, it doesn't make a lot of sense to make it so complex with stateful&amp;nbsp;operations that it precludes concurrency.&lt;/p&gt; &lt;p&gt;Most of these poor design choices are caused by the design not solving the right problem (performance requirements)&amp;nbsp;or because the requirements changed over time and the earlier design made it difficult to adapt to the new requirements.&lt;/p&gt; &lt;p&gt;&lt;strong&gt;Understanding Performance&lt;/strong&gt;&lt;/p&gt; &lt;p&gt;There are at least two basic tools for understanding performance.&lt;/p&gt; &lt;p&gt;&lt;strong&gt;1.&amp;nbsp; &lt;/strong&gt;&lt;a href="http://en.wikipedia.org/wiki/Asymptotic_analysis"&gt;&lt;strong&gt;Asymptotic Analysis&lt;/strong&gt;&lt;/a&gt;&lt;/p&gt; &lt;p&gt;I am sure that my readers know and love asymptotic analysis.&amp;nbsp; It is so important that developers know what they are doing when they call a System.* function, which&amp;nbsp;has an O(n) time complexity, n times -- O(n^2) behavior.&amp;nbsp; Know what is going on in terms of both space and time.&lt;/p&gt; &lt;p&gt;&lt;strong&gt;2.&amp;nbsp; Benchmarks / Profilers&lt;/strong&gt;&lt;/p&gt; &lt;p&gt;So often when a performance problem exists, developers will convince themselves that they know what the problem is&amp;nbsp;without accurately measuring the behavior of the system.&amp;nbsp; They will proceed to "fix" the problem only to discover that what they thought would be of great benefit is in fact unimportant.&lt;/p&gt; &lt;p&gt;I've done that.&amp;nbsp; When C# 1.0 was in beta back in 2000, I was working at a small company that decided to try out this new .NET stuff.&amp;nbsp; My first application was a&amp;nbsp;good sized&amp;nbsp;application that including a custom scripting engine inside of it.&amp;nbsp; The performance wasn't great and so I set about fixing it.&amp;nbsp; I was sure that I knew what the problem was and so I began improving some algorithms in various complex parts of the system.&amp;nbsp; But I found that it didn't help matters at all.&lt;/p&gt; &lt;p&gt;At this point, I broke out a profiler and began measuring the actual behavior of the system.&amp;nbsp; The suprising result (at the time) was that pretty much all of the performance problems came from a small loop that was building up the text buffer for the scripting engine.&amp;nbsp; It was using the + operator on strings.&amp;nbsp; Since this was my first .NET application, I had no idea that concatenating hundreds of thousands of strings was a bad idea.&lt;/p&gt; &lt;p&gt;When I changed the code to use a StringBuilder instead, it sailed.&amp;nbsp; I made a few other improvements (all of which were targeted and very small), and the application was running fine.&lt;/p&gt; &lt;p&gt;Now the point of all of this is &lt;em&gt;not&lt;/em&gt; that the + operator on strings should not be used.&amp;nbsp; If that were true then we would make the C# compiler issue a warning when you used it.&amp;nbsp; The point is that a programmer should be aware of the costs and tradeoffs involved with a programming decision and act accordingly.&amp;nbsp; Measurement is a powerful tool.&amp;nbsp; Knowing where the problems lie is&amp;nbsp;the key to success.&amp;nbsp; Measure early and often.&lt;/p&gt; &lt;p&gt;The result of profiling is a large set of various statistics about an application.&amp;nbsp; If the measurements are taken in context then they are a powerful tool.&amp;nbsp; As with any statistics, what is being measured is as important as the actual measurement.&lt;/p&gt; &lt;p&gt;Analyzing an application is very rewarding.&amp;nbsp; You are able to see the material benefits of any improvement in a very quantitative way.&amp;nbsp; Apply the scientific method in the process of analyzing a problem.&amp;nbsp; Once you suspect you know what the problem is then consider it the hypothesis and then prove it by observing the data (profiling data)&amp;nbsp;from an operation (the suspect code) across various trials.&lt;/p&gt; &lt;p&gt;Try to think big and understand not only what is the problem but why it is a problem.&amp;nbsp; The best solutions attack not only the symptoms but the fundamental causes of the problem.&amp;nbsp; Look to understand the nature of the problem.&lt;/p&gt; &lt;p&gt;&lt;strong&gt;Some Good Performance Resources&lt;/strong&gt;&lt;/p&gt; &lt;p&gt;&lt;a href="http://blogs.msdn.com/ricom/"&gt;Rico Mariani's (Visual Studio&amp;nbsp;Performance Architect) Blog&lt;/a&gt;&lt;/p&gt; &lt;p&gt;&lt;a href="http://blogs.msdn.com/vancem/"&gt;Vance Morrison's (CLR Performance Architect) Blog&lt;/a&gt;&lt;/p&gt;&lt;img src="http://blogs.msdn.com/aggbug.aspx?PostID=1918500" width="1" height="1"&gt;</description><category domain="http://blogs.msdn.com/wesdyer/archive/tags/Programming/default.aspx">Programming</category></item><item><title>Extending the World</title><link>http://blogs.msdn.com/wesdyer/archive/2007/03/09/extending-the-world.aspx</link><pubDate>Fri, 09 Mar 2007 14:06:29 GMT</pubDate><guid isPermaLink="false">91d46819-8472-40ad-a661-2c78acb4018c:1843300</guid><dc:creator>wesdyer</dc:creator><slash:comments>26</slash:comments><comments>http://blogs.msdn.com/wesdyer/comments/1843300.aspx</comments><wfw:commentRss>http://blogs.msdn.com/wesdyer/commentrss.aspx?PostID=1843300</wfw:commentRss><description>&lt;p&gt;When people think of C# 3.0 and Linq, they commonly think of queries and databases.&amp;nbsp; The phenomenal work of the &lt;a href="http://blogs.msdn.com/mattwar/"&gt;Linq&lt;/a&gt; &lt;a href="http://forums.microsoft.com/MSDN/Search/Search.aspx?words=keith+farmer&amp;amp;localechoice=9&amp;amp;SiteID=1&amp;amp;searchscope=forumscope&amp;amp;ForumID=123"&gt;to&lt;/a&gt; &lt;a href="http://blogs.madtechnology.net/blogs/chris/"&gt;SQL&lt;/a&gt; &lt;a href="http://blogs.msdn.com/jomo_fisher/"&gt;guys&lt;/a&gt; provides ample reason to think of it this way; nevertheless, C# 3.0 and Linq&amp;nbsp;are really much much more.&amp;nbsp; I have discussed a number of things that can be done with lambdas, expression trees, and queries&amp;nbsp;and will continue to do so but I want to pause and discuss a little gem that is often overlooked in C# 3.0.&amp;nbsp; This new language feature has fundamentally changed both the way that I work in C# and &lt;a href="http://antwrp.gsfc.nasa.gov/apod/ap971026.html"&gt;my view of the world&lt;/a&gt;.&amp;nbsp; I've been using it a lot without ever drawing attention explicitly to it.&amp;nbsp; At least &lt;a href="http://base4.net/Blog.aspx?ID=334"&gt;one reader&lt;/a&gt; noticed it and the possibilities it opens up and at least a couple of readers want an expanded version of it without even knowing it.&lt;/p&gt; &lt;p&gt;So what is the feature?&amp;nbsp; It's extension methods.&lt;/p&gt; &lt;p&gt;At first glance they don't look very special.&amp;nbsp; I mean really, all they are is one extra token in the definition of a static method inside of a static class.&lt;/p&gt; &lt;blockquote&gt; &lt;p&gt;&lt;font face="Courier New"&gt;static class Foo {&lt;/font&gt;&lt;/p&gt; &lt;p&gt;&lt;font face="Courier New"&gt;&amp;nbsp; public static Bar Baz(&lt;font color="#ff8000"&gt;this&lt;/font&gt; Qux Quux) { ...&lt;/font&gt;&lt;/p&gt;&lt;/blockquote&gt; &lt;p&gt;But as is usually the case, it's the semantics that are more interesting than the particular syntax.&lt;/p&gt; &lt;p&gt;The first argument of an extension method (the argument marked with this) is the implicit receiver of the method.&amp;nbsp; The extension method &lt;em&gt;appears&lt;/em&gt; to be an instance method on the receiver but it is not.&amp;nbsp; Therefore, it cannot access private or protected members of the receiver.&lt;/p&gt; &lt;p&gt;For example, let's say that I detested the fact that the framework doesn't have a ToInt method defined on string.&amp;nbsp; Now, I can just provide my own:&lt;/p&gt; &lt;blockquote&gt; &lt;p&gt;&lt;font face="Courier New"&gt;public static int ToInt(this string s)&lt;br&gt;{&lt;br&gt;&amp;nbsp; return int.Parse(s);&lt;br&gt;}&lt;/font&gt;&lt;/p&gt;&lt;/blockquote&gt; &lt;p&gt;And I can then call it as:&lt;/p&gt; &lt;blockquote&gt; &lt;p&gt;&lt;font face="Courier New"&gt;"5".ToInt()&lt;/font&gt;&lt;/p&gt;&lt;/blockquote&gt; &lt;p&gt;The compiler transforms the call into:&lt;/p&gt; &lt;blockquote&gt; &lt;p&gt;&lt;font face="Courier New"&gt;ToInt("5")&lt;/font&gt;&lt;/p&gt;&lt;/blockquote&gt; &lt;p&gt;Notice how it turns it outside out.&amp;nbsp; So if I have three extension methods A, B, and C&lt;/p&gt; &lt;blockquote&gt; &lt;p&gt;&lt;font face="Courier New"&gt;x.A().B().C()&lt;/font&gt;&lt;/p&gt;&lt;/blockquote&gt; &lt;p&gt;The calls get turned into&lt;/p&gt; &lt;blockquote&gt; &lt;p&gt;&lt;font face="Courier New"&gt;C(B(A(x)))&lt;/font&gt;&lt;/p&gt;&lt;/blockquote&gt; &lt;p&gt;While all of this explains how extension methods work, it doesn't explain why they are so cool.&lt;/p&gt; &lt;p&gt;A few months back, I was reading various online content related to C# 3.0.&amp;nbsp; I wanted to get a feel for what customers were feeling and incorporate it as much as possible into the product.&amp;nbsp; In the process, I came across an interesting post, &lt;a href="http://lukeplant.me.uk/blog.php?id=1107301645"&gt;Why learning Haskell/Python makes you a worse programmer&lt;/a&gt;.&amp;nbsp; The author argues that learning a language like Python or Haskell can make things more difficult for you if your day job is programming in a language like C#.&lt;/p&gt; &lt;p&gt;I sympathize with what the author has to say and have had to spend enough time programming in languages that I didn't like that I think that I understand the pain.&lt;/p&gt; &lt;p&gt;That said, I hope that the author (and others who feel like him) will be pleasantly surprised by C# 3.0.&amp;nbsp; For example, let's look at his example of painful programming:&lt;/p&gt; &lt;blockquote&gt; &lt;p&gt;"I have a list of Foo objects, each having a Description() method that returns a string. I need to concatenate all the non-empty descriptions, inserting newlines between them."&lt;/p&gt;&lt;/blockquote&gt; &lt;p&gt;In Python, he says that he would write:&lt;/p&gt; &lt;blockquote&gt; &lt;p&gt;&lt;font face="Courier New"&gt;"\n".join(foo.description() for foo in mylist if foo.description() != "")&lt;/font&gt;&lt;/p&gt;&lt;/blockquote&gt; &lt;p&gt;In Haskell, his solution looks like:&lt;/p&gt; &lt;blockquote&gt; &lt;p&gt;&lt;font face="Courier New"&gt;concat $ List.intersperse "\n" $ filter (/= "") $ map description mylist&lt;/font&gt;&lt;/p&gt;&lt;/blockquote&gt; &lt;p&gt;These both look like reasonable code and I rather like them.&amp;nbsp; Fortunately, you can express them in C# 3.0.&amp;nbsp; Here is the code that looks like the Python solution.&lt;/p&gt; &lt;blockquote&gt; &lt;p&gt;&lt;font face="Courier New"&gt;"\n".Join(from x in mylist where x.Description != "" select x.Description)&lt;/font&gt;&lt;/p&gt;&lt;/blockquote&gt; &lt;p&gt;And here is the code that is closer to his Haskell solution:&lt;/p&gt; &lt;blockquote&gt; &lt;p&gt;&lt;font face="Courier New"&gt;mylist.Where(x =&amp;gt; x.Description != "").Select(x =&amp;gt; x.Description).Intersperse("\n").Concat();&lt;/font&gt;&lt;/p&gt;&lt;/blockquote&gt; &lt;p&gt;At this point, some will protest that there is no Join instance method on string and there is no Intersperse defined on IEnumerable&amp;lt;T&amp;gt;.&amp;nbsp; And for that matter, how can you define a method on an interface in the first place?&amp;nbsp; Of course, extension methods are the answer to all of these questions.&lt;/p&gt; &lt;blockquote&gt; &lt;p&gt;&lt;font face="Courier New"&gt;public static string Join(this string s, IEnumerable&amp;lt;string&amp;gt; ss)&lt;br&gt;{&lt;br&gt;&amp;nbsp; return string.Join(s, ss.ToArray());&lt;br&gt;}&lt;/font&gt;&lt;/p&gt; &lt;p&gt;&lt;font face="Courier New"&gt;&lt;/font&gt;&lt;font face="Courier New"&gt;&lt;br&gt;public static IEnumerable&amp;lt;T&amp;gt; Intersperse&amp;lt;T&amp;gt;(this IEnumerable&amp;lt;T&amp;gt; sequence, T value)&lt;br&gt;{&lt;br&gt;&amp;nbsp; bool first = true;&lt;br&gt;&amp;nbsp; foreach (var item in sequence)&lt;br&gt;&amp;nbsp; {&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; if (first)&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; first = false;&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; else&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; yield return value;&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; yield return item;&lt;br&gt;&amp;nbsp; }&lt;br&gt;}&lt;/font&gt;&lt;/p&gt;&lt;/blockquote&gt; &lt;p&gt;It is as if these methods were defined on the receiver to begin with.&amp;nbsp; At this point the realization sets in: a whole new mode of development has been opened up.&lt;/p&gt; &lt;p&gt;Typically for a given problem, a programmer is accustomed to building up a solution until it finally meets the requirements.&amp;nbsp; Now, it is possible to extend the world to meet the solution instead of solely just building up until we get to it.&amp;nbsp; That library doesn't provide what you need, just extend the library to meet your needs.&lt;/p&gt; &lt;p&gt;I find myself switching between the two modes frequently: building up some functionality here and extending some there.&amp;nbsp; In fact, these days I find that I often start with extension methods and then when certain patterns begin to emerge then I factor those into classes.&lt;/p&gt; &lt;p&gt;It also makes some interesting styles of programming&amp;nbsp;easier.&amp;nbsp; I am sure it has some name, but since I don't know what it is I'll call it data interface programming.&amp;nbsp; First we declare an immutable interface that includes only data elements.&lt;/p&gt; &lt;blockquote&gt; &lt;p&gt;&lt;font face="Courier New"&gt;interface ICustomer&lt;br&gt;{&lt;br&gt;&amp;nbsp; string Name { get; }&lt;br&gt;&amp;nbsp; int ID { get; }&lt;br&gt;} &lt;/font&gt;&lt;/p&gt;&lt;/blockquote&gt; &lt;p&gt;Then, we declare an inaccessible implementation of ICustomer that allows customers to be created through a factory that only exposes the immutable version.&lt;/p&gt; &lt;blockquote&gt; &lt;p&gt;&lt;font face="Courier New"&gt;class Factory&lt;br&gt;{&lt;br&gt;&amp;nbsp; class Customer : ICustomer&lt;br&gt;&amp;nbsp; {&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; public string Name { get; set; }&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; public int ID { get; set; }&lt;br&gt;&amp;nbsp; } &lt;/font&gt; &lt;p&gt;&lt;font face="Courier New"&gt;&amp;nbsp; public static ICustomer CreateCustomer(int id, string name)&lt;br&gt;&amp;nbsp; {&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; return new Customer { ID = id, Name = name };&lt;br&gt;&amp;nbsp; }&lt;br&gt;}&lt;/font&gt;&lt;/p&gt;&lt;/blockquote&gt; &lt;p&gt;Then we can declare behavior through extension methods.&lt;/p&gt; &lt;blockquote&gt; &lt;p&gt;&lt;font face="Courier New"&gt;public static string GetAlias(this ICustomer customer)&lt;br&gt;{&lt;br&gt;&amp;nbsp; return customer.Name + customer.ID.ToString();&lt;br&gt;}&lt;/font&gt;&lt;/p&gt;&lt;/blockquote&gt; &lt;p&gt;And finally, we can use the behavior.&lt;/p&gt; &lt;blockquote&gt; &lt;p&gt;&lt;font face="Courier New"&gt;var customer = Factory.CreateCustomer(4, "wes");&lt;br&gt;Console.WriteLine(customer.GetAlias());&lt;/font&gt;&lt;/p&gt;&lt;/blockquote&gt; &lt;p&gt;All of this may seem like a round about way to declare an&amp;nbsp;immutable abstract base class with various derived classes.&amp;nbsp; But there is a fundamental difference, &lt;em&gt;the interface and behavior can change depending upon which extension methods are in scope&lt;/em&gt;.&amp;nbsp; So one part of the program or system can treat them one way and another can have an entirely different view of things.&lt;/p&gt; &lt;p&gt;Of course, what I really want to be able to do (and we don't do it yet) is something like:&lt;/p&gt; &lt;blockquote&gt; &lt;p&gt;&lt;font face="Courier New"&gt;var customer = new ICustomer { ID = 4, Name = "wes" };&lt;br&gt;Console.WriteLine(customer.GetAlias());&lt;/font&gt;&lt;/p&gt;&lt;/blockquote&gt; &lt;p&gt;And then I skip the whole Factory thing all together.&amp;nbsp; The customer is immutable and the definition of the type is short and sweet.&amp;nbsp; All of the work of done by the compiler which incidentally doesn't need the factory because it can name mangle the implementation class and provide customized constructors automatically.&amp;nbsp; But I digress, hopefully we can do something like that in the future.&lt;/p&gt; &lt;p&gt;Of course&amp;nbsp;extension methods don't make the traditional techniques inapplicable, they are still as useful as ever.&amp;nbsp; As with all design considerations, there are trade-offs involved.&amp;nbsp; Care must be taken to manage extension methods so that chaos doesn't ensue, but when they are used appropriately they are&amp;nbsp;fantastically useful.&lt;/p&gt; &lt;p&gt;As I have been writing C# code, I have accumulated a library of useful extension methods and I encourage you to do the same thing so that the ideas that you think roll naturally off of your fingertips.&lt;/p&gt;&lt;img src="http://blogs.msdn.com/aggbug.aspx?PostID=1843300" width="1" height="1"&gt;</description><category domain="http://blogs.msdn.com/wesdyer/archive/tags/C_2300_/default.aspx">C#</category></item><item><title>Immutability, Purity, and Referential Transparency</title><link>http://blogs.msdn.com/wesdyer/archive/2007/03/01/immutability-purity-and-referential-transparency.aspx</link><pubDate>Thu, 01 Mar 2007 10:44:12 GMT</pubDate><guid isPermaLink="false">91d46819-8472-40ad-a661-2c78acb4018c:1777705</guid><dc:creator>wesdyer</dc:creator><slash:comments>32</slash:comments><comments>http://blogs.msdn.com/wesdyer/comments/1777705.aspx</comments><wfw:commentRss>http://blogs.msdn.com/wesdyer/commentrss.aspx?PostID=1777705</wfw:commentRss><description>&lt;p&gt;&lt;/p&gt; &lt;p&gt;How often do you write code that just works?&amp;nbsp; It seems to happen so rarely&amp;nbsp;that I find myself suspicious if&amp;nbsp;code does just work.&amp;nbsp; When was the last time that you wrote a non-trivial program that had no compile errors&amp;nbsp;on the first try and then ran fine as well?&amp;nbsp; If it happened recently then congratulations.&amp;nbsp; If it hasn't then join the club.&amp;nbsp; Admittedly, most programmers don't just write a whole program and then submit it to a compiler and&amp;nbsp;a&amp;nbsp;test harness&amp;nbsp;to see if it works.&amp;nbsp; Typically it is built incrementally: a function here, a class there, testing all the time.&amp;nbsp; &lt;a href="http://en.wikipedia.org/wiki/REPL"&gt;Code-Compile-Test&lt;/a&gt;...rinse and repeat.  &lt;p&gt;I recently read a post where the author describes &lt;a href="http://www.haskell.org/haskellwiki/Why_Haskell_just_works"&gt;why Haskell programs just seem to work&lt;/a&gt;.&amp;nbsp; It got me thinking about my own experience in Haskell.&amp;nbsp; One of the most interesting things about Haskell is that many programmers don't use a&amp;nbsp;debugger (&lt;a href="http://haskell.org/haskellwiki/GHC/GHCi_debugger"&gt;GHCi does have one&lt;/a&gt;).&amp;nbsp; It seems that the impulse to break out the debugger to better understand code occurs&amp;nbsp;far less than in other languages.&amp;nbsp;  &lt;p&gt;Can you imagine working in C# without a debugger?&amp;nbsp; So why is it that many Haskell users seem to get along without a debugger? &lt;p&gt;&lt;strong&gt;A Tale of Two Sorts&lt;/strong&gt;  &lt;p&gt;Consider writing a function&amp;nbsp;that sorts an IEnumerable&amp;lt;T&amp;gt; using the &lt;a href="http://en.wikipedia.org/wiki/Quicksort"&gt;quicksort algorithm&lt;/a&gt;.&amp;nbsp; Here is one&amp;nbsp;possible implementation:  &lt;blockquote&gt; &lt;p&gt;&lt;font face="Courier New"&gt;static IEnumerable&amp;lt;T&amp;gt; QuickSort&amp;lt;T&amp;gt;(this IEnumerable&amp;lt;T&amp;gt; sequence) where T : IComparable&amp;lt;T&amp;gt;&lt;br&gt;{&lt;br&gt;&amp;nbsp; var array = sequence.ToArray();&lt;br&gt;&amp;nbsp; QuickSort(array, 0, array.Length - 1);&lt;br&gt;&amp;nbsp; return array;&lt;br&gt;} &lt;/font&gt; &lt;p&gt;&lt;font face="Courier New"&gt;static void QuickSort&amp;lt;T&amp;gt;(this T[] array, int start, int end) where T : IComparable&amp;lt;T&amp;gt;&lt;br&gt;{&lt;br&gt;&amp;nbsp; if (end - start &amp;lt; 1)&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; return;&lt;br&gt;&amp;nbsp; var pivot = array[start];&lt;br&gt;&amp;nbsp; var j = start;&lt;br&gt;&amp;nbsp; for (var i = start + 1; i &amp;lt;= end; ++i)&lt;br&gt;&amp;nbsp; {&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; if (array[i].CompareTo(pivot) &amp;lt; 0)&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; {&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; ++j;&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; var temp = array[j];&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; array[j] = array[i];&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; array[i] = temp;&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; }&lt;br&gt;&amp;nbsp; }&lt;br&gt;&amp;nbsp; array[start] = array[j];&lt;br&gt;&amp;nbsp; array[j] = pivot;&lt;br&gt;&amp;nbsp; QuickSort(array, start, j - 1);&lt;br&gt;&amp;nbsp; QuickSort(array, j + 1, end);&lt;br&gt;}&lt;/font&gt;&lt;/p&gt;&lt;/blockquote&gt; &lt;p&gt;Now imagine that ++j was in the wrong place (at the end of the block).&amp;nbsp; The output of sorting  &lt;blockquote&gt; &lt;p&gt;4, 3, 6, 9, 1, 0, 2, 7, 5, 8&lt;/p&gt;&lt;/blockquote&gt; &lt;p&gt;would be &lt;blockquote&gt; &lt;p&gt;4, 4, 4, 4, 4, 9, 6, 7, 7, 8&lt;/p&gt;&lt;/blockquote&gt; &lt;p&gt;Clearly this isn't right.&amp;nbsp; So after a quick scan of the code, most programmers would attach a debugger to see what is going on.  &lt;p&gt;The programmer might then step through the code until some state transition ends in a corrupt state.&amp;nbsp; Hopefully the programmer&amp;nbsp;understands the &lt;em&gt;intent&lt;/em&gt; of the code so that a fix can be issued to bring the implementation in line with the intent.  &lt;p&gt;Contrast the previous definition of quicksort with the following definition:  &lt;blockquote&gt; &lt;p&gt;&lt;font face="Courier New"&gt;static IEnumerable&amp;lt;T&amp;gt; QuickSort&amp;lt;T&amp;gt;(this IEnumerable&amp;lt;T&amp;gt; sequence) where T : IComparable&amp;lt;T&amp;gt;&lt;br&gt;{&lt;br&gt;&amp;nbsp; if (!sequence.Any())&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; return sequence;&lt;br&gt;&amp;nbsp; var pivot = sequence.First();&lt;br&gt;&amp;nbsp; var remaining = sequence.Skip(1);&lt;br&gt;&amp;nbsp;&amp;nbsp;return ((from x in remaining where x.CompareTo(pivot) &amp;lt; 0 select x).QuickSort())&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; .Concat(pivot)&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; .Concat((from x in remaining where x.CompareTo(pivot) &amp;gt;= 0 select x).QuickSort());&lt;br&gt;}&lt;/font&gt;&lt;/p&gt;&lt;/blockquote&gt; &lt;p&gt;What do you notice that is different besides the number of lines of code? &lt;p&gt;The first definition creates an array and then does in an place quicksort on the array, destructively updating the contents.&amp;nbsp; It creates several temporary values (i, j)&amp;nbsp;needed to store intermediate results.&amp;nbsp; If&amp;nbsp;a programmer&amp;nbsp;hasn't written the algorithm recently then chances are that the code&amp;nbsp;will contain at least an&amp;nbsp;one off by one error&amp;nbsp;or some other similar error.&amp;nbsp; I've seen too many people do poorly on whiteboards on similar&amp;nbsp;problems&amp;nbsp;(where incidentally there is no debugger, syntax highlighting, or intellisense) to believe that most people would just get it right the first time.  &lt;p&gt;The second definition &lt;em&gt;does not modify any data&lt;/em&gt;.&amp;nbsp; Sure it makes assignments but each of these assignments are to a newly introduced variable.&amp;nbsp; These variables are really just aliases for the expressions that are assigned to them because the expressions are side-effect free.&amp;nbsp; Furthermore, the second definition is essentially just a brief description of what the quicksort is rather than a step by&amp;nbsp;step description of how it is accomplished.  &lt;p&gt;At this point, some people will probably be thinking, "But isn't the first approach so much faster than the second approach?" &lt;p&gt;Maybe, maybe not.&amp;nbsp; Perhaps it doesn't even matter. &lt;p&gt;I think it is important to&amp;nbsp;use the following principle:&amp;nbsp; &lt;em&gt;Make it correct, make it clear, make it concise, make&amp;nbsp;it fast.&amp;nbsp; In that order.&lt;/em&gt;&amp;nbsp; &lt;p&gt;If I find that the code in question&amp;nbsp;is not performant enough given the user scenarios that we need to support or if the code is overly complex for the sake of eliminating side-effects then I consider adding state.&amp;nbsp; But note that if I wanted to introduce state to our quicksort, I could do it in two different ways: contained within the quicksort function or&amp;nbsp;exposed to the caller of quicksort.&amp;nbsp; This is somewhat analogous to calling either the first function or the second function in the first definition of quicksort.&amp;nbsp; If the state is exposed then quicksort could do an in-place sort on&amp;nbsp;the&amp;nbsp;collection passed to&amp;nbsp;the quicksort function.&amp;nbsp; Alternatively, quicksort could simply return a new&amp;nbsp;collection that is sorted and not update the original collection.&amp;nbsp; This leads to the second principle:  &lt;blockquote&gt; &lt;p&gt;&lt;em&gt;Write&amp;nbsp;side-effect free&amp;nbsp;code.&amp;nbsp; If&amp;nbsp;side-effects are required then confine&amp;nbsp;them to the smallest scope possible.&lt;/em&gt;&lt;/p&gt;&lt;/blockquote&gt; &lt;p&gt;Most programmers have been following this to some extent for years.&amp;nbsp; We all know that generally it is not a good idea to use &lt;a href="http://en.wikipedia.org/wiki/Global_variables"&gt;global variables&lt;/a&gt;.&amp;nbsp; This is basically the extreme of exposing&amp;nbsp;side-effects (the global scope).&amp;nbsp; Unfortunately, many of the programmers who don't use global variables&amp;nbsp;don't realize that the same principles apply to fields, properties, parameters, and variables&amp;nbsp;on a more limited scale: don't mutate them unless you have a good reason.&amp;nbsp; &lt;p&gt;&lt;strong&gt;A Little Story about State&lt;/strong&gt;  &lt;p&gt;Some time ago,&amp;nbsp;I wrote &lt;a href="http://blogs.msdn.com/wesdyer/archive/2006/01/13/saving-the-state-of-enumerators.aspx"&gt;a post&lt;/a&gt; about a way to save the state of an IEnumerator&amp;lt;T&amp;gt;.&amp;nbsp; What I didn't tell is the story behind the post.  &lt;p&gt;I was writing&amp;nbsp;a managed lexer and parser generator.&amp;nbsp; The system is pretty&amp;nbsp;neat and includes things like &lt;a href="http://en.wikipedia.org/wiki/GLR_parser"&gt;GLR parsing&lt;/a&gt;, automatic inference of the &lt;a href="http://en.wikipedia.org/wiki/Abstract_syntax_tree"&gt;AST&lt;/a&gt; types, &lt;a href="http://lambda-the-ultimate.org/node/1018"&gt;automatic error recovery&lt;/a&gt;, and whole slew of other features.&amp;nbsp; The parser takes&amp;nbsp;an IEnumerable&amp;lt;IToken&amp;gt; in order to decouple the lexer from the parser.&amp;nbsp; However, for many of the features of the parser, it needs a way to save the state the of the underlying token stream and possibly restore it at a later time after more of the stream has been consumed.  &lt;p&gt;Originally, I wrote a MarkableEnumerator&amp;lt;T&amp;gt; which wrapped an IEnumerator&amp;lt;T&amp;gt; and consumed the input.&amp;nbsp; Clients could request a mark which they could then restore at a later point.&amp;nbsp; If they did this then the MarkableEnumerator&amp;lt;T&amp;gt; would continue at the restored point when MoveNext was called again.&amp;nbsp; This little piece of software (about 100 lines of code)&amp;nbsp;caused &lt;a href="http://blogs.msdn.com/cyrusn/"&gt;Cyrus&lt;/a&gt; and&amp;nbsp;me lots of trouble.&amp;nbsp; It was super complicated because it was heavily optimized to keep its internal storage as small as possible while preserving requested past state (and possibly restoring it).&amp;nbsp; It used a cyclical buffer and a number of opaque handles.&amp;nbsp; One of the worst problems is that it was a somewhat leaky abstraction since the complexity leaked into the code consuming it.  &lt;p&gt;When the code was first introduced it was reasonably contained but over time its inherent complexity began to pervade the whole parser.&amp;nbsp; Eventually, it was hard to make improvements to the parser without breaking the invariants of the MarkableEnumerator.&amp;nbsp; It was an absolute horror.&amp;nbsp; I remember one night&amp;nbsp;well past midnight, Cyrus and I were talking about how much we hated the thing, but&amp;nbsp;we needed&amp;nbsp;it to provide&amp;nbsp;good performance.  &lt;p&gt;Then it occurred to us that we could replace the whole mess of opaque handles, circular buffers, mark and release code, and MarkableEnumerators within MarkableEnumerators&amp;nbsp;with just a linked list that wrapped the enumerator.&amp;nbsp; If someone wanted to save the state of the enumerator and resume it&amp;nbsp;then all they need to do is keep a reference to the desired node.&amp;nbsp; To all of the clients, it&amp;nbsp;looked just like an immutable&amp;nbsp;linked list.&amp;nbsp; That is it.&amp;nbsp; So much simpler and guess what?&amp;nbsp; It was almost as fast.&amp;nbsp; But even more importantly, because of its simplicity we were able to make even more important code faster.&amp;nbsp; Our development time for new features rocketed again.  &lt;p&gt;There are several lessons from this story, but one of them is perhaps the most important considering our current discussion.&amp;nbsp; Reducing the&amp;nbsp;number and scope&amp;nbsp;of side-effects&amp;nbsp;simplifies the code. &lt;p&gt;&lt;strong&gt;Immutable Binary Trees&lt;/strong&gt; &lt;p&gt;Mutation often seems to just cause problems.  &lt;p&gt;&lt;img src="http://www.scienceclarified.com/images/uesc_07_img0388.jpg"&gt;&lt;/p&gt; &lt;p&gt;Suppose that we want to&amp;nbsp;create a BinaryTree class.&amp;nbsp; One straightforward&amp;nbsp;implementation is  &lt;blockquote&gt; &lt;p&gt;&lt;font face="Courier New"&gt;class BinaryTree&amp;lt;T&amp;gt;&lt;br&gt;{&lt;br&gt;&amp;nbsp; public T Value&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; { get; set; } // yes, we have autoimplemented&lt;br&gt;&amp;nbsp; public BinaryTree&amp;lt;T&amp;gt; Parent { get; set; } // properties in case you haven't&lt;/font&gt;&lt;font face="Courier New"&gt;&lt;br&gt;&amp;nbsp; public BinaryTree&amp;lt;T&amp;gt; Left&amp;nbsp;&amp;nbsp; { get; set; } // heard&lt;br&gt;&amp;nbsp; public BinaryTree&amp;lt;T&amp;gt; Right&amp;nbsp; { get; set; }&lt;br&gt;}&lt;/font&gt;&lt;/p&gt;&lt;/blockquote&gt; &lt;p&gt;I don't&amp;nbsp;like it very much.&amp;nbsp; Those sets&amp;nbsp;give me an uneasy feeling.&amp;nbsp; Of course it depends on how the&amp;nbsp;objects are used, but suppose that we intend to use the binary tree&amp;nbsp;in a multithreaded environment.&amp;nbsp; If someone changes&amp;nbsp;any of the members of a node there is a chance that some other thread&amp;nbsp;already has a reference to a node in the tree and will then have a tree in an inconsistent state.&amp;nbsp; Yes, we could&amp;nbsp;use a lock to fix the problem but I tend to like a different approach to this problem.&amp;nbsp;  &lt;blockquote&gt; &lt;p&gt;&lt;font face="Courier New"&gt;class BinaryTree&amp;lt;T&amp;gt;&lt;br&gt;{&lt;br&gt;&amp;nbsp; T value;&lt;br&gt;&amp;nbsp; BinaryTree&amp;lt;T&amp;gt; left;&lt;br&gt;&amp;nbsp; BinaryTree&amp;lt;T&amp;gt; right; &lt;/font&gt; &lt;p&gt;&lt;font face="Courier New"&gt;&amp;nbsp; public BinaryTree(T value, BinaryTree&amp;lt;T&amp;gt; left, BinaryTree&amp;lt;T&amp;gt; right)&lt;br&gt;&amp;nbsp; {&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; this.value = value;&lt;br&gt;&amp;nbsp; &amp;nbsp; this.left = left;&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; this.right = right;&lt;br&gt;&amp;nbsp; } &lt;/font&gt; &lt;p&gt;&lt;font face="Courier New"&gt;&amp;nbsp; public T Value { get { return value; } }&lt;br&gt;&amp;nbsp; public BinaryTree&amp;lt;T&amp;gt; Left { get { return left; } }&lt;br&gt;&amp;nbsp; public BinaryTree&amp;lt;T&amp;gt; Right { get { return right; } }&lt;br&gt;}&lt;/font&gt;&lt;/p&gt;&lt;/blockquote&gt; &lt;p&gt;This is essentially the same as the first BinaryTree except that it is immutable (no sets and no methods causing mutation).&amp;nbsp; This requires that we have a constructor that takes in the appropriate values.&amp;nbsp; Also, you may have noticed that there is no Parent property.&amp;nbsp; The reason is that if the node is immutable then it is hard to know what the parent is at the time of creation.&amp;nbsp; With an immutable tree, you generally can either create parents before children or children before parents.&amp;nbsp; I prefer the later (despite the biological conundrum posed by this).&amp;nbsp; Note that this doesn't mean that we can't know what the parent of a given node is.&amp;nbsp; Indeed we can, but we need to introduce a new concept before addressing this.&lt;/p&gt; &lt;p&gt;Nodes can really be parented by n nodes.&amp;nbsp; Since any node can be constructed with a given node as either the left or the right child.&amp;nbsp; But given a tree (a root), we can enforce (assuming that we don't want DAGs)&amp;nbsp;that a node has at most one parent.&amp;nbsp; We will call this a BinaryTreeVersion.&lt;/p&gt; &lt;blockquote&gt; &lt;p&gt;&lt;font face="Courier New"&gt;class BinaryTreeVersion&amp;lt;T&amp;gt;&lt;br&gt;{&lt;br&gt;&amp;nbsp; BinaryTree&amp;lt;T&amp;gt; tree;&lt;br&gt;&amp;nbsp; Dictionary&amp;lt;BinaryTree&amp;lt;T&amp;gt;, BinaryTree&amp;lt;T&amp;gt;&amp;gt; parentMap; &lt;/font&gt; &lt;p&gt;&lt;font face="Courier New"&gt;&amp;nbsp; public BinaryTreeVersion(BinaryTree&amp;lt;T&amp;gt; tree)&lt;br&gt;&amp;nbsp; {&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; this.tree = tree;&lt;br&gt;&amp;nbsp; } &lt;/font&gt; &lt;p&gt;&lt;font face="Courier New"&gt;&amp;nbsp; public BinaryTree&amp;lt;T&amp;gt; Tree { get { return tree; } }&lt;br&gt;&amp;nbsp; public BinaryTree&amp;lt;T&amp;gt; GetParentOf(BinaryTree&amp;lt;T&amp;gt; node)&lt;br&gt;&amp;nbsp; {&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; if (parentMap == null)&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; {&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; parentMap = new Dictionary&amp;lt;BinaryTree&amp;lt;T&amp;gt;, BinaryTree&amp;lt;T&amp;gt;&amp;gt;();&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; FillParentMap(tree, null);&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;}&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; return parentMap[node];&lt;br&gt;&amp;nbsp; } &lt;/font&gt; &lt;p&gt;&lt;font face="Courier New"&gt;&amp;nbsp; void FillParentMap(BinaryTree&amp;lt;T&amp;gt; tree, BinaryTree&amp;lt;T&amp;gt; parent)&lt;br&gt;&amp;nbsp; {&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; if (tree == null)&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; return;&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; parentMap.Add(tree, parent);&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; FillParentMap(tree.Left, tree);&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; FillParentMap(tree.Right, tree);&lt;br&gt;&amp;nbsp; } &lt;/font&gt;&lt;font face="Courier New"&gt;&lt;br&gt;}&lt;/font&gt;&lt;/p&gt;&lt;/blockquote&gt; &lt;p&gt;The parent operation is exposed on the BinaryTreeVersion.&amp;nbsp; The parent of a given node is stored in the parentMap which is filled with node-parent pairs.&amp;nbsp; So now we have a tree that is immutable and the ability to access a node's parent.&lt;/p&gt; &lt;p&gt;But we can take it one step further, we can create functions that will modify the tree.&amp;nbsp; Note that we will not actually modify the tree but&amp;nbsp;we will return a new BinaryTreeVersion.&amp;nbsp; The ChangeNodeValues function&amp;nbsp;takes two functions:&amp;nbsp; a function that determines whether to modify the given node's value and a function to compute the node's new value (there are better ways to do this for specific modifications and yes I could have used a visitor).&lt;/p&gt; &lt;blockquote&gt; &lt;p&gt;&lt;font face="Courier New"&gt;class BinaryTreeVersion&amp;lt;T&amp;gt;&lt;br&gt;{&lt;br&gt;&lt;/font&gt; &lt;p&gt;&lt;font face="Courier New"&gt;&amp;nbsp;...&amp;nbsp;&lt;/font&gt;  &lt;p&gt;&lt;font face="Courier New"&gt;&amp;nbsp; public BinaryTreeVersion&amp;lt;T&amp;gt; ChangeNodeValues(Func&amp;lt;BinaryTree&amp;lt;T&amp;gt;, bool&amp;gt; predicate, Func&amp;lt;BinaryTree&amp;lt;T&amp;gt;, T&amp;gt; newValue)&lt;br&gt;&amp;nbsp; {&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; return new BinaryTreeVersion&amp;lt;T&amp;gt;(ChangeNodeValue(tree, predicate, newValue));&lt;br&gt;&amp;nbsp; } &lt;/font&gt; &lt;p&gt;&lt;font face="Courier New"&gt;&amp;nbsp; BinaryTree&amp;lt;T&amp;gt; ChangeNodeValue(BinaryTree&amp;lt;T&amp;gt; node, Func&amp;lt;BinaryTree&amp;lt;T&amp;gt;, bool&amp;gt; predicate, Func&amp;lt;BinaryTree&amp;lt;T&amp;gt;, T&amp;gt; newValue)&lt;br&gt;&amp;nbsp; {&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; if (node == null)&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; return null;&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; var left = ChangeNodeValue(node.Left, predicate, newValue);&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; var right = ChangeNodeValue(node.Right, predicate, newValue);&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; var value = predicate(node) ? newValue(node) : node.Value;&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; if (value.Equals(node.Value) &amp;amp;&amp;amp; left == node.Left &amp;amp;&amp;amp; right == node.Right)&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; return node;&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; return new BinaryTree&amp;lt;T&amp;gt;(value, left, right);&lt;br&gt;&amp;nbsp; }&lt;br&gt;}&lt;/font&gt;&lt;/p&gt;&lt;/blockquote&gt; &lt;p&gt;The neat thing is that since we use immutable trees, we can share subtrees that are not changed.&amp;nbsp; Even so, if another thread has a reference to the first BinaryTreeVersion or a node in the first tree then things will just work because we are mucking around with the data.&lt;/p&gt; &lt;p&gt;&lt;strong&gt;The Benefits of Purity&lt;/strong&gt;&lt;/p&gt; &lt;p&gt;One of the most painful things in software development is integrating two or more&amp;nbsp;things (objects, assemblies, functions, ...) together.&amp;nbsp; Invariably something will go wrong and a programmer that worked on one or the other&amp;nbsp;things in question&amp;nbsp;will protest, "It worked on my machine!"&amp;nbsp; Yes, indeed it probably did and it probably even works by itself but when put together with other things&amp;nbsp;it doesn't play so nice.&lt;/p&gt; &lt;p&gt;One way to increase the reliability of a unit&amp;nbsp;is to eliminate the side-effects.&amp;nbsp; This makes composing and integrating&amp;nbsp;units together much easier and more robust.&amp;nbsp; Since they are side-effect free, they always work the same no matter the environment.&amp;nbsp; This is called &lt;a href="http://en.wikipedia.org/wiki/Referential_transparency"&gt;referential transparency&lt;/a&gt;.&lt;/p&gt; &lt;p&gt;Conversely, things that are side-effect free are also easier to divide.&amp;nbsp; For a good example of this take a look at PLinq which farms out querying work to the available threads.&amp;nbsp; It divides up the work and then integrates the results: map-reduce.&lt;/p&gt; &lt;p&gt;But that is a discussion for another day...&lt;/p&gt;&lt;img src="http://blogs.msdn.com/aggbug.aspx?PostID=1777705" width="1" height="1"&gt;</description><category domain="http://blogs.msdn.com/wesdyer/archive/tags/C_2300_/default.aspx">C#</category><category domain="http://blogs.msdn.com/wesdyer/archive/tags/Functional+Programming/default.aspx">Functional Programming</category></item><item><title>Linq to ASCII Art</title><link>http://blogs.msdn.com/wesdyer/archive/2007/02/23/linq-to-ascii-art.aspx</link><pubDate>Fri, 23 Feb 2007 09:02:00 GMT</pubDate><guid isPermaLink="false">91d46819-8472-40ad-a661-2c78acb4018c:1745602</guid><dc:creator>wesdyer</dc:creator><slash:comments>40</slash:comments><comments>http://blogs.msdn.com/wesdyer/comments/1745602.aspx</comments><wfw:commentRss>http://blogs.msdn.com/wesdyer/commentrss.aspx?PostID=1745602</wfw:commentRss><description>&lt;p&gt;Last night I was searching for an audio version of &lt;em&gt;&lt;a href="http://www.amazon.com/Hackers-Painters-Big-Ideas-Computer/dp/0596006624"&gt;Painters and Hackers&lt;/a&gt;&lt;/em&gt; by &lt;a href="http://www.paulgraham.com/"&gt;Paul Graham&lt;/a&gt;.&amp;nbsp; Pretty soon I had completely forgotten about the book and found myself reading the &lt;a href="http://en.wikipedia.org/wiki/Main_Page"&gt;Wikipedia&lt;/a&gt; article about &lt;a href="http://en.wikipedia.org/wiki/Hacker"&gt;Hackers&lt;/a&gt;.&amp;nbsp; Isn't Internet search great?&lt;/p&gt; &lt;p&gt;Of all of the things in the article, the one thing that captured my attention was the &lt;a href="http://en.wikipedia.org/wiki/Image:Lamoascii.png"&gt;ASCII picture&lt;/a&gt; of &lt;a href="http://en.wikipedia.org/wiki/Adrian_Lamo"&gt;Adrian Lamo&lt;/a&gt;.&amp;nbsp; I immediately thought, "How cool is that!?"&amp;nbsp; So instead of&amp;nbsp;popping off my current stack frame and returning to searching for &lt;em&gt;Painters and Hackers&lt;/em&gt;, I began thinking about how to create such a picture.&amp;nbsp; I certainly did not want to create it by hand.&amp;nbsp; I didn't even want to pick which characters or colors would be printed to the screen.&amp;nbsp; So accordingly, I began thinking of writing a program to do it for me.&lt;/p&gt; &lt;p&gt;I grabbed the latest bits and began writing code.&amp;nbsp; A few hours later, I had a working program with a few bells and whistles too.&lt;/p&gt; &lt;p&gt;&lt;strong&gt;ASCII Art&lt;/strong&gt;&lt;/p&gt; &lt;p&gt;Here is an example of converting &lt;a href="http://en.wikipedia.org/wiki/Gandalf"&gt;Gandalf&lt;/a&gt; from pixels to &lt;a href="http://www.asciitable.com/"&gt;ASCII&lt;/a&gt;:&lt;/p&gt; &lt;p&gt;&lt;a href="http://blogs.msdn.com/blogfiles/wesdyer/WindowsLiveWriter/LinqtoASCIIArt_12D96/image036.png" atomicselection="true"&gt;&lt;img style="border-top-width: 0px; border-left-width: 0px; border-bottom-width: 0px; border-right-width: 0px" height="424" src="http://blogs.msdn.com/blogfiles/wesdyer/WindowsLiveWriter/LinqtoASCIIArt_12D96/image0_thumb28.png" width="334" border="0"&gt;&lt;/a&gt;&lt;a href="http://blogs.msdn.com/blogfiles/wesdyer/WindowsLiveWriter/LinqtoASCIIArt_12D96/image%7B0%7D%5B3%5D.png" atomicselection="true"&gt;&lt;img style="border-top-width: 0px; border-left-width: 0px; border-bottom-width: 0px; border-right-width: 0px" height="424" src="http://blogs.msdn.com/blogfiles/wesdyer/WindowsLiveWriter/LinqtoASCIIArt_12D96/image%7B0%7D_thumb%5B1%5D.png" width="350" border="0"&gt; &lt;/a&gt;&lt;/p&gt; &lt;p&gt;&lt;strong&gt;How to Convert and Image to ASCII Art&lt;/strong&gt;&lt;/p&gt; &lt;p&gt;The process works like this:&lt;/p&gt; &lt;p&gt;Determine how big of an area will be used for displaying the ASCII art.&amp;nbsp; By default, the width of the image will be the width of the console's buffer and the height will be computed so as the preserve the ratio of width to height from the original image.&lt;/p&gt; &lt;p&gt;Now divide the original image into as many rectangles as will be used to display the ASCII.&amp;nbsp; For each rectangle in the original picture determine its grayscale value by averaging the&amp;nbsp;grayscale values&amp;nbsp;of each pixel.&amp;nbsp; The grayscale value of a pixel is:&lt;/p&gt; &lt;blockquote&gt; &lt;p&gt;&lt;font face="Courier New"&gt;GrayScale = .3 * Red + .59 * Green + .11 * Blue&lt;/font&gt;&lt;/p&gt;&lt;/blockquote&gt; &lt;p&gt;We then increase the contrast of each region by some amount (d is the luminosity of a region, contrast is any double but usually around 1.5):&lt;/p&gt; &lt;blockquote&gt; &lt;p&gt;&lt;font face="Courier New"&gt;public static double Contrast(this double d, double contrast)&lt;br&gt;{&lt;br&gt;&amp;nbsp; return (((d - .5) * contrast) + .5).Bound(0, 1);&lt;br&gt;}&lt;/font&gt;&lt;/p&gt;&lt;/blockquote&gt; &lt;p&gt;Finally, for each region in the ASCII art we choose from an array of possible ASCII figures (sorted) by the grayscale value for that region.&amp;nbsp; The ASCII figure with the closest luminosity is picked.&lt;/p&gt; &lt;p&gt;The only point that I haven't covered is how the array of ASCII figures was generated.&amp;nbsp; I could have done this by hand if I wanted to, but I didn't want to.&amp;nbsp; Instead, I generate the grayscale figures each time.&amp;nbsp; Each figure consists of a character and a console color either ConsoleColor.DarkGray, ConsoleColor.Gray, or ConsoleColor.White.&amp;nbsp; The characters are one of the alphanumeric characters or&amp;nbsp;the special symbols (things like %, $, @, ...).&amp;nbsp; The program generates all of the combinations and then measures their grayscale value by drawing them to a hidden bitmap and then computing their average grayscale value.&amp;nbsp; The figures are sorted by this value and a final grayscale is built.&lt;/p&gt; &lt;p&gt;&lt;strong&gt;A Few&amp;nbsp;Snippets&lt;/strong&gt;&lt;/p&gt; &lt;p&gt;If you take a look at the source, you will notice that it is written rather different than most C# code.&amp;nbsp; A lot of the code resides in extension methods and there are a number of lambdas and queries.&amp;nbsp; In fact, loops are kind of rare in the code.&amp;nbsp; For example, here is a function that returns all of the pixels in a rectangular region of a bitmap.&lt;/p&gt; &lt;blockquote&gt; &lt;p&gt;&lt;font face="Courier New"&gt;public static IEnumerable&amp;lt;Color&amp;gt; GetPixels(this Bitmap image, Rectangle rect)&lt;br&gt;{&lt;br&gt;&amp;nbsp; return from y in rect.Top.To(rect.Bottom)&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &amp;nbsp; from x in rect.Left.To(rect.Right)&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; select image.GetPixel(x, y);&lt;br&gt;}&lt;/font&gt;&lt;/p&gt;&lt;/blockquote&gt; &lt;p&gt;The To function is a helpful little function that I wrote.  &lt;blockquote&gt; &lt;p&gt;&lt;font face="Courier New"&gt;public static IEnumerable&amp;lt;int&amp;gt; To(this int start, int end)&lt;br&gt;{&lt;br&gt;&amp;nbsp; var diff = end - start &amp;gt; 0 ? 1 : -1;&lt;br&gt;&amp;nbsp; for (var current = start; current != end; current += diff)&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; yield return current;&lt;br&gt;}&lt;/font&gt;&lt;/p&gt;&lt;/blockquote&gt; &lt;p&gt;Of course, I also could have written Iterate and then written To in terms of that.  &lt;blockquote&gt; &lt;p&gt;&lt;font face="Courier New"&gt;public static IEnumerable&amp;lt;T&amp;gt; Iterate&amp;lt;T&amp;gt;(T initialValue, Func&amp;lt;T, bool&amp;gt; predicate, Func&amp;lt;T, T&amp;gt; next)&lt;br&gt;{&lt;br&gt;&amp;nbsp; for (var current = initialValue; predicate(current); current = next(current))&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; yield return current;&lt;br&gt;}&lt;/font&gt;&lt;/p&gt; &lt;p&gt;&lt;font face="Courier New"&gt;public static IEnumerable&amp;lt;int&amp;gt; To(this int start, int end)&lt;br&gt;{&lt;br&gt;&amp;nbsp; var diff = end - start &amp;gt; 0 ? 1 : -1;&lt;br&gt;&amp;nbsp; return Iterate(start, x =&amp;gt; x != end, x =&amp;gt; x + diff);&lt;br&gt;}&lt;/font&gt;&lt;/p&gt;&lt;/blockquote&gt; &lt;p&gt;Another interesting part is setting up the display and then restoring the original display properties of the console.  &lt;blockquote&gt; &lt;p&gt;&lt;font face="Courier New"&gt;using (SetupConsole())&lt;/font&gt;  &lt;p&gt;&lt;font face="Courier New"&gt;&amp;nbsp; ...&lt;/font&gt; &lt;/p&gt;&lt;/blockquote&gt; &lt;p&gt;Where SetupConsole is defined as:  &lt;blockquote&gt; &lt;p&gt;&lt;font face="Courier New"&gt;&lt;/font&gt;&lt;/p&gt; &lt;p&gt;&lt;font face="Courier New"&gt;static ActionDisposable SetupConsole()&lt;br&gt;{&lt;br&gt;&amp;nbsp; var originalBackgroundColor = Console.BackgroundColor;&lt;br&gt;&amp;nbsp; var originalForegroundColor = Console.ForegroundColor;&lt;br&gt;&amp;nbsp; return new ActionDisposable(() =&amp;gt;&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; {&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; Console.BackgroundColor = originalBackgroundColor;&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; Console.ForegroundColor = originalForegroundColor;&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; });&lt;br&gt;}&lt;/font&gt;&lt;/p&gt;&lt;/blockquote&gt; &lt;p&gt;Notice that the original state of the console is captured only in the SetupConsole method and does not clutter the rest of the code.&amp;nbsp; The&amp;nbsp;closure&amp;nbsp;that is&amp;nbsp;created contains all of the necessary information to restore the console to its original state.&amp;nbsp; This way we hide data &lt;em&gt;even from private members of the same class&lt;/em&gt;.&amp;nbsp; If they don't need to know, then they don't need to know.&amp;nbsp; Instead only a means for restoring the original state is provided.  &lt;p&gt;I'm sure that the program can be improved a lot.&amp;nbsp; So if you have any comments, suggestions, or bugs then just post a comment.&amp;nbsp; Enjoy!  &lt;p&gt;&lt;strong&gt;Update:&lt;/strong&gt;  &lt;p&gt;I took the comments as well as some of my own ideas and improved the ASCII art generator.&amp;nbsp; I also modified the &lt;em&gt;How to Convert an Image to ASCII Art &lt;/em&gt;section to reflect some changes.&amp;nbsp; Thank you to everyone that contributed.  &lt;p&gt;&lt;strong&gt;Download the Source&lt;/strong&gt;&lt;/p&gt; &lt;p&gt;&lt;a href="http://www.box.net/public/10oy0aodrk"&gt;&lt;img height="24" alt="File icon" src="http://www.box.net/thumbs/24x24/default_file.gif" width="24" align="absMiddle" border="0"&gt;AsciiPictureSource.zip&lt;/a&gt;&lt;/p&gt; &lt;p&gt;&lt;a href="http://www.box.net/public/8ofyrvmzho"&gt;&lt;img height="24" alt="File icon" src="http://www.box.net/thumbs/24x24/default_file.gif" width="24" align="absMiddle" border="0"&gt;AsciiPictureSourcev1.1.zip&lt;/a&gt;&lt;/p&gt;&lt;img src="http://blogs.msdn.com/aggbug.aspx?PostID=1745602" width="1" height="1"&gt;</description><category domain="http://blogs.msdn.com/wesdyer/archive/tags/Programming/default.aspx">Programming</category><category domain="http://blogs.msdn.com/wesdyer/archive/tags/C_2300_/default.aspx">C#</category></item><item><title>The Virtues of Laziness</title><link>http://blogs.msdn.com/wesdyer/archive/2007/02/13/the-virtues-of-laziness.aspx</link><pubDate>Wed, 14 Feb 2007 00:11:57 GMT</pubDate><guid isPermaLink="false">91d46819-8472-40ad-a661-2c78acb4018c:1671293</guid><dc:creator>wesdyer</dc:creator><slash:comments>22</slash:comments><comments>http://blogs.msdn.com/wesdyer/comments/1671293.aspx</comments><wfw:commentRss>http://blogs.msdn.com/wesdyer/commentrss.aspx?PostID=1671293</wfw:commentRss><description>&lt;p&gt;It seems that I riled some people up with my blog post yesterday.&amp;nbsp; After some thought, I think the primary reason that there was some backlash is because some people feel that I violated one of the sacred principles of FP:&amp;nbsp; lists are *the* data structure.&amp;nbsp; Well, let me set the matter straight.&amp;nbsp; I love lists.&amp;nbsp; Especially the singlely linked immutable kind that are found in many functional languages.&amp;nbsp; Furthermore, Microsoft is not trying to launch some massive marketing campaign to sell IEnumerable&amp;lt;T&amp;gt; as the *new* list.&amp;nbsp; So to be clear, I talked about IEnumerable&amp;lt;T&amp;gt; yesterday because people who have used functional languages will wonder where are the lists in C# 3.0.&amp;nbsp; IEnumerable&amp;lt;T&amp;gt; is not the same as a&amp;nbsp;list, but there are many similarities between IEnumerable&amp;lt;T&amp;gt; and&amp;nbsp;lazy lists&amp;nbsp;that I pointed out yesterday when I showed they are isomorphic by describing the bijective mapping between them.&lt;/p&gt; &lt;p&gt;Furthermore, it is the case that some data structures are generally better than others.&amp;nbsp; But there are tradeoffs between using the various data structures.&amp;nbsp;&amp;nbsp;Also, *not* all of the tradeoffs are captured by looking exclusively at their time complexity for some operation.&amp;nbsp; There is of course the space complexity and there is the complexity of implementation itself.&amp;nbsp; And don't forget that often they have different characteristics for different operations.&amp;nbsp; The key point here is that a given problem will have a number of constraints and each of the competing designs has a number of trade-offs.&amp;nbsp; As an interviewer, when I&amp;nbsp;notice a candidate is not aware of the trade-offs that he is making then I start to worry that they were not considered at all.&amp;nbsp; Furthermore, when I notice that a candidate seems to favor one data structure to the exclusion of others, I start to wonder how many tools are in the toolbox.&amp;nbsp; But after observing this behavior many times, I am convinced that it often is not the coding problem that is driving usage of some data structure&amp;nbsp;but the mode of thinking that the candidate employs.&lt;/p&gt; &lt;p&gt;One more thing before I continue on.&amp;nbsp; At least one reader wondered why I said the following:&lt;/p&gt; &lt;blockquote&gt; &lt;p&gt;"Where most programmers who are accustomed to imperative style would naturally use an array, &lt;strong&gt;a&amp;nbsp;variable&lt;/strong&gt;, or a mutable object, a functional programmer will often use a list."&lt;/p&gt;&lt;/blockquote&gt; &lt;p&gt;Yes, I meant to say exactly what I said.&amp;nbsp; In fact, when I wrote it, I paused before deciding to include it because I thought it might be misunderstood.&amp;nbsp; When I first read SICP, the most mind bending and rewarding topic was at the end of chapter 3.&amp;nbsp; The section on streams.&amp;nbsp; One of the motivations that was given for using a stream (infinite list) was that variables that change their value over time cause problems.&amp;nbsp; One way to address this was to have streams represent the state of the variable over time where each element of the stream represents a state of the variable at some point in time.&lt;/p&gt; &lt;p&gt;So without further ado, let's take a look at &lt;a href="http://en.wikipedia.org/wiki/Stream_%28computer%29"&gt;streams&lt;/a&gt;...&lt;/p&gt; &lt;p&gt;What we want is an infinite list.&amp;nbsp; The problem is that infinite list can never actually be fully realized because of&amp;nbsp;their infinite nature.&amp;nbsp; So if we attempt to realize an infinite list either the computer will enter an infinite loop or it will run out of resources (stack overflow, out of memory, etc.).&lt;/p&gt; &lt;p&gt;We can overcome this problem by having lazy lists.&amp;nbsp; Lists where the next element in the list is not realized until it is needed.&amp;nbsp; Yesterday, I presented one such lazy list which uses an enumerator to realize the next element.&amp;nbsp; Today, I present another which has a more intriguing definition.&lt;/p&gt; &lt;blockquote&gt; &lt;p&gt;&lt;font face="Courier New"&gt;class Stream&amp;lt;T&amp;gt; : IList&amp;lt;T&amp;gt;&lt;br&gt;{&lt;br&gt;&amp;nbsp; Func&amp;lt;IList&amp;lt;T&amp;gt;&amp;gt; next;&lt;br&gt;&amp;nbsp; T value; &lt;/font&gt; &lt;p&gt;&lt;font face="Courier New"&gt;&amp;nbsp; public Stream(T value, Func&amp;lt;IList&amp;lt;T&amp;gt;&amp;gt; next)&lt;br&gt;&amp;nbsp; {&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; this.value = value;&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; this.next = next;&lt;br&gt;&amp;nbsp; } &lt;/font&gt; &lt;p&gt;&lt;font face="Courier New"&gt;&amp;nbsp; public IList&amp;lt;T&amp;gt; Next { get { return next(); } }&lt;br&gt;&amp;nbsp; public T Value { get { return value; } }&lt;br&gt;}&lt;/font&gt;&lt;/p&gt;&lt;/blockquote&gt; &lt;p&gt;This lazy list is very similar to a normal list.&amp;nbsp; The only difference is that instead of taking a list as the value of the next node in the list, it takes a function which will evaluate to the next node in the list.&amp;nbsp; But this difference is critical.&lt;/p&gt; &lt;p&gt;The first difference can easily be seen by imaging a list type, ErrorList, that when constructed throws an exception.&lt;/p&gt; &lt;blockquote&gt; &lt;p&gt;&lt;font face="Courier New"&gt;class ErrorList&amp;lt;T&amp;gt; : IList&amp;lt;T&amp;gt;&lt;br&gt;{&lt;br&gt;&amp;nbsp; public ErrorList()&amp;nbsp;&amp;nbsp; { throw new Exception(); }&lt;br&gt;&amp;nbsp; public IList&amp;lt;T&amp;gt; Next { get { throw new Exception(); } }&lt;br&gt;&amp;nbsp; public T Value&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; { get { throw new Exception(); } }&lt;br&gt;}&lt;/font&gt;&lt;/p&gt;&lt;/blockquote&gt; &lt;p&gt;Now consider the following code:&lt;/p&gt; &lt;blockquote&gt; &lt;p&gt;&lt;font face="Courier New"&gt;var list = new List&amp;lt;int&amp;gt;(1, new ErrorList&amp;lt;int&amp;gt;());&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; // error, exception thrown&lt;br&gt;var stream = new Stream&amp;lt;int&amp;gt;(1, () =&amp;gt; new ErrorList&amp;lt;int&amp;gt;()); // no error&lt;/font&gt;&lt;/p&gt;&lt;/blockquote&gt; &lt;p&gt;An exception is thrown when the list is constructed but when the stream is constructed no exception is thrown.&amp;nbsp; Unless the Next property is evaluated on the stream, there will never be an exception.&lt;/p&gt; &lt;p&gt;The second difference can be seen in the following code:&lt;/p&gt; &lt;blockquote&gt; &lt;p&gt;&lt;font face="Courier New"&gt;IList&amp;lt;BigInteger&amp;gt; onesList = null;&lt;br&gt;onesList = new List&amp;lt;BigInteger&amp;gt;(1, onesList);&lt;br&gt;IList&amp;lt;BigInteger&amp;gt; onesStream = null;&lt;br&gt;onesStream = new Stream&amp;lt;BigInteger&amp;gt;(1, () =&amp;gt; onesStream);&lt;/font&gt;&lt;/p&gt;&lt;/blockquote&gt; &lt;p&gt;If you try to list all of the values in onesList, then you will notice that it only contains one value.&amp;nbsp; Whereas onesStream contains an infinite number of values.&amp;nbsp; The reason is that when we constructed onesList, we passed in onesList but onesList had the value null at the time so the next node was set to null.&amp;nbsp; But in the stream case we passed in a function that would be evaluated sometime in the future.&amp;nbsp; By the time that we evaluate it, it will return the proper value of onesStream.&lt;/p&gt; &lt;p&gt;A third difference is found in the performance of the two lists.&amp;nbsp; With the lazy lists, parts of the list that are never realized are never paid for.&amp;nbsp; So it is a pay as you go model as opposed to pay everything up front.&amp;nbsp; Furthermore, less space can be required since the whole list is not necessarily held in memory at once but only a process decription that can compute each element as it is required.&lt;/p&gt; &lt;p&gt;So now we have this infinite stream of ones, but can we do anything more interesting?&amp;nbsp; Sure.&amp;nbsp; First, let's define a zip function between lists.&lt;/p&gt; &lt;p&gt;&lt;font face="Courier New"&gt;&amp;nbsp; public static IList&amp;lt;V&amp;gt; Zip&amp;lt;T,U,V&amp;gt;(Func&amp;lt;T,U,V&amp;gt; f, IList&amp;lt;T&amp;gt; list1, IList&amp;lt;U&amp;gt; list2)&lt;br&gt;&amp;nbsp; {&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; if (list1 == null || list2 == null)&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; return null;&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; return new Stream&amp;lt;V&amp;gt;(f(list1.Value, list2.Value), () =&amp;gt; Zip&amp;lt;T,U,V&amp;gt;(f, list1.Next, list2.Next));&lt;br&gt;&amp;nbsp; }&lt;/font&gt; &lt;p&gt;Yes, that is somewhat of a mouthful.&amp;nbsp; Here is what it does.&amp;nbsp; It takes two lists where the lists may differ from each other in what kind of elements they contain.&amp;nbsp; It also takes a function from the type of the first list's elements and the type of the second list's elements and returns possibly a new type.&amp;nbsp; Then if either of the lists is empty we return an empty list (null).&amp;nbsp; But if both lists are non-empty then we return a stream where the first element is the application of the given function to the first element of both of the lists and the rest of the list will be the evaluation of Zip on the rest of the two lists.&amp;nbsp; It is important that Zip uses a stream because these lists may be infinite and if we try to immediately evaluate the entire list we will run out of resources.&lt;/p&gt; &lt;p&gt;Now that we have Zip, let's put it to use to define the natural numbers.&lt;/p&gt; &lt;blockquote&gt; &lt;p&gt;&lt;font face="Courier New"&gt;IList&amp;lt;BigInteger&amp;gt; ones = null;&lt;br&gt;ones = new Stream&amp;lt;BigInteger&amp;gt;(1, () =&amp;gt; ones);&lt;br&gt;IList&amp;lt;BigInteger&amp;gt; natural = null;&lt;br&gt;natural = new Stream&amp;lt;BigInteger&amp;gt;(0, () =&amp;gt; Zip((x, y) =&amp;gt; x + y, natural, ones));&lt;/font&gt;&lt;/p&gt;&lt;/blockquote&gt; &lt;p&gt;So what we are saying is that the natural numbers begin with zero and then are followed by the sum of the first natural number with the first element of ones (0 + 1).&amp;nbsp; The second natural number is the sum of the second element of natural numbers with the second element of ones (1 + 1) and so on.&amp;nbsp; This works because each element of natural numbers is defined only in terms of the elements of natural numbers that occur previous to it.&lt;/p&gt; &lt;p&gt;So now we can easily define the odd numbers (2k + 1)&amp;nbsp;and even numbers (2k).&amp;nbsp; But first we need a map function for lists.&lt;/p&gt; &lt;blockquote&gt; &lt;p&gt;&lt;font face="Courier New"&gt;public static IList&amp;lt;U&amp;gt; Map&amp;lt;T, U&amp;gt;(Func&amp;lt;T, U&amp;gt; f, IList&amp;lt;T&amp;gt; list)&lt;br&gt;{&lt;br&gt;&amp;nbsp; if (list == null)&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; return null;&lt;br&gt;&amp;nbsp; return new Stream&amp;lt;U&amp;gt;(f(list.Value), () =&amp;gt; Map(f, list.Next));&lt;br&gt;} &lt;/font&gt;&lt;/p&gt;&lt;/blockquote&gt; &lt;p&gt;Now here&amp;nbsp;are the definitions of odd and even numbers.&lt;/p&gt; &lt;blockquote&gt; &lt;p&gt;&lt;font face="Courier New"&gt;IList&amp;lt;BigInteger&amp;gt; odds = Map(x =&amp;gt; 2 * x + 1, natural);&lt;br&gt;IList&amp;lt;BigInteger&amp;gt; evens = Map(x =&amp;gt; 2 * x, natural);&lt;/font&gt;&lt;/p&gt;&lt;/blockquote&gt; &lt;p&gt;We can also define the fibonacci sequence as a stream.&lt;/p&gt; &lt;blockquote&gt; &lt;p&gt;&lt;font face="Courier New"&gt;IList&amp;lt;BigInteger&amp;gt; fibs = null;&lt;br&gt;fibs = new List&amp;lt;BigInteger&amp;gt;(0, new Stream&amp;lt;BigInteger&amp;gt;(1, () =&amp;gt; Zip(add, fibs, fibs.Next)));&lt;/font&gt;&lt;/p&gt;&lt;/blockquote&gt; &lt;p&gt;What we are saying here is that the first fibonacci number is zero and the second is one but then the next one is the sum of the first number and the second number and so on.&amp;nbsp; This is similar to the natural numbers definition which used itself to compute itself.&lt;/p&gt; &lt;p&gt;If you try it out, you will also notice that it isn't very efficient.&amp;nbsp; This is because we are back to our exponential time complexity.&amp;nbsp; But this can easily be remedied by memoizing the next function in the constructor to the stream:&lt;/p&gt;&lt;font face="Courier New"&gt;&amp;nbsp; public Stream(T value, Func&amp;lt;IList&amp;lt;T&amp;gt;&amp;gt; next)&lt;br&gt;&amp;nbsp; {&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; this.value = value;&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; this.next = next&lt;font color="#ff8040"&gt;.Memoize()&lt;/font&gt;;&lt;br&gt;&amp;nbsp; } &lt;/font&gt; &lt;p&gt;Now it has linear time complexity by trading off some space (linear as well).&lt;/p&gt; &lt;p&gt;Let's finish by solving the famous problem of producing the &lt;a href="http://en.wikipedia.org/wiki/Hamming_numbers"&gt;Hamming numbers&lt;/a&gt;.&amp;nbsp; The problem is to list all of the positive integers who have no prime factors other than 2, 3, or 5 in ascending order.&amp;nbsp; The first ten Hamming numbers are:&lt;/p&gt; &lt;blockquote&gt; &lt;p&gt;1, 2, 3, 4, 5, 6, 8, 9, 10, 12&lt;/p&gt;&lt;/blockquote&gt; &lt;p&gt;This problem is notoriously difficult without lazy evaluation and is used to demonstrate the power of laziness.&lt;/p&gt; &lt;p&gt;To solve this problem first note that the first hamming number is 1.&amp;nbsp; Then if h is a hamming number so is 2h, 3h, and 5h.&amp;nbsp; So we can define three streams which map the hamming numbers to 2h, 3h, and 5h respectively.&amp;nbsp; The only remaining requirement is that they must be in order.&amp;nbsp; We can maintain this invariant by defining a function named Merge:&lt;/p&gt; &lt;blockquote&gt; &lt;p&gt;&lt;font face="Courier New"&gt;public static IList&amp;lt;T&amp;gt; Merge&amp;lt;T&amp;gt;(IList&amp;lt;T&amp;gt; list1, IList&amp;lt;T&amp;gt; list2) where T : IComparable&amp;lt;T&amp;gt;&lt;br&gt;{&lt;br&gt;&amp;nbsp; if (list1 == null)&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; return list2;&lt;br&gt;&amp;nbsp; else if (list2 == null)&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; return list1;&lt;br&gt;&amp;nbsp; int c = list1.Value.CompareTo(list2.Value);&lt;br&gt;&amp;nbsp; if (c &amp;lt; 0)&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; return new Stream&amp;lt;T&amp;gt;(list1.Value, () =&amp;gt; Merge(list1.Next, list2));&lt;br&gt;&amp;nbsp; else if (c &amp;gt; 0)&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; return new Stream&amp;lt;T&amp;gt;(list2.Value, () =&amp;gt; Merge(list1, list2.Next));&lt;br&gt;&amp;nbsp; else&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; return new Stream&amp;lt;T&amp;gt;(list1.Value, () =&amp;gt; Merge(list1.Next, list2.Next));&lt;br&gt;}&lt;/font&gt;&lt;/p&gt;&lt;/blockquote&gt; &lt;p&gt;Now we are ready to define the Hamming numbers.&amp;nbsp; Notice how close the definition in the code is to our description:&lt;/p&gt; &lt;blockquote&gt; &lt;p&gt;&lt;font face="Courier New"&gt;IList&amp;lt;BigInteger&amp;gt; hamming = null;&lt;br&gt;hamming = new Stream&amp;lt;BigInteger&amp;gt;(1, () =&amp;gt; Merge(Map(x =&amp;gt; x * 2, hamming), Merge(Map(x =&amp;gt; x * 3, hamming), Map(x =&amp;gt; x * 5, hamming))));&lt;/font&gt;&lt;/p&gt;&lt;/blockquote&gt; &lt;p&gt;Now for fun, try to think of how to do it without lazy evaluation.&lt;/p&gt;&lt;img src="http://blogs.msdn.com/aggbug.aspx?PostID=1671293" width="1" height="1"&gt;</description><category domain="http://blogs.msdn.com/wesdyer/archive/tags/C_2300_/default.aspx">C#</category><category domain="http://blogs.msdn.com/wesdyer/archive/tags/Functional+Programming/default.aspx">Functional Programming</category></item><item><title>Why all the love for lists?</title><link>http://blogs.msdn.com/wesdyer/archive/2007/02/12/why-all-of-the-love-for-lists.aspx</link><pubDate>Mon, 12 Feb 2007 22:41:00 GMT</pubDate><guid isPermaLink="false">91d46819-8472-40ad-a661-2c78acb4018c:1663771</guid><dc:creator>wesdyer</dc:creator><slash:comments>15</slash:comments><comments>http://blogs.msdn.com/wesdyer/comments/1663771.aspx</comments><wfw:commentRss>http://blogs.msdn.com/wesdyer/commentrss.aspx?PostID=1663771</wfw:commentRss><description>&lt;P&gt;One of the things that I have noticed when&amp;nbsp;participating in&amp;nbsp;interviews&amp;nbsp;with potential candidates is that most candidates have a favorite data structure.&amp;nbsp; Presumably this is the data structure that they feel the most comfortable with.&amp;nbsp; The problem is that no matter what coding question I ask them, they see the answer through the lenses of their favorite data structure.&amp;nbsp; I have met programmers who are in love with hash tables, others who have a certain fondness for B-trees, and quite a few who adore arrays.&amp;nbsp; My feeling is that this happens not because they understand the data structure itself better than other data structures&amp;nbsp;(honestly, I can't believe that the guy who loves b-trees doesn't understand what arrays are), but it is because&amp;nbsp;each data structure encourages a certain way of&amp;nbsp;thinking about problems.&amp;nbsp; So really the candidates are just thinking about the question in a certain way that is expressed on the outside as using some particular data structure.&lt;/P&gt;
&lt;P&gt;One of the first things that a newcomer to functional programming will notice is that lists are all the rage.&amp;nbsp; Where most programmers who are accustomed to imperative style would naturally use an array, a&amp;nbsp;variable, or a mutable object, a functional programmer will often use a list.&amp;nbsp; Why is this?&lt;/P&gt;
&lt;P&gt;If we consider the insight that it is not the data structure itself but rather the mode of thinking that encourages the usage of the data structure then we can make some progress on understanding this.&amp;nbsp; Lists are the simplest recursive data structure.&amp;nbsp; A list is just a node consisting of a value and the next node in the list.&amp;nbsp; The definition of a list is defined in terms of itself.&lt;/P&gt;
&lt;BLOCKQUOTE&gt;
&lt;P&gt;&lt;FONT face="Courier New"&gt;&lt;/FONT&gt;
&lt;P&gt;&lt;FONT face="Courier New"&gt;interface IList&amp;lt;T&amp;gt;&lt;BR&gt;{&lt;BR&gt;&amp;nbsp; IList&amp;lt;T&amp;gt; Next { get; }&lt;BR&gt;&amp;nbsp; T Value { get; }&lt;BR&gt;}&lt;/FONT&gt;&lt;/P&gt;&lt;/BLOCKQUOTE&gt;
&lt;P&gt;But notice how similar this way of thinking is to recursive functions.&amp;nbsp; For example a very common function defined over lists is Length.&amp;nbsp; This function computes the length of a given list.&lt;/P&gt;
&lt;BLOCKQUOTE&gt;
&lt;P&gt;&lt;FONT face="Courier New"&gt;public static int Length&amp;lt;T&amp;gt;(this IList&amp;lt;T&amp;gt; list)&lt;BR&gt;{&lt;BR&gt;&amp;nbsp; if (list == null)&lt;BR&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; return 0;&lt;BR&gt;&amp;nbsp; return 1 + Length(list.Next);&lt;BR&gt;}&lt;/FONT&gt;&lt;/P&gt;&lt;/BLOCKQUOTE&gt;
&lt;P&gt;Length is a function that is defined in terms of itself.&amp;nbsp; Like the definition of list, Length has a value (either the 0 or the 1 +) and it has a next (the recursive call to Length(list.Next)).&amp;nbsp; So one reason why lists are so popular in functional programming is that they encourage a recursive way of thinking about problems.&lt;/P&gt;
&lt;P&gt;In C# 3.0, lists are not so commonly used as IEnumerable&amp;lt;T&amp;gt;.&amp;nbsp; In fact, IEnumerable&amp;lt;T&amp;gt; is used so much that it sticks out in the same way the usage of lists in functional programming languages sticks out.&amp;nbsp; The primary Linq provider that will be shipped is Linq to Objects which requires that the source of a query implement IEnumerable&amp;lt;T&amp;gt;.&lt;/P&gt;
&lt;P&gt;In some senses, IEnumerable&amp;lt;T&amp;gt; is not so very different from the definition of IList&amp;lt;T&amp;gt; shown above.&amp;nbsp; Both of them represent sequences of elements where only the current value and the next element are available at a given time.&amp;nbsp; In fact, it is relatively easy to define one in terms of the other.&lt;/P&gt;
&lt;P&gt;Here is a definition of IEnumerable&amp;lt;T&amp;gt; in terms of IList&amp;lt;T&amp;gt;.&lt;/P&gt;
&lt;BLOCKQUOTE&gt;
&lt;P&gt;&lt;FONT face="Courier New"&gt;public static IEnumerable&amp;lt;T&amp;gt; GetEnumerator&amp;lt;T&amp;gt;(this IList&amp;lt;T&amp;gt; list)&lt;BR&gt;{&lt;BR&gt;&amp;nbsp; for (var current = list; current != null; current = current.Next)&lt;BR&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; yield return current.Value;&lt;BR&gt;}&lt;/FONT&gt;&lt;/P&gt;&lt;/BLOCKQUOTE&gt;
&lt;P&gt;And here is a corresponding definition of IList&amp;lt;T&amp;gt; in terms of IEnumerable&amp;lt;T&amp;gt; (take from &lt;A href="http://blogs.msdn.com/wesdyer/archive/2006/01/13/saving-the-state-of-enumerators.aspx" mce_href="http://blogs.msdn.com/wesdyer/archive/2006/01/13/saving-the-state-of-enumerators.aspx"&gt;this post&lt;/A&gt;).&lt;/P&gt;
&lt;BLOCKQUOTE&gt;
&lt;P&gt;&lt;FONT face="Courier New"&gt;class LazyList&amp;lt;T&amp;gt; : IList&amp;lt;T&amp;gt;&lt;BR&gt;{&lt;BR&gt;&amp;nbsp; IList&amp;lt;T&amp;gt; next;&lt;BR&gt;&amp;nbsp; T value;&lt;BR&gt;&amp;nbsp; IEnumerator&amp;lt;T&amp;gt; enumerator; &lt;/FONT&gt;
&lt;P&gt;&lt;FONT face="Courier New"&gt;&amp;nbsp;&amp;nbsp;LazyList(T value, IEnumerator&amp;lt;T&amp;gt; enumerator)&lt;BR&gt;&amp;nbsp; {&lt;BR&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; this.value = value;&lt;BR&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;this.enumerator = enumerator;&lt;BR&gt;&amp;nbsp; } &lt;/FONT&gt;
&lt;P&gt;&lt;FONT face="Courier New"&gt;&amp;nbsp; public static IList&amp;lt;T&amp;gt; Create(IEnumerable&amp;lt;T&amp;gt; enumerable)&lt;BR&gt;&amp;nbsp; {&lt;BR&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; return Create(enumerable.GetEnumerator());&lt;BR&gt;&amp;nbsp; } &lt;/FONT&gt;
&lt;P&gt;&lt;FONT face="Courier New"&gt;&amp;nbsp; public static IList&amp;lt;T&amp;gt; Create(IEnumerator&amp;lt;T&amp;gt; enumerator)&lt;BR&gt;&amp;nbsp; {&lt;BR&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; if (enumerator.MoveNext())&lt;BR&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; return new LazyList&amp;lt;T&amp;gt;(enumerator.Current, enumerator);&lt;BR&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; return null;&lt;BR&gt;&amp;nbsp; } &lt;/FONT&gt;
&lt;P&gt;&lt;FONT face="Courier New"&gt;&amp;nbsp; public IList&amp;lt;T&amp;gt; Next&lt;BR&gt;&amp;nbsp; {&lt;BR&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; get&lt;BR&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; {&lt;BR&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; if (enumerator != null)&lt;BR&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; {&lt;BR&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; next = Create(enumerator);&lt;BR&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; enumerator = null;&lt;BR&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; }&lt;BR&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; return next;&lt;BR&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;}&lt;BR&gt;&amp;nbsp; } &lt;/FONT&gt;
&lt;P&gt;&lt;FONT face="Courier New"&gt;&amp;nbsp; public T Value { get { return value; } }&lt;BR&gt;}&lt;/FONT&gt;&lt;/P&gt;&lt;/BLOCKQUOTE&gt;
&lt;P&gt;But it should be noted that there is a critical difference between both of these definitions and the following definition of List&amp;lt;T&amp;gt;.&lt;/P&gt;
&lt;BLOCKQUOTE&gt;
&lt;P&gt;&lt;FONT face="Courier New"&gt;class List&amp;lt;T&amp;gt; : IList&amp;lt;T&amp;gt;&lt;BR&gt;{&lt;BR&gt;&amp;nbsp; T value;&lt;BR&gt;&amp;nbsp; IList&amp;lt;T&amp;gt; next; &lt;/FONT&gt;
&lt;P&gt;&lt;FONT face="Courier New"&gt;&amp;nbsp; public List(T value, IList&amp;lt;T&amp;gt; next)&lt;BR&gt;&amp;nbsp; {&lt;BR&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; this.value = value;&lt;BR&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; this.next = next;&lt;BR&gt;&amp;nbsp; } &lt;/FONT&gt;
&lt;P&gt;&lt;FONT face="Courier New"&gt;&amp;nbsp; public IList&amp;lt;T&amp;gt; Next { get { return next; } }&lt;BR&gt;&amp;nbsp; public T Value { get { return value; } } &lt;/FONT&gt;
&lt;P&gt;&lt;FONT face="Courier New"&gt;&amp;nbsp; public static IList&amp;lt;T&amp;gt; Empty { get { return null; } }&lt;BR&gt;}&lt;/FONT&gt;&lt;/P&gt;&lt;/BLOCKQUOTE&gt;
&lt;P&gt;Did you notice what it is?&amp;nbsp; The previous definitions were lazy but this definition is not.&amp;nbsp; The iterator did not describe the data itself but rather a process for sequencing data that will be executed possibly sometime in the future.&amp;nbsp; The LazyList also does not actually realize an entire list.&amp;nbsp; It describes a way to construct the next element of a list on demand.&amp;nbsp; But the definition of List does not defer anything to the future.&amp;nbsp; Now the question is, does it matter?&lt;/P&gt;&lt;img src="http://blogs.msdn.com/aggbug.aspx?PostID=1663771" width="1" height="1"&gt;</description><category domain="http://blogs.msdn.com/wesdyer/archive/tags/C_2300_/default.aspx">C#</category><category domain="http://blogs.msdn.com/wesdyer/archive/tags/Functional+Programming/default.aspx">Functional Programming</category></item></channel></rss>