<?xml version="1.0" encoding="utf-8"?>
<rss xmlns:atom="https://www.w3.org/2005/Atom" xmlns:sy="https://purl.org/rss/1.0/modules/syndication/" xmlns:dc="https://purl.org/dc/elements/1.1/" xmlns:content="https://purl.org/rss/1.0/modules/content/" xmlns:wfw="https://wellformedweb.org/CommentAPI/" xmlns:slash="https://purl.org/rss/1.0/modules/slash/"
  version="2.0">
  <channel>
    <title>Yet Another Language Geek</title>
    <atom:link
      href="https://docs.microsoft.com/archive/blogs/wesdyer/feed.xml"
      rel="self"
      type="application/rss+xml" />
    <link>https://docs.microsoft.com/archive/blogs/wesdyer/feed.xml</link>
    <description />
    <lastBuildDate>Sat, 04 Apr 2015 21:01:51 GMT</lastBuildDate>
    <language>en-US</language>
    <sy:updatePeriod>hourly</sy:updatePeriod>
    <sy:updateFrequency>1</sy:updateFrequency>
    <item>
      <title>A Brief Introduction to the Reactive Extensions for .NET, Rx</title>
      <link>https://docs.microsoft.com/archive/blogs/wesdyer/a-brief-introduction-to-the-reactive-extensions-for-net-rx</link>
      <pubDate>Wed, 18 Nov 2009 15:26:31 GMT</pubDate>
      <dc:creator><![CDATA[wesdyer]]></dc:creator>
      <guid
        isPermaLink="false">https://blogs.msdn.microsoft.com/wesdyer/2009/11/18/a-brief-introduction-to-the-reactive-extensions-for-net-rx/</guid>
      <description><![CDATA[Wow, it has been a long time since I have blogged.&#160; Yesterday, we made the first official...]]></description>
      <content:encoded><![CDATA[<p>Wow, it has been a long time since I have blogged.&#160; Yesterday, we made the first official public release of Rx on <a href="https://msdn.microsoft.com/en-us/devlabs/ee794896.aspx">devlabs</a>.&#160; And that means that I can now talk about what has been on my mind for the past while: Rx.&#160; What is Rx?&#160; Rx is short for the Reactive Extensions for .NET.&#160; Think of it as a prescription strength library for writing reactive programs in your favorite .NET language.</p>  <p>Today, I want to give you a brief introduction to Rx that complements my <a href="https://channel9.msdn.com/posts/J.Van.Gogh/Writing-your-first-Rx-Application/">screencast</a>.&#160; In subsequent posts, I will dive deep into the semantics of Rx providing detailed explanations and examples.&#160; Hopefully, this will positively impact your day to day work and allow you to have a lot of fun in the process.&#160; Please feel free to ask any questions that you may have or <a href="https://social.msdn.microsoft.com/Forums/en-US/rx/threads">provide feedback about Rx</a>.&#160; This first release is a sort of preview of the technology.&#160; We will provide regular updates that both extend and refine the library and we want you to be a part of that process.</p>  <p><strong>First Steps</strong></p>  <p>Rx is currently available for <a href="https://download.microsoft.com/download/6/2/A/62A3E195-254C-445A-8109-6AE77A28AB63/Rx_Net35_SP1.exe">.NET Framework 3.5 SP1</a>, <a href="https://download.microsoft.com/download/4/B/9/4B91A290-925C-4E2E-BEF3-996CF4B50661/Rx_Net4_Beta2.exe">.NET Framework 4 Beta 2</a>, and <a href="https://download.microsoft.com/download/9/6/B/96BE463C-F261-45CE-A4FA-D1052339505F/Rx_SL3.exe">Silverlight 3</a>.&#160; Download and install one of these versions and then open Visual Studio.</p>  <p><a href="https://msdnshared.blob.core.windows.net/media/TNBlogsFS/BlogFileStorage/blogs_msdn/wesdyer/WindowsLiveWriter/AGentleIntroductiontotheReactiveEx.NETRx_B78F/image_2.png" original-url="https://blogs.msdn.com/blogfiles/wesdyer/WindowsLiveWriter/AGentleIntroductiontotheReactiveEx.NETRx_B78F/image_2.png"><img style="border-bottom: 0px; border-left: 0px; display: inline; border-top: 0px; border-right: 0px" title="image" border="0" alt="image" src="https://msdnshared.blob.core.windows.net/media/TNBlogsFS/BlogFileStorage/blogs_msdn/wesdyer/WindowsLiveWriter/AGentleIntroductiontotheReactiveEx.NETRx_B78F/image_thumb.png" original-url="https://blogs.msdn.com/blogfiles/wesdyer/WindowsLiveWriter/AGentleIntroductiontotheReactiveEx.NETRx_B78F/image_thumb.png" width="244" height="65" /></a> </p>  <p>Create a WPF Application or a Silverlight Application.</p>  <p><a href="https://msdnshared.blob.core.windows.net/media/TNBlogsFS/BlogFileStorage/blogs_msdn/wesdyer/WindowsLiveWriter/AGentleIntroductiontotheReactiveEx.NETRx_B78F/image_6.png" original-url="https://blogs.msdn.com/blogfiles/wesdyer/WindowsLiveWriter/AGentleIntroductiontotheReactiveEx.NETRx_B78F/image_6.png"><img style="border-bottom: 0px; border-left: 0px; display: inline; border-top: 0px; border-right: 0px" title="image" border="0" alt="image" src="https://msdnshared.blob.core.windows.net/media/TNBlogsFS/BlogFileStorage/blogs_msdn/wesdyer/WindowsLiveWriter/AGentleIntroductiontotheReactiveEx.NETRx_B78F/image_thumb_2.png" original-url="https://blogs.msdn.com/blogfiles/wesdyer/WindowsLiveWriter/AGentleIntroductiontotheReactiveEx.NETRx_B78F/image_thumb_2.png" width="245" height="84" /></a> </p>  <p><a href="https://msdnshared.blob.core.windows.net/media/TNBlogsFS/BlogFileStorage/blogs_msdn/wesdyer/WindowsLiveWriter/AGentleIntroductiontotheReactiveEx.NETRx_B78F/image_8.png" original-url="https://blogs.msdn.com/blogfiles/wesdyer/WindowsLiveWriter/AGentleIntroductiontotheReactiveEx.NETRx_B78F/image_8.png"><img style="border-bottom: 0px; border-left: 0px; display: inline; border-top: 0px; border-right: 0px" title="image" border="0" alt="image" src="https://msdnshared.blob.core.windows.net/media/TNBlogsFS/BlogFileStorage/blogs_msdn/wesdyer/WindowsLiveWriter/AGentleIntroductiontotheReactiveEx.NETRx_B78F/image_thumb_3.png" original-url="https://blogs.msdn.com/blogfiles/wesdyer/WindowsLiveWriter/AGentleIntroductiontotheReactiveEx.NETRx_B78F/image_thumb_3.png" width="319" height="196" /></a> </p>  <p><strong>The Chrome</strong></p>  <p></p>  <p></p>  <p></p>  <p>When the designer opens, replace the existing Grid control with the following XAML.</p>  <blockquote>   <p><font color="#0000ff" face="Courier New">&lt;<font color="#800040">Canvas</font>&gt;        <br />&#160;&#160;&#160; &lt;<font color="#800000">TextBlock</font>        <br />&#160;&#160;&#160;&#160;&#160;&#160;&#160; <font color="#ff0000">x</font>:<font color="#ff0000">Name</font>=&quot;textBlock&quot;        <br />&#160;&#160;&#160;&#160;&#160;&#160;&#160; <font color="#ff0000">Text</font>=&quot;Rx Rocks!&quot; /&gt;        <br />&#160;&#160;&#160; &lt;<font color="#800000">Image         <br /></font>&#160;&#160;&#160;&#160;&#160;&#160;&#160; <font color="#ff0000">x</font>:<font color="#ff0000">Name</font>=&quot;image&quot;        <br />&#160;&#160;&#160;&#160;&#160;&#160;&#160; <font color="#ff0000">Source</font>=&quot;</font><a href="https://upload.wikimedia.org/wikipedia/commons/7/7a/Rx_symbol.png&quot;"><font color="#0000ff" face="Courier New">https://upload.wikimedia.org/wikipedia/commons/7/7a/Rx_symbol.png&quot;</font></a>      <br /><font color="#0000ff" face="Courier New">&#160;&#160;&#160;&#160;&#160;&#160;&#160; <font color="#ff0000">Width</font>=&quot;100&quot;        <br />&#160;&#160;&#160;&#160;&#160;&#160;&#160; <font color="#ff0000">Height</font>=&quot;100&quot;        <br />&#160;&#160;&#160;&#160;&#160;&#160;&#160; <font color="#ff0000">Canvas.Left</font>=&quot;0&quot;        <br />&#160;&#160;&#160;&#160;&#160;&#160;&#160; <font color="#ff0000">Canvas.Top</font>=&quot;25&quot; /&gt;        <br />&lt;/<font color="#800000">Canvas</font>&gt; </font></p> </blockquote>  <p>Then switch to the code view.</p>  <p><a href="https://msdnshared.blob.core.windows.net/media/TNBlogsFS/BlogFileStorage/blogs_msdn/wesdyer/WindowsLiveWriter/AGentleIntroductiontotheReactiveEx.NETRx_B78F/image_10.png" original-url="https://blogs.msdn.com/blogfiles/wesdyer/WindowsLiveWriter/AGentleIntroductiontotheReactiveEx.NETRx_B78F/image_10.png"><img style="border-bottom: 0px; border-left: 0px; display: inline; border-top: 0px; border-right: 0px" title="image" border="0" alt="image" src="https://msdnshared.blob.core.windows.net/media/TNBlogsFS/BlogFileStorage/blogs_msdn/wesdyer/WindowsLiveWriter/AGentleIntroductiontotheReactiveEx.NETRx_B78F/image_thumb_4.png" original-url="https://blogs.msdn.com/blogfiles/wesdyer/WindowsLiveWriter/AGentleIntroductiontotheReactiveEx.NETRx_B78F/image_thumb_4.png" width="216" height="64" /></a> </p>  <p><strong>Starting with Rx</strong></p>  <p>To begin using Rx, first add a reference to <strong>System.Reactive</strong> and <strong>System.CoreEx</strong>.&#160; The two other assemblies included with this release are System.Threading (task parallel library) and System.Interactive (more enumerable goodness).</p>  <p><a href="https://msdnshared.blob.core.windows.net/media/TNBlogsFS/BlogFileStorage/blogs_msdn/wesdyer/WindowsLiveWriter/AGentleIntroductiontotheReactiveEx.NETRx_B78F/image_12.png" original-url="https://blogs.msdn.com/blogfiles/wesdyer/WindowsLiveWriter/AGentleIntroductiontotheReactiveEx.NETRx_B78F/image_12.png"><img style="border-bottom: 0px; border-left: 0px; display: inline; border-top: 0px; border-right: 0px" title="image" border="0" alt="image" src="https://msdnshared.blob.core.windows.net/media/TNBlogsFS/BlogFileStorage/blogs_msdn/wesdyer/WindowsLiveWriter/AGentleIntroductiontotheReactiveEx.NETRx_B78F/image_thumb_5.png" original-url="https://blogs.msdn.com/blogfiles/wesdyer/WindowsLiveWriter/AGentleIntroductiontotheReactiveEx.NETRx_B78F/image_thumb_5.png" width="244" height="70" /></a> </p>  <p><a href="https://msdnshared.blob.core.windows.net/media/TNBlogsFS/BlogFileStorage/blogs_msdn/wesdyer/WindowsLiveWriter/AGentleIntroductiontotheReactiveEx.NETRx_B78F/image_14.png" original-url="https://blogs.msdn.com/blogfiles/wesdyer/WindowsLiveWriter/AGentleIntroductiontotheReactiveEx.NETRx_B78F/image_14.png"><img style="border-bottom: 0px; border-left: 0px; display: inline; border-top: 0px; border-right: 0px" title="image" border="0" alt="image" src="https://msdnshared.blob.core.windows.net/media/TNBlogsFS/BlogFileStorage/blogs_msdn/wesdyer/WindowsLiveWriter/AGentleIntroductiontotheReactiveEx.NETRx_B78F/image_thumb_6.png" original-url="https://blogs.msdn.com/blogfiles/wesdyer/WindowsLiveWriter/AGentleIntroductiontotheReactiveEx.NETRx_B78F/image_thumb_6.png" width="290" height="253" /></a> </p>  <p><a href="https://msdnshared.blob.core.windows.net/media/TNBlogsFS/BlogFileStorage/blogs_msdn/wesdyer/WindowsLiveWriter/AGentleIntroductiontotheReactiveEx.NETRx_B78F/image_16.png" original-url="https://blogs.msdn.com/blogfiles/wesdyer/WindowsLiveWriter/AGentleIntroductiontotheReactiveEx.NETRx_B78F/image_16.png"><img style="border-bottom: 0px; border-left: 0px; display: inline; border-top: 0px; border-right: 0px" title="image" border="0" alt="image" src="https://msdnshared.blob.core.windows.net/media/TNBlogsFS/BlogFileStorage/blogs_msdn/wesdyer/WindowsLiveWriter/AGentleIntroductiontotheReactiveEx.NETRx_B78F/image_thumb_7.png" original-url="https://blogs.msdn.com/blogfiles/wesdyer/WindowsLiveWriter/AGentleIntroductiontotheReactiveEx.NETRx_B78F/image_thumb_7.png" width="294" height="256" /></a>&#160;</p>  <p>Once you have added a reference to System.Reactive and System.CoreEx, then you can use the reactive operators found in Observable.</p>  <p><strong>Observable Sequences</strong></p>  <p>Observables, like enumerables, are sequences.&#160; The only difference is that the latter is pull-based and the former is push-based.&#160; Both sequences are a possibly empty sequence of values optionally followed by either normal termination or abnormal termination.</p>  <p>When you want to enumerate an enumerable:</p>  <blockquote>   <p>1.&#160; Get the enumerator from the enumerable</p>    <p>2.&#160; Call MoveNext and call Current on the enumerator for each value in the sequence</p>    <p>3.&#160; The sequence ends when MoveNext returns false (normal termination) or MoveNext or Current throws an exception (abnormal termination)</p> </blockquote>  <p>The user writes a foreach statement over an enumerable sequence.</p>  <blockquote>   <p><font face="Courier New"><font color="#0000ff">foreach</font> (<font color="#0000ff">var</font> x <font color="#0000ff">in</font> xs)        <br />&#160;&#160;&#160; F(x); </font></p> </blockquote>  <p>With enumerables, each value is pulled out of the source and bound to the iteration variable before executing the user code.&#160; Note that the consumer controls this process.</p>  <p>When you want to observe an observable sequence:</p>  <blockquote>   <p>1.&#160; Subscribe an observer to the observable</p>    <p>2.&#160; OnNext is called on the observer for each value in the sequence</p>    <p>3.&#160; The sequence ends when OnCompleted (normal termination) or OnError (abnormal termination) is called on the observer</p> </blockquote>  <p>The user writes a subscribe statement over an observable sequence.</p>  <blockquote>   <p><font face="Courier New">xs.Subscribe(x =&gt; F(x));</font></p> </blockquote>  <p>With observables, each value is pushed out of the source and bound to the handler variable before executing the user code.&#160; Note that the producer controls this process.</p>  <p><strong>Hello, World!</strong></p>  <p>Let’s write our first Rx application, the obligatory “Hello, World!” application.</p>  <p>Remember all those times that you wrote UI applications with asynchronous operations and got the dreaded Cross-Thread operation exception.</p>  <p><a href="https://msdnshared.blob.core.windows.net/media/TNBlogsFS/BlogFileStorage/blogs_msdn/wesdyer/WindowsLiveWriter/AGentleIntroductiontotheReactiveEx.NETRx_B78F/image_18.png" original-url="https://blogs.msdn.com/blogfiles/wesdyer/WindowsLiveWriter/AGentleIntroductiontotheReactiveEx.NETRx_B78F/image_18.png"><img style="border-bottom: 0px; border-left: 0px; display: inline; border-top: 0px; border-right: 0px" title="image" border="0" alt="image" src="https://msdnshared.blob.core.windows.net/media/TNBlogsFS/BlogFileStorage/blogs_msdn/wesdyer/WindowsLiveWriter/AGentleIntroductiontotheReactiveEx.NETRx_B78F/image_thumb_8.png" original-url="https://blogs.msdn.com/blogfiles/wesdyer/WindowsLiveWriter/AGentleIntroductiontotheReactiveEx.NETRx_B78F/image_thumb_8.png" width="337" height="189" /></a> </p>  <p>Well Rx, makes this simpler despite the fact that it has <strong>a lot</strong> of asynchronous and event-based operations going on at once.</p>  <p>The user may specify the default SynchronizationContext to which to send Rx messages.&#160; By default, it uses a reactive event loop except in Silverlight where it uses the dispatcher by default.&#160; The user can change this by setting Observable.Context to the appropriate SynchronizationContext.&#160; Rx provides a few commonly used synchronization contexts in the class SynchronizationContexts.</p>  <p>Since we are using WPF, we should set the default context to the dispatcher context.</p>  <blockquote>   <p><font face="Courier New"><font color="#008080">Observable</font>.Context = <font color="#008080">SynchronizationContexts</font>.CurrentDispatcher;</font> </p> </blockquote>  <p>Now, we can use the UI without getting cross-thread exceptions.</p>  <p>Rx includes a number of basic operations for constructing observable sequences.&#160; For example, Return creates a singleton sequence that contains an OnNext message with the specified value followed by an OnCompleted message.&#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.</p>  <p></p>  <p></p>  <p></p>  <blockquote>   <p><font face="Courier New"><font color="#0000ff">var</font> helloWorld = <font color="#008080">Observable</font>.Return(<font color="#800000">&quot;Hello, World!&quot;</font>); </font></p>    <p><font face="Courier New">helloWorld.Subscribe(value =&gt; textBlock.Text = value);</font></p> </blockquote>  <p>When we run the application, we see that the text is set to “Hello, World!”.</p>  <p><a href="https://msdnshared.blob.core.windows.net/media/TNBlogsFS/BlogFileStorage/blogs_msdn/wesdyer/WindowsLiveWriter/AGentleIntroductiontotheReactiveEx.NETRx_B78F/image_20.png" original-url="https://blogs.msdn.com/blogfiles/wesdyer/WindowsLiveWriter/AGentleIntroductiontotheReactiveEx.NETRx_B78F/image_20.png"><img style="border-bottom: 0px; border-left: 0px; display: inline; border-top: 0px; border-right: 0px" title="image" border="0" alt="image" src="https://msdnshared.blob.core.windows.net/media/TNBlogsFS/BlogFileStorage/blogs_msdn/wesdyer/WindowsLiveWriter/AGentleIntroductiontotheReactiveEx.NETRx_B78F/image_thumb_9.png" original-url="https://blogs.msdn.com/blogfiles/wesdyer/WindowsLiveWriter/AGentleIntroductiontotheReactiveEx.NETRx_B78F/image_thumb_9.png" width="244" height="244" /></a> </p>  <p><strong>A Second Step</strong></p>  <p>Another basic operation for constructing observable sequences, is the Interval operator.&#160; It creates an observable sequence that repeatedly sends an OnNext message after the specified time interval.&#160; For example, we can create an observable sequence that sends a message after every second.</p>  <blockquote>   <p><font face="Courier New"><font color="#0000ff">var</font> timer = <font color="#008080">Observable</font>.Interval(<font color="#008080">TimeSpan</font>.FromSeconds(1)); </font></p>    <p><font face="Courier New">timer.Subscribe(value =&gt; textBlock.Text = value.ToString());</font> </p> </blockquote>  <p><a href="https://msdnshared.blob.core.windows.net/media/TNBlogsFS/BlogFileStorage/blogs_msdn/wesdyer/WindowsLiveWriter/AGentleIntroductiontotheReactiveEx.NETRx_B78F/image_22.png" original-url="https://blogs.msdn.com/blogfiles/wesdyer/WindowsLiveWriter/AGentleIntroductiontotheReactiveEx.NETRx_B78F/image_22.png"><img style="border-bottom: 0px; border-left: 0px; display: inline; border-top: 0px; border-right: 0px" title="image" border="0" alt="image" src="https://msdnshared.blob.core.windows.net/media/TNBlogsFS/BlogFileStorage/blogs_msdn/wesdyer/WindowsLiveWriter/AGentleIntroductiontotheReactiveEx.NETRx_B78F/image_thumb_10.png" original-url="https://blogs.msdn.com/blogfiles/wesdyer/WindowsLiveWriter/AGentleIntroductiontotheReactiveEx.NETRx_B78F/image_thumb_10.png" width="244" height="244" /></a>&#160;</p>  <p><strong>Wrapping .NET Events</strong></p>  <p>Another source of observable sequences is existing .NET events and asynchronous computations.&#160; We can bring these existing reactive sources into Rx by using conversions.&#160; For example, we can convert .NET events to observable sequences using the FromEvent operator.&#160; The user must specify the type of EventArgs for the event, the target, and the event name.&#160; We can use this to convert the MouseDown event on the image to an observable sequence of events</p>  <blockquote>   <p><font face="Courier New"><font color="#0000ff">var</font> mouseDown = <font color="#008080">Observable</font>.FromEvent&lt;<font color="#008080">MouseButtonEventArgs</font>&gt;(image, <font color="#800000">&quot;MouseDown&quot;</font>);</font> </p> </blockquote>  <p><strong>LINQ to Rx</strong></p>  <p>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.&#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.</p>  <blockquote>   <p><font face="Courier New"><font color="#0000ff">var</font> mouseDown = <font color="#0000ff">from</font> evt <font color="#0000ff">in </font></font><font face="Courier New"><font color="#008080">Observable</font>.FromEvent&lt;<font color="#008080">MouseButtonEventArgs</font>&gt;(image, <font color="#800000">&quot;MouseDown&quot;</font>)        <br />&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; <font color="#0000ff">select</font> evt.EventArgs.GetPosition(image);</font> </p> </blockquote>  <p><strong>Composition</strong></p>  <p>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.</p>  <blockquote>   <p><font face="Courier New"><font color="#0000ff">var </font>q = timer.Until(mouseDown); </font></p>    <p><font face="Courier New">q.Subscribe(value =&gt; textBlock.Text = value.ToString()); </font></p> </blockquote>  <p><strong>Drag and Drop</strong></p>  <p>We can put together these simple pieces and build drag and drop.&#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.&#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.</p>  <p>What is the specification of drag and drop?&#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.</p>  <p>Therefore, we need three events: the mouse down on the image, the mouse move on the window, and the mouse up on the window.&#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.</p>  <blockquote>   <p><font face="Courier New"><font color="#0000ff">var</font> mouseDown = <font color="#0000ff">from</font> evt <font color="#0000ff">in</font> <font color="#008080">Observable</font>.FromEvent&lt;<font color="#008080">MouseButtonEventArgs</font>&gt;(image, <font color="#800000">&quot;MouseDown&quot;</font>)        <br />&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; <font color="#0000ff">select</font> evt.EventArgs.GetPosition(image); </font></p>    <p><font face="Courier New"><font color="#0000ff">var</font> mouseUp = <font color="#008080">Observable</font>.FromEvent&lt;<font color="#008080">MouseButtonEventArgs</font>&gt;(image, <font color="#800000">&quot;MouseUp&quot;</font>); </font></p>    <p><font face="Courier New"><font color="#0000ff">var</font> mouseMove = <font color="#0000ff">from</font> evt <font color="#0000ff">in</font> <font color="#008080">Observable</font>.FromEvent&lt;<font color="#008080">MouseEventArgs</font>&gt;(image, &quot;MouseMove&quot;)        <br />&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; <font color="#0000ff">select</font> evt.EventArgs.GetPosition(<font color="#0000ff">this</font>); </font></p> </blockquote>  <p>Now, we can write a query that expresses our intent.&#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.&#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.</p>  <blockquote>   <p><font face="Courier New"><font color="#0000ff">var</font> q = <font color="#0000ff">from</font> imageOffset <font color="#0000ff">in</font> mouseDown        <br />&#160;&#160;&#160;&#160;&#160;&#160;&#160; <font color="#0000ff">from</font> pos <font color="#0000ff">in</font> mouseMove.Until(mouseUp)        <br />&#160;&#160;&#160;&#160;&#160;&#160;&#160; <font color="#0000ff">select new </font>{ X = pos.X - imageOffset.X, Y = pos.Y - imageOffset.Y }; </font></p> </blockquote>  <p>Finally, we can subscribe to the observable sequence of positions and update the position of the image.</p>  <blockquote>   <p><font face="Courier New">q.Subscribe(value =&gt;       <br />&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; {        <br />&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; <font color="#008080">Canvas</font>.SetLeft(image, value.X);        <br />&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; <font color="#008080">Canvas</font>.SetTop(image, value.Y);        <br />&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; });</font></p> </blockquote>  <p><a href="https://msdnshared.blob.core.windows.net/media/TNBlogsFS/BlogFileStorage/blogs_msdn/wesdyer/WindowsLiveWriter/AGentleIntroductiontotheReactiveEx.NETRx_B78F/image_24.png" original-url="https://blogs.msdn.com/blogfiles/wesdyer/WindowsLiveWriter/AGentleIntroductiontotheReactiveEx.NETRx_B78F/image_24.png"><img style="border-bottom: 0px; border-left: 0px; display: inline; border-top: 0px; border-right: 0px" title="image" border="0" alt="image" src="https://msdnshared.blob.core.windows.net/media/TNBlogsFS/BlogFileStorage/blogs_msdn/wesdyer/WindowsLiveWriter/AGentleIntroductiontotheReactiveEx.NETRx_B78F/image_thumb_11.png" original-url="https://blogs.msdn.com/blogfiles/wesdyer/WindowsLiveWriter/AGentleIntroductiontotheReactiveEx.NETRx_B78F/image_thumb_11.png" width="244" height="244" /></a>&#160;</p>  <p><strong>Looking Forward</strong></p>  <p></p>  <p>Drag and drop is fun, but it is only one small example of the power of Rx.&#160; Next time, we will start our deep dive into the semantics of Rx.&#160; Until then take the time to download it and take it for a test drive.</p>]]></content:encoded>
    </item>
    <item>
      <title>The Marvels of Monads</title>
      <link>https://docs.microsoft.com/archive/blogs/wesdyer/the-marvels-of-monads</link>
      <pubDate>Thu, 10 Jan 2008 19:06:13 GMT</pubDate>
      <dc:creator><![CDATA[wesdyer]]></dc:creator>
      <guid
        isPermaLink="false">https://blogs.msdn.microsoft.com/wesdyer/2008/01/10/the-marvels-of-monads/</guid>
      <description><![CDATA[If the word &quot;continuation&quot; causes eyes to glaze over, then the word &quot;monad&quot;...]]></description>
      <content:encoded><![CDATA[<p>If the word <a href="https://blogs.msdn.com/wesdyer/archive/2007/12/22/continuation-passing-style.aspx">&quot;continuation&quot;</a> causes eyes to glaze over, then the word &quot;monad&quot; induces mental paralysis.&#160; Perhaps, this is why some have begun inventing more benign names for monads.</p>  <p>These days, monads are the celebrities of programming language theory.&#160; They gloss the cover of blogs and have been <a href="https://www.loria.fr/~kow/monads/index.html">compared to everything</a> from <a href="https://www.haskell.org/haskellwiki/Monads_as_containers">boxes of fruit</a> to <a href="https://www.haskell.org/haskellwiki/Meet_Bob_The_Monadic_Lover">love affairs</a>.&#160; Nerds everywhere are exclaiming that the experience of understanding monads causes a <a href="https://groups.google.com/group/comp.lang.functional/browse_thread/thread/346dd6767ecb3851">pleasantly</a> <a href="https://koweycode.blogspot.com/2006/08/does-haskell-hurt-your-brain.html">painful</a> <a href="https://lambda-the-ultimate.org/node/724">mental sensation</a>.</p>  <p>Like continuations, monads are simpler than they sound and are very useful in many situations.&#160; In fact, programmers write code in a variety of languages that implicitly use common monads without even breaking a sweat.</p>  <p><a href="https://lambda-the-ultimate.org/node/92">With</a> <a href="https://james-iry.blogspot.com/2007/09/monads-are-elephants-part-1.html">all</a> <a href="https://www.haskell.org/tutorial/monads.html">of</a> <a href="https://moonbase.rydia.net/mental/writings/programming/monads-in-ruby/00introduction.html">the</a> <a href="https://sigfpe.blogspot.com/2006/08/you-could-have-invented-monads-and.html">attention</a> <a href="https://www.alpheccar.org/en/posts/show/60">that</a> <a href="https://patryshev.com/monad/m-intro.html">monads</a> <a href="https://www.engr.mun.ca/~theo/Misc/haskell_and_monads.htm">get</a>, why am I writing yet another explanation of monads?&#160; Not to compare them to some everyday occurrence or to chronicle my journey to understanding.&#160; I explain monads because I need monads.&#160; They elegantly solve programming problems in a number of languages and contexts.</p>  <p><strong>Introducing Monads</strong></p>  <p><a href="https://en.wikipedia.org/wiki/Monad_%28category_theory%29">Monads</a> come from <a href="https://en.wikipedia.org/wiki/Category_theory">category theory</a>.&#160; <a href="https://www.disi.unige.it/person/MoggiE/ftp/ic91.pdf">Moggi introduced them</a> to computer scientists to aid in the analysis of the semantics of computations.&#160; In an excellent paper, <em><a href="https://coblitz.codeen.org:3125/citeseer.ist.psu.edu/cache/papers/cs/4583/http:zSzzSzcm.bell-labs.comzSzwhozSzwadlerzSztopicszSz..zSzpaperszSzessencezSzessence.pdf/wadler92essence.pdf">The Essence of Functional Programming</a></em>, Wadler showed that monads are generally useful in computer programs to compose together functions which operate on amplified values rather than values.&#160; <a href="https://en.wikipedia.org/wiki/Monads_in_functional_programming">Monads</a> became <a href="https://www.haskell.org/all_about_monads/html/index.html">an important part</a> of the programming language Haskell where they tackle <a href="https://research.microsoft.com/~simonpj/papers/marktoberdorf/mark.pdf">the awkward squad</a>: IO, concurrency, exceptions, and foreign-function calls.</p>  <p>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.&#160; This is unfortunate, because monads are more broadly applicable.</p>  <p><strong>Controlling Complexity</strong></p>  <p>Composition is the key to controlling complexity in software.&#160; In <em><a href="https://mitpress.mit.edu/sicp/">The Structure and Interpretation of Computer Programs</a></em>, Abelson and Sussman argue that composition beautifully expresses complex systems from simple patterns.</p>  <blockquote>   <p>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.</p> </blockquote>  <p>One form of composition, function composition, succinctly describes the dependencies between function calls.&#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.</p>  <blockquote>   <pre class="code"><span style="color: blue">public static </span><span style="color: #2b91af">Func</span>&lt;T, V&gt; Compose&lt;T, U, V&gt;(<span style="color: blue">this </span><span style="color: #2b91af">Func</span>&lt;U, V&gt; f, <span style="color: #2b91af">Func</span>&lt;T, U&gt; g)
{
    <span style="color: blue">return </span>x =&gt; f(g(x));
}</pre>
</blockquote>
<a href="https://11011.net/software/vspaste"></a>

<p>For example, instead of applying <em>g</em> to the value <em>x</em> and then applying <em>f</em> to the result, compose <em>f</em> with <em>g</em> and then apply the result to the value <em>x</em>.&#160; The key difference is the abstraction of the dependency between <em>f</em> and <em>g</em>.</p>

<blockquote>
  <pre class="code"><span style="color: blue">var </span>r = f(g(x));         <font color="#008000">// without function composition</font>
<span style="color: blue">var </span>r = f.Compose(g)(x); <font color="#008000">// with function composition</font></pre>
</blockquote>
<a href="https://11011.net/software/vspaste"></a>

<p>Given the function <em>Identity</em>, function composition must obey three laws.</p>

<blockquote>
  <pre class="code"><span style="color: blue">public static </span>T Identity&lt;T&gt;(<span style="color: blue">this </span>T value)
{
    <span style="color: blue">return </span>value;
}</pre>
</blockquote>

<blockquote>
  <p><strong>1.&#160; Left identity</strong></p>

  <p>&#160;&#160;&#160;&#160; Identity.Compose(f) = f</p>

  <p><strong>2.&#160; Right identity</strong></p>

  <p>&#160;&#160;&#160;&#160; f.Compose(Identity) = f</p>

  <p><strong>3.&#160; Associative</strong></p>

  <p>&#160;&#160;&#160;&#160; f.Compose(g.Compose(h)) = (f.Compose(g)).Compose(h)</p>
</blockquote>

<p>Often, values are not enough.&#160; Constructed types amplify values.&#160; The type <em>IEnumerable&lt;T&gt;</em> represents a lazily computed list of values of type <em>T</em>.&#160; The type <em>Nullable&lt;T&gt;</em> represents a possibly missing value of type <em>T</em>.&#160; The type <em>Func&lt;Func&lt;T, Answer&gt;, Answer&gt; </em>represents a function, which returns an <em>Answer</em> given a continuation, which takes a <em>T </em>and returns an <em>Answer</em>.&#160; Each of these types amplifies the type <em>T</em>.</p>

<p>Suppose that instead of composing functions which return values, we compose functions which take values and return amplified values.&#160; Let <em>M&lt;T&gt;</em> denote the type of the amplified values.</p>

<blockquote>
  <pre class="code"><span style="color: blue">public static </span><span style="color: #2b91af">Func</span>&lt;T, <span style="color: #2b91af">M</span>&lt;V&gt;&gt; Compose&lt;T, U, V&gt;(<span style="color: blue">this </span><span style="color: #2b91af">Func</span>&lt;U, <span style="color: #2b91af">M</span>&lt;V&gt;&gt; f, <span style="color: #2b91af">Func</span>&lt;T, <span style="color: #2b91af">M</span>&lt;U&gt;&gt; g)
{
    <span style="color: blue">return </span>x =&gt; f(g(x)); <span style="color: green">// error, g(x) returns M&lt;U&gt; and f takes U
</span>}</pre>
</blockquote>
<a href="https://11011.net/software/vspaste"></a>

<p>Function composition fails, because the return and input types do not match.&#160; Composition with amplified values requires a function that accesses the underlying value and feeds it to the next function.&#160; Call that function &quot;Bind&quot; and use it to define function composition.</p>

<blockquote>
  <pre class="code"><span style="color: blue">public static </span><span style="color: #2b91af">Func</span>&lt;T, <span style="color: #2b91af">M</span>&lt;V&gt;&gt; Compose&lt;T, U, V&gt;(<span style="color: blue">this </span><span style="color: #2b91af">Func</span>&lt;U, <span style="color: #2b91af">M</span>&lt;V&gt;&gt; f, <span style="color: #2b91af">Func</span>&lt;T, <span style="color: #2b91af">M</span>&lt;U&gt;&gt; g)
{
    <span style="color: blue">return </span>x =&gt; Bind(g(x), f);
}</pre>
</blockquote>
<a href="https://11011.net/software/vspaste"></a>

<p>The input and output types determine the signature of <em>Bind.</em>&#160; Therefore, <em>Bind</em> takes an amplified value, M&lt;<em>U&gt;,</em> and a function from <em>U</em>&#160; to <em>M&lt;V&gt;</em>, and returns an amplified value, <em>M&lt;V&gt;</em>.</p>

<blockquote>
  <pre class="code"><span style="color: blue">public static </span><span style="color: #2b91af">M</span>&lt;V&gt; Bind&lt;U, V&gt;(<span style="color: blue">this </span><span style="color: #2b91af">M</span>&lt;U&gt; m, <span style="color: #2b91af">Func</span>&lt;U, <span style="color: #2b91af">M</span>&lt;V&gt;&gt; k)</pre>
</blockquote>
<a href="https://11011.net/software/vspaste"></a>

<p>The body of <em>Bind</em> depends on the mechanics of the amplified values, <em>M&lt;T&gt;</em>.&#160; Each amplified type will need a distinct definition of <em>Bind</em>.</p>

<p>In addition to <em>Bind</em>, define a function which takes an unamplified value and amplifies it.&#160; Call this function &quot;Unit&quot;.</p>

<blockquote>
  <pre class="code"><span style="color: blue">public static </span><span style="color: #2b91af">M</span>&lt;T&gt; Unit&lt;T&gt;(<span style="color: blue">this </span>T value)</pre>
</blockquote>

<p>Together the amplified type, <em>M&lt;T&gt;</em>, the function <em>Bind</em>, and the function <em>Unit</em> enable function composition with amplified values.</p>

<p><strong>Meet the Monads</strong></p>

<p>Viola, we have invented monads.</p>

<p>Monads are a triple consisting of a type, a <em>Unit</em> function, and a <em>Bind</em> function.&#160; Furthermore, to be a monad, the triple must satisfy three laws:</p>

<blockquote>
  <p><strong>1.&#160; Left Identity</strong></p>

  <p>&#160;&#160;&#160;&#160; Bind(Unit(e), k) = k(e)</p>

  <p><strong>2.&#160; Right Identity</strong></p>

  <p>&#160;&#160;&#160;&#160; Bind(m, Unit) = m</p>

  <p><strong>3.&#160; Associative</strong></p>

  <p>&#160;&#160;&#160;&#160; Bind(m, x =&gt; Bind(k(x), y =&gt; h(y)) = Bind(Bind(m, x =&gt; k(x)), y =&gt; h(y))</p>
</blockquote>

<p>The laws are similar to those of function composition.&#160; This is not a coincidence.&#160; They guarantee that the monad is well behaved and composition works properly.</p>

<p>To define a particular monad, the writer supplies the triple, thereby specifying the mechanics of the amplified values.</p>

<p><strong>The Identity Monad</strong></p>

<p>The simplest monad is the <em>Identity</em> monad.&#160; The type represents a wrapper containing a value.</p>

<blockquote>
  <pre class="code"><span style="color: blue">class </span><span style="color: #2b91af">Identity</span>&lt;T&gt;
{
    <span style="color: blue">public </span>T Value { <span style="color: blue">get</span>; <span style="color: blue">private set</span>; }
    <span style="color: blue">public </span>Identity(T value) { <span style="color: blue">this</span>.Value = value; }
}</pre>
</blockquote>
<a href="https://11011.net/software/vspaste"></a><a href="https://11011.net/software/vspaste"></a>

<p>The <em>Unit</em> function takes a value and returns a new instance of <em>Identity</em>, which wraps the value.</p>

<blockquote>
  <pre class="code"><span style="color: blue">static </span><span style="color: #2b91af">Identity</span>&lt;T&gt; Unit&lt;T&gt;(T value)
{
    <span style="color: blue">return new </span><span style="color: #2b91af">Identity</span>&lt;T&gt;(value);
}</pre>
</blockquote>
<a href="https://11011.net/software/vspaste"></a><a href="https://11011.net/software/vspaste"></a>

<p>The bind function takes an instance of <em>Identity</em>, unwraps the value, and invokes the delegate, <em>k</em>, with the<em> </em>unwrapped value.&#160; The result is a new instance of <em>Identity</em>. </p>

<blockquote>
  <pre class="code"><span style="color: blue">static </span><span style="color: #2b91af">Identity</span>&lt;U&gt; Bind&lt;T,U&gt;(<span style="color: #2b91af">Identity</span>&lt;T&gt; id, <span style="color: #2b91af">Func</span>&lt;T,<span style="color: #2b91af">Identity</span>&lt;U&gt;&gt; k)
{
    <span style="color: blue">return </span>k(id.Value);
}</pre>
</blockquote>
<a href="https://11011.net/software/vspaste"></a>

<p>Consider a simple program that creates two <em>Identity </em>wrappers and performs an operation on the wrapped values.&#160; First, bind <em>x</em> to the value within the wrapper containing the value five.&#160; Then, bind <em>y </em>to the value within the wrapper containing the value six.&#160; Finally, add the values,<em> x</em> and <em>y,</em> together.&#160; The result is an instance of <em>Identity</em> wrapping the value eleven.</p>

<blockquote>
  <p><font face="Courier New"><span style="color: blue">var </span>r = Bind(Unit(5), x =&gt; 

      <br />&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; Bind(Unit(6), y =&gt; 

      <br />&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; Unit(x + y))); 

      <br />

      <br /><span style="color: #2b91af">Console</span>.WriteLine(r.Value);</font></p>
</blockquote>
<a href="https://11011.net/software/vspaste"></a><a href="https://11011.net/software/vspaste"></a><a href="https://11011.net/software/vspaste"></a>

<p>While this works, it is rather clumsy.&#160; It would be nice to have syntax for dealing with the monad.&#160; Fortunately, we do.</p>

<p>C# 3.0 introduced query comprehensions which are actually monad comprehensions in disguise.&#160; We can rewrite the identity monad to use LINQ.&#160; Perhaps, it should have been called LINM (Language INtegrated Monads), but it just doesn't have the same ring to it.</p>

<p>Rename the method <em>Unit</em> to <em>ToIdentity </em>and <em>Bind</em> to <em>SelectMany</em>.&#160; Then, make them both extension methods.</p>

<blockquote>
  <pre class="code"><span style="color: blue">public static </span><span style="color: #2b91af">Identity</span>&lt;T&gt; ToIdentity&lt;T&gt;(<span style="color: blue">this </span>T value)
{
    <span style="color: blue">return new </span><span style="color: #2b91af">Identity</span>&lt;T&gt;(value);
}

<span style="color: blue">public static </span><span style="color: #2b91af">Identity</span>&lt;U&gt; SelectMany&lt;T, U&gt;(<span style="color: blue">this </span><span style="color: #2b91af">Identity</span>&lt;T&gt; id, <span style="color: #2b91af">Func</span>&lt;T, <span style="color: #2b91af">Identity</span>&lt;U&gt;&gt; k)
{
    <span style="color: blue">return </span>k(id.Value);
}</pre>
</blockquote>
<a href="https://11011.net/software/vspaste"></a>

<p>The changes impact the calling code.</p>

<blockquote>
  <pre class="code"><span style="color: blue">var </span>r = 5.ToIdentity().SelectMany(
            x =&gt; 6.ToIdentity().SelectMany(
                y =&gt; (x + y).ToIdentity()));

<span style="color: #2b91af">Console</span>.WriteLine(r.Value);</pre>
</blockquote>
<a href="https://11011.net/software/vspaste"></a>

<p>Equivalent methods are part of the standard query operators defined for LINQ.&#160; However, the standard query operators also include a slightly different version of <em>SelectMany</em> for performance reasons.&#160; It combines <em>Bind</em> with <em>Unit</em>, so that lambdas are not deeply nested.&#160; The signature is the same except for an extra argument that is a delegate which takes two arguments and returns a value.&#160; The delegate combines the two values together.&#160; This version of <em>SelectMany</em> binds <em>x </em>to the wrapped value, applies <em>k</em> to <em>x</em>, binds the result to <em>y</em>, and then applies the combining function, <em>s,</em> to <em>x</em> and <em>y.&#160; </em>The resultant value is wrapped and returned.</p>

<blockquote>
  <pre class="code"><span style="color: blue">public static </span><span style="color: #2b91af">Identity</span>&lt;V&gt; SelectMany&lt;T, U, V&gt;(<span style="color: blue">this </span><span style="color: #2b91af">Identity</span>&lt;T&gt; id, <span style="color: #2b91af">Func</span>&lt;T, <span style="color: #2b91af">Identity</span>&lt;U&gt;&gt; k, <span style="color: #2b91af">Func</span>&lt;T,U,V&gt; s)
{
    <span style="color: blue">return </span>id.SelectMany(x =&gt; k(x).SelectMany(y =&gt; s(x, y).ToIdentity()));
}</pre>
  <a href="https://11011.net/software/vspaste"></a><a href="https://11011.net/software/vspaste"></a></blockquote>
<a href="https://11011.net/software/vspaste"></a>

<p>Of course, we can remove some of the code from the generalized solution by using our knowledge of the <em>Identity</em> monad.</p>

<blockquote>
  <pre class="code"><span style="color: blue">public static </span><span style="color: #2b91af">Identity</span>&lt;V&gt; SelectMany&lt;T, U, V&gt;(<span style="color: blue">this </span><span style="color: #2b91af">Identity</span>&lt;T&gt; id, <span style="color: #2b91af">Func</span>&lt;T, <span style="color: #2b91af">Identity</span>&lt;U&gt;&gt; k, <span style="color: #2b91af">Func</span>&lt;T,U,V&gt; s)
{
    <span style="color: blue">return </span>s(id.Value, k(id.Value).Value).ToIdentity();
}</pre>
</blockquote>
<a href="https://11011.net/software/vspaste"></a>

<p>The call-site does not need to nest lambdas.</p>

<blockquote>
  <pre class="code"><span style="color: blue">var </span>r = 5.ToIdentity()
         .SelectMany(x =&gt; 6.ToIdentity(), (x, y) =&gt; x + y);

<span style="color: #2b91af">Console</span>.WriteLine(r.Value);</pre>
</blockquote>
<a href="https://11011.net/software/vspaste"></a>

<p>With the new definition of <em>SelectMany</em>, programmers can use C#'s query comprehension syntax.&#160; The <em>from </em>notation binds the introduced variable to the value wrapped by the expression on the right.&#160; This allows subsequent expressions to use the wrapped values without directly calling <em>SelectMany</em>.</p>

<blockquote>
  <pre class="code"><span style="color: blue">var </span>r = <span style="color: blue">from </span>x <span style="color: blue">in </span>5.ToIdentity()
        <span style="color: blue">from </span>y <span style="color: blue">in </span>6.ToIdentity()
        <span style="color: blue">select </span>x + y;</pre>
</blockquote>
<a href="https://11011.net/software/vspaste"></a>

<p>Since the original <em>SelectMany</em> definition corresponds directly to the monadic <em>Bind</em> function and because the existence of a generalized transformation has been demonstrated, the remainder of the post will use the original signature.&#160; But, keep in mind that the second definition is the one used by the query syntax.</p>

<p><strong>The Maybe Monad</strong></p>

<p>The <em>Identity</em> monad is an example of a monadic container type where the <em>Identity</em> monad wrapped a value.&#160; If we change the definition to contain either a value or a missing value then we have the <em>Maybe</em> monad.</p>

<p>Again, we need a type definition.&#160; The <em>Maybe</em> type is similar to the <em>Identity</em> type but adds a property denoting whether a value is missing.&#160; It also has a predefined instance, <em>Nothing</em>, representing all instances lacking a value.</p>

<blockquote>
  <pre class="code"><span style="color: blue">class </span><span style="color: #2b91af">Maybe</span>&lt;T&gt;
{
    <span style="color: blue">public readonly static </span><span style="color: #2b91af">Maybe</span>&lt;T&gt; Nothing = <span style="color: blue">new </span><span style="color: #2b91af">Maybe</span>&lt;T&gt;();
    <span style="color: blue">public </span>T Value { <span style="color: blue">get</span>; <span style="color: blue">private set</span>; }
    <span style="color: blue">public bool </span>HasValue { <span style="color: blue">get</span>; <span style="color: blue">private set</span>; }
    Maybe()
    {
        HasValue = <span style="color: blue">false</span>;
    }
    <span style="color: blue">public </span>Maybe(T value)
    {
        Value = value;
        HasValue = <span style="color: blue">true</span>;
    }
}</pre>
</blockquote>

<p>The <em>Unit</em> function takes a value and constructs a <em>Maybe</em> instance, which wraps the value.</p>

<blockquote>
  <pre class="code"><span style="color: blue">public static </span><span style="color: #2b91af">Maybe</span>&lt;T&gt; ToMaybe&lt;T&gt;(<span style="color: blue">this </span>T value)
{
    <span style="color: blue">return new </span><span style="color: #2b91af">Maybe</span>&lt;T&gt;(value);
}</pre>
</blockquote>
<a href="https://11011.net/software/vspaste"></a>

<p>The <em>Bind</em> function takes a <em>Maybe</em> instance and if there is a value then it applies the delegate to the contained value.&#160; Otherwise, it returns <em>Nothing</em>.</p>

<blockquote>
  <pre class="code"><span style="color: blue">public static </span><span style="color: #2b91af">Maybe</span>&lt;U&gt; SelectMany&lt;T, U&gt;(<span style="color: blue">this </span><span style="color: #2b91af">Maybe</span>&lt;T&gt; m, <span style="color: #2b91af">Func</span>&lt;T, <span style="color: #2b91af">Maybe</span>&lt;U&gt;&gt; k)
{
    <span style="color: blue">if </span>(!m.HasValue)
        <span style="color: blue">return </span><span style="color: #2b91af">Maybe</span>&lt;U&gt;.Nothing;
    <span style="color: blue">return </span>k(m.Value);
}</pre>
</blockquote>
<a href="https://11011.net/software/vspaste"></a>

<p>The programmer can use the comprehension syntax to work with the <em>Maybe</em> monad.&#160; For example, create an instance of <em>Maybe</em> containing the value five and add it to <em>Nothing</em>.</p>

<blockquote>
  <pre class="code"><span style="color: blue">var </span>r = <span style="color: blue">from </span>x <span style="color: blue">in </span>5.ToMaybe()
        <span style="color: blue">from </span>y <span style="color: blue">in </span><span style="color: #2b91af">Maybe</span>&lt;<span style="color: blue">int</span>&gt;.Nothing
        <span style="color: blue">select </span>x + y;

<span style="color: #2b91af">Console</span>.WriteLine(r.HasValue ? r.Value.ToString() : <span style="color: #a31515">&quot;Nothing&quot;</span>);</pre>
</blockquote>
<a href="https://11011.net/software/vspaste"></a>

<p>The result is &quot;Nothing&quot;.&#160; We have implemented the null propagation of nullables without explicit language support.</p>

<p><strong>The List Monad</strong></p>

<p>Another important container type is the list type.&#160; In fact, the list monad is at the heart of LINQ.&#160; The type <em>IEnumerable&lt;T&gt; </em>denotes a lazily computed list.</p>

<p>The <em>Unit</em> function takes a value and returns a list, which contains only that value.</p>

<blockquote>
  <pre class="code"><span style="color: blue">public static </span><span style="color: #2b91af">IEnumerable</span>&lt;T&gt; ToList&lt;T&gt;(<span style="color: blue">this </span>T value)
{
    <span style="color: blue">yield return </span>value;
}</pre>
</blockquote>
<a href="https://11011.net/software/vspaste"></a>

<p>The <em>Bind</em> function takes an <em>IEnumerable&lt;T&gt;</em>, a delegate, which takes a <em>T</em> and returns an <em>IEnumerable&lt;U&gt;</em>, and returns an <em>IEnumerable&lt;U&gt;</em>.</p>

<blockquote>
  <pre class="code"><span style="color: blue">public static </span><span style="color: #2b91af">IEnumerable</span>&lt;U&gt; SelectMany&lt;T, U&gt;(<span style="color: blue">this </span><span style="color: #2b91af">IEnumerable</span>&lt;T&gt; m, <span style="color: #2b91af">Func</span>&lt;T, <span style="color: #2b91af">IEnumerable</span>&lt;U&gt;&gt; k)
{
    <span style="color: blue">foreach </span>(<span style="color: blue">var </span>x <span style="color: blue">in </span>m)
        <span style="color: blue">foreach </span>(<span style="color: blue">var </span>y <span style="color: blue">in </span>k(x))
            <span style="color: blue">yield return </span>y;
}</pre>
</blockquote>
<a href="https://11011.net/software/vspaste"></a>

<p>Now, the programmer can write the familiar query expressions with <em>IEnumerable&lt;T&gt;.</em></p>

<blockquote>
  <pre class="code"><span style="color: blue">var </span>r = <span style="color: blue">from </span>x <span style="color: blue">in new</span>[] { 0, 1, 2 }
        <span style="color: blue">from </span>y <span style="color: blue">in new</span>[] { 0, 1, 2 }
        <span style="color: blue">select </span>x + y;

<span style="color: blue">foreach </span>(<span style="color: blue">var </span>i <span style="color: blue">in </span>r)
    <span style="color: #2b91af">Console</span>.WriteLine(i);</pre>
</blockquote>
<a href="https://11011.net/software/vspaste"></a>

<p>Remember that it is the monad that enables the magic.</p>

<p><strong>The Continuation Monad</strong></p>

<p>The continuation monad answers <a href="https://blogs.msdn.com/wesdyer/archive/2007/12/22/continuation-passing-style.aspx">the question that was posed at the end of the last post</a>: how can a programmer write CPS code in a more palatable way?</p>

<p>The type of the continuation monad, <em>K</em>, is a delegate which when given a continuation, which takes an argument and returns an answer, will return an answer.</p>

<blockquote>
  <pre class="code"><span style="color: blue">delegate </span>Answer <span style="color: #2b91af">K</span>&lt;T,Answer&gt;(<span style="color: #2b91af">Func</span>&lt;T,Answer&gt; k);</pre>
</blockquote>

<p>The type <em>K</em> fundamentally differs from types <em>Identity&lt;T&gt;</em>, <em>Maybe&lt;T&gt;</em>, and <em>IEnumerable&lt;T&gt;</em>.&#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.&#160; Rather, it composes together continuations the user writes.</p>

<p>To be a monad, there must be a <em>Unit</em> function which takes a <em>T </em>and returns a <em>K&lt;T</em>,<em>Answer&gt;</em> for some answer type.</p>

<blockquote>
  <pre class="code"><span style="color: blue">public static </span><span style="color: #2b91af">K</span>&lt;T, Answer&gt; ToContinuation&lt;T, Answer&gt;(<span style="color: blue">this </span>T value)</pre>
</blockquote>
<a href="https://11011.net/software/vspaste"></a>

<p>What should it do?&#160; When in doubt, look to the types.&#160;&#160; The method takes a <em>T</em> and returns a function, which takes a function from <em>T</em> to <em>Answer</em>, and returns an <em>Answer</em>.&#160; Therefore, the method must return a function and the only argument of that function must be a function from <em>T</em> to <em>Answer</em>.&#160; Call the argument <em>c</em>.</p>

<blockquote>
  <pre class="code"><span style="color: blue">return </span>(<span style="color: #2b91af">Func</span>&lt;T, Answer&gt; c) =&gt; ...</pre>
</blockquote>
<a href="https://11011.net/software/vspaste"></a>

<p>The body of the lambda must return a value of type <em>Answer</em>.&#160; Values of type <em>Func&lt;T,Answer&gt;</em> and a <em>T</em> are<em>&#160;</em>available.&#160; Apply <em>c</em> to <em>value</em> and the result is of type <em>Answer.</em></p>

<blockquote>
  <pre class="code"><span style="color: blue">return </span>(<span style="color: #2b91af">Func</span>&lt;T, Answer&gt; c) =&gt; c(value);</pre>
</blockquote>
<a href="https://11011.net/software/vspaste"></a>

<p>To be a monad, <em>Bind</em> must take a <em>K&lt;T,Answer&gt;</em> and a function from <em>T </em>to <em>K&lt;U, Answer&gt;</em> and return a <em>K&lt;U, Answer&gt;</em>.</p>

<blockquote>
  <pre class="code"><span style="color: blue">public static </span><span style="color: #2b91af">K</span>&lt;U, Answer&gt; SelectMany&lt;T, U, Answer&gt;(<span style="color: blue">this </span><span style="color: #2b91af">K</span>&lt;T, Answer&gt; m, <span style="color: #2b91af">Func</span>&lt;T, <span style="color: #2b91af">K</span>&lt;U, Answer&gt;&gt; k)</pre>
</blockquote>
<a href="https://11011.net/software/vspaste"></a>

<p>But what about the body?&#160; The result must be of type <em>K&lt;U, Answer&gt;</em>, but how is a result of the correct type formed?</p>

<p>Expand <em>K</em>'s definition to gain some insight.</p>

<blockquote>
  <p><strong>return type</strong></p>

  <p><strong>&#160;&#160;&#160;&#160; </strong><font face="Courier New"><span style="color: blue"><font color="#008080">Func</font></span>&lt;<font color="#008080">Func</font>&lt;U, Answer&gt;, Answer&gt;</font></p>

  <p><strong><em>m</em>'s type</strong></p>

  <p><strong>&#160;&#160;&#160;&#160; </strong><font face="Courier New"><span style="color: blue"><font color="#008080">Func</font></span>&lt;<font color="#008080">Func</font>&lt;T, Answer&gt;, Answer&gt;</font></p>

  <p><strong><em>k</em>'s type</strong></p>

  <p><strong>&#160;&#160;&#160;&#160; </strong><font face="Courier New"><span style="color: #2b91af">Func</span>&lt;T, <font color="#2b91af">Func</font>&lt;<font color="#008080">Func</font>&lt;U, Answer&gt;, Answer&gt;&gt;</font></p>
</blockquote>
<a href="https://11011.net/software/vspaste"></a>

<p>Applying <em>k</em> to a value of type <em>T</em> results in a value of type <em>K&lt;U,Answer&gt;</em>, but no value of type <em>T</em> is available.&#160; Build the return type directly by constructing a function, which takes a function from <em>U</em> to <em>Answer</em>.&#160; Call the parameter <em>c</em>.</p>

<blockquote>
  <pre class="code"><span style="color: blue">return </span>(<span style="color: #2b91af">Func</span>&lt;U,Answer&gt; c) =&gt; ...</pre>
</blockquote>
<a href="https://11011.net/software/vspaste"></a>

<p>The body must be type of <em>Answer </em>so that the return type of <em>Bind</em> is <em>K&lt;U,Answer&gt;</em>.&#160; Perhaps, <em>m</em> could be applied to a function from <em>T</em> to <em>Answer</em>.&#160; The result is a value of type <em>Answer</em>.</p>

<blockquote>
  <pre class="code"><span style="color: blue">return </span>(<span style="color: #2b91af">Func</span>&lt;U,Answer&gt; c) =&gt; m(...)</pre>
</blockquote>
<a href="https://11011.net/software/vspaste"></a>

<p>The expression inside the invocation of <em>m</em> must be of type <em>Func&lt;T,Answer&gt;</em>.&#160; Since there is nothing of that type, construct the function by creating a lambda with one parameter, <em>x</em>, of type <em>T.</em></p>

<blockquote>
  <pre class="code"><span style="color: blue">return </span>(<span style="color: #2b91af">Func</span>&lt;U,Answer&gt; c) =&gt; m((T x) =&gt; ...)</pre>
</blockquote>
<a href="https://11011.net/software/vspaste"></a>

<p>The body of this lambda must be of type <em>Answer</em>.&#160; Values of type <em>T, </em><em>Func&lt;U,Answer&gt;, </em>and <em>Func&lt;T,Func&lt;Func&lt;U,Answer&gt;, Answer&gt;&gt;</em> haven't been used yet.&#160; Apply <em>k</em> to <em>x</em>.</p>

<blockquote>
  <pre class="code"><span style="color: blue">return </span>(<span style="color: #2b91af">Func</span>&lt;U,Answer&gt; c) =&gt; m((T x) =&gt; k(x)...)</pre>
</blockquote>
<a href="https://11011.net/software/vspaste"></a>

<p>The result is a value of type <em>Func&lt;Func&lt;U,Answer&gt;,Answer&gt;</em>.&#160; Apply the result to <em>c</em>.</p>

<blockquote>
  <pre class="code"><span style="color: blue">return </span>(<span style="color: #2b91af">Func</span>&lt;U,Answer&gt; c) =&gt; m((T x) =&gt; k(x)(c));</pre>
</blockquote>
<a href="https://11011.net/software/vspaste"></a>

<p>The continuation monad turns the computation inside out.&#160; The comprehension syntax can be used to construct continuations.</p>

<p>Construct a computation, which invokes a continuation with the value seven.&#160; Pass this computation to another computation, which invokes a continuation with the value six.&#160;&#160; Pass this computation to another computation, which invokes a continuation with the result of adding the results of the first two continuations together.&#160; Finally, pass a continuation, which replaces &quot;1&quot;s with &quot;a&quot;s, to the result.</p>

<blockquote>
  <pre class="code"><span style="color: blue">var </span>r = <span style="color: blue">from </span>x <span style="color: blue">in </span>7.ToContinuation&lt;<span style="color: blue">int</span>,<span style="color: blue">string</span>&gt;()
        <span style="color: blue">from </span>y <span style="color: blue">in </span>6.ToContinuation&lt;<span style="color: blue">int</span>,<span style="color: blue">string</span>&gt;()
        <span style="color: blue">select </span>x + y;

<span style="color: #2b91af">Console</span>.WriteLine(r(z =&gt; z.ToString().Replace(<span style="color: #a31515">'1'</span>, <span style="color: #a31515">'a'</span>))); <font color="#008000">// displays a3</font></pre>
</blockquote>

<p>The continuation monad does the heavy-lifting of constructing the continuations.</p>

<p><strong>Monadic Magic</strong></p>

<p>Beautiful composition of amplified values requires monads.&#160; The <em>Identity</em>, <em>Maybe</em>, and <em>IEnumerable</em> monads demonstrate the power of monads as container types.&#160; The continuation monad, <em>K</em>, shows how monads can readily express complex computation.</p>

<p>Stay tuned for more with monads.&#160; Until then, see what monads can do for you.</p>]]></content:encoded>
    </item>
    <item>
      <title>Continuation-Passing Style</title>
      <link>https://docs.microsoft.com/archive/blogs/wesdyer/continuation-passing-style</link>
      <pubDate>Sat, 22 Dec 2007 01:51:58 GMT</pubDate>
      <dc:creator><![CDATA[wesdyer]]></dc:creator>
      <guid
        isPermaLink="false">https://blogs.msdn.microsoft.com/wesdyer/2007/12/22/continuation-passing-style/</guid>
      <description><![CDATA[There are some technical words that cause quite a stir even amongst geeks.&#160; When someone says...]]></description>
      <content:encoded><![CDATA[<p>There are some technical words that cause quite a stir even amongst geeks.&#160; When someone says the word <a href="https://en.wikipedia.org/wiki/Continuation">&quot;continuation&quot;</a>, people's eyes glaze over and they seek the first opportunity to change the subject.&#160; The stir is caused because most people don't understand what a continuation is or why someone would want to use one.&#160; This is unfortunate, because they really are rather more simple than they sound. </p>  <p><strong>Defining Continuations</strong></p>  <p>A continuation represents the remainder of a computation given a point in that computation.&#160; For example, suppose that two methods are defined: <em>M</em> and <em>Main</em>.&#160; The method <em>Main</em> invokes <em>M</em> and then writes &quot;Done&quot; to the console.&#160; The method <em>M</em> assigns <em>x </em>the value five, invokes <em>F</em>, increments <em>x</em>, and writes <em>x</em> to the console.</p>  <blockquote>   <pre class="code"><span style="color: blue">static void </span>M()
{
    <span style="color: blue">var </span>x = 5;
    F();  <span style="color: green">// &lt;----------- Point in the computation
    </span>++x;
    <span style="color: #2b91af">Console</span>.WriteLine(x);
}

<span style="color: blue">static void </span>Main()
{
    M();
    <span style="color: #2b91af">Console</span>.WriteLine(<span style="color: #a31515">&quot;Done&quot;</span>);
}</pre>
</blockquote>
<a href="https://11011.net/software/vspaste"></a><a href="https://11011.net/software/vspaste"></a>

<p>The continuation of the computation at the invocation of <em>F </em>is the remainder of the program execution beginning with incrementing <em>x</em> in the method <em>M</em>.&#160; In this case, the continuation includes incrementing <em>x</em>, writing <em>x</em>, returning to <em>Main</em>, and writing &quot;Done&quot; to the console.</p>

<p>Some languages give programmers explicit access to continuations.&#160; For example, Scheme has a function which calls a function passing a function representing the current continuation.&#160; The function is aptly named <a href="https://community.schemewiki.org/?call-with-current-continuation">call with current continuation</a> or <em>call/cc</em>.&#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.</p>

<blockquote>
  <pre class="code">T CallCC&lt;T&gt;(<span style="color: #2b91af">Func</span>&lt;<font color="#2b91af">Func</font>&lt;T,T&gt;, T&gt; f)</pre>
</blockquote>

<p>Continuations are the functional counterparts of GOTOs both in power and inscrutability.&#160; They can express arbitrary control flow like coroutines and exceptions while bewildering some of the brightest programmers.</p>

<p><strong>Returning Values with Continuations</strong></p>

<p>The simplest use of a continuation is to simulate returning out of a function.&#160; Suppose that .NET had the function <em>CallCC</em>.&#160; If <em>Main</em> calls a function <em>Foo</em> passing the value four and if <em>Foo</em> immediately invokes <em>CallCC</em> with a lambda that binds <em>Return</em> to the continuation at the point of the call to <em>CallCC, </em>then when <em>Return</em> is invoked inside of the lambda with the value four, computation will immediately jump out of the lambda to the point after <em>CallCC</em> but before the return with the value four on the stack.&#160; This happens regardless what of occurs after the invocation of <em>Return</em> inside the lambda.</p>

<blockquote>
  <pre class="code"><span style="color: blue">static int </span>Foo(<span style="color: blue">int </span>n)
{
    <span style="color: blue">return </span>CallCC&lt;<span style="color: blue">int</span>&gt;(Return =&gt;
        {
            Return(n);
            <span style="color: blue">return </span>n + 1;
        });
}

<span style="color: blue">static void </span>Main()
{
    Foo(4);
}</pre>
  <a href="https://11011.net/software/vspaste"></a></blockquote>

<p>The result of running the program is therefore four and not five.</p>

<p>All of this demonstrates that returning from a function is equivalent to invoking the continuation defined at the function's call-site.&#160; When a function &quot;returns&quot;, it implicitly invokes the continuation of its call-site.</p>

<p>When people explain continuations, they usually discuss stack frames and instruction pointers.&#160; It is easy to see why.&#160; The implicit invocation of the &quot;return&quot; continuation restores the stack frame at the call-site and sets the instruction pointer to the instruction immediately after the call-site.&#160; This is what invoking a continuation does: restore the appropriate stack frame and set the instruction pointer.</p>

<p><strong>Continuation-Passing Style</strong></p>

<p>It is still possible to use continuations if a language does not support a function like <em>call/cc</em>.&#160; A programmer can explicitly construct the continuation of a computation and pass it directly to a function.</p>

<p>To illustrate this transformation, suppose that a function, <em>Identity,</em> is defined that returns the value it is given. </p>

<blockquote>
  <pre class="code"><span style="color: blue">static </span>T Identity&lt;T&gt;(T value)
{
    <span style="color: blue">return </span>value;
}</pre>
</blockquote>

<p>The return statement in <em>Identity</em> implicitly invokes the continuation of the call-site causing computation to leave <em>Identity</em> and resume at the point immediately after the invocation of <em>Identity</em> at the call-site.&#160; If <em>Main</em> contains only a call to <em>WriteLine</em> passing the result of the call to <em>Identity,</em> then computation resumes with the call to <em>WriteLine</em>.</p>

<blockquote>
  <pre class="code"><span style="color: blue">static void </span>Main()
{
    <span style="color: #2b91af">Console</span>.WriteLine(Identity(<span style="color: #a31515">&quot;foo&quot;</span>));
}</pre>
</blockquote>
<a href="https://11011.net/software/vspaste"></a>

<p>However, instead of implicitly invoking <em>Identity's</em> continuation, the programmer can pass the continuation to <em>Identity </em>explicitly.&#160; An extra argument is added to <em>Identity</em> which is a void-returning delegate with one parameter that is the same type as the return type of the former <em>Identity</em> function.</p>

<blockquote>
  <pre class="code"><span style="color: blue">static void </span>Main()
{
    Identity(<span style="color: #a31515">&quot;foo&quot;</span>, s =&gt; <span style="color: #2b91af">Console</span>.WriteLine(s));
}

<span style="color: blue">static void </span>Identity&lt;T&gt;(T value, <span style="color: #2b91af">Action</span>&lt;T&gt; k)
{
    k(value);
}</pre>
</blockquote>
<a href="https://11011.net/software/vspaste"></a><a href="https://11011.net/software/vspaste"></a>

<p>At the call-site, the remainder of the computation has moved into the lambda passed to <em>Identity</em>.&#160; The continuation is explicitly passed.&#160; On the callee's side, the return statement is replaced by the invocation of the continuation parameter, <em>k</em>, with the return value.</p>

<p>This pattern is called <a href="https://en.wikipedia.org/wiki/Continuation-passing_style">continuation-passing style</a> or CPS.</p>

<p><strong>Converting to CPS</strong></p>

<p>Now that we know enough to be dangerous, let's see what we can do.&#160; Consider the typical <em>Max</em> function.</p>

<blockquote>
  <pre class="code"><span style="color: blue">static int </span>Max(<span style="color: blue">int </span>n, <span style="color: blue">int </span>m)
{
    <span style="color: blue">if </span>(n &gt; m)
        <span style="color: blue">return </span>n;
    <span style="color: blue">else
        return </span>m;
}</pre>
</blockquote>

<p>To convert this function to CPS, follow these steps:</p>

<blockquote>
  <p>1.&#160; Change the return type to void</p>

  <p>2.&#160; Add an extra argument of type <em>Action&lt;T&gt;</em> where <em>T</em> is the original return type</p>

  <p>3.&#160; Replace all return statements with invocations of the new continuation argument passing the expression used in the return statement</p>
</blockquote>

<p>Applying these steps to the integer version of <em>Max</em>, the function now returns void, takes an extra parameter, <em>k</em>, of type <em>Action&lt;int&gt;</em>, and invokes <em>k</em> everywhere a return statement appeared.</p>

<blockquote>
  <pre class="code"><span style="color: blue">static void </span>Max(<span style="color: blue">int </span>n, <span style="color: blue">int </span>m, <span style="color: #2b91af">Action</span>&lt;<span style="color: blue">int</span>&gt; k)
{
    <span style="color: blue">if </span>(n &gt; m)
        k(n);
    <span style="color: blue">else
        </span>k(m);
}</pre>
</blockquote>
<a href="https://11011.net/software/vspaste"></a>

<p>To convert the call-site to CPS:</p>

<blockquote>
  <p>1.&#160; Remove all of the remaining computation after the call-site</p>

  <p>2.&#160; Put the remaining computation in the body of the lambda corresponding to the continuation argument</p>
</blockquote>

<p>For example, suppose the user defined a method <em>Main</em> which invokes <em>WriteLine</em> with the result of applying <em>Max</em> to three and four.</p>

<blockquote>
  <p><font face="Courier New"><span style="color: blue"><font face="Verdana"></font>static void </span>Main()

      <br />{

      <br />&#160;&#160;&#160; <span style="color: #2b91af">Console</span>.WriteLine(Max(3, 4));

      <br />}</font></p>
</blockquote>

<p>The remaining computation after the invocation of <em>Max </em>is the call to <em>WriteLine</em>.&#160; Therefore, the call to <em>WriteLine </em>is moved into the lambda representing the continuation passed to <em>Max</em>.</p>

<blockquote>
  <p><font face="Courier New"><span style="color: blue">static void </span>Main()

      <br />{

      <br />&#160;&#160;&#160; Max(3, 4, x =&gt; <span style="color: #2b91af">Console</span>.WriteLine(x));

      <br />}</font></p>
</blockquote>
<a href="https://11011.net/software/vspaste"></a>

<p>The steps for converting the call-site skirted the issue of what to do with return statements in the continuation.&#160; For example, suppose there are three methods <em>Main</em>, <em>F</em>, and <em>G</em> where <em>Main </em>calls <em>F</em> and <em>F</em> calls <em>G.&#160; </em>To convert <em>F</em> and <em>G </em>to CPS, follow the same transformation steps as with <em>Max</em>.</p>

<blockquote>
  <pre class="code"><span style="color: blue">static void </span>Main()
{
    <span style="color: #2b91af">Console</span>.WriteLine(F(1) + 1);
}

<span style="color: blue">static int </span>F(<span style="color: blue">int </span>n)
{
    <span style="color: blue">return </span>G(n + 1) + 1;
}

<span style="color: blue">static int </span>G(<span style="color: blue">int </span>n)
{
    <span style="color: blue">return </span>n + 1;
}</pre>
</blockquote>
<a href="https://11011.net/software/vspaste"></a>

<p>However, what should the transformation do with the return statement in <em>F</em>?&#160; The continuation passed to <em>G</em> should definitely not attempt to return a result because the continuation is a void-returning delegate.</p>

<blockquote>
  <pre class="code"><span style="color: blue">static void </span>F(<span style="color: blue">int </span>n, <span style="color: #2b91af">Action</span>&lt;<span style="color: blue">int</span>&gt; k)
{
    G(n + 1, x =&gt; { <span style="color: blue">return </span>x + 1; });  <span style="color: green">// error, Action&lt;int&gt; cannot return a value
</span>}</pre>
  <a href="https://11011.net/software/vspaste"></a></blockquote>
<a href="https://11011.net/software/vspaste"></a>

<p>That wouldn't make any sense.&#160; Delegates with void return-types cannot return values.&#160; Furthermore, the code completely ignores <em>k</em>.</p>

<p>Instead, the return statement should be transformed into an invocation of <em>k</em>.</p>

<blockquote>
  <pre class="code"><span style="color: blue">static void </span>Main()
{
    F(1, x =&gt; <span style="color: #2b91af">Console</span>.WriteLine(x + 1));
}

<span style="color: blue">static void </span>F(<span style="color: blue">int </span>n, <span style="color: #2b91af">Action</span>&lt;<span style="color: blue">int</span>&gt; k)
{
    G(n + 1, x =&gt; k(x + 1));
}

<span style="color: blue">static void </span>G(<span style="color: blue">int </span>n, <span style="color: #2b91af">Action</span>&lt;<span style="color: blue">int</span>&gt; k)
{
    k(n + 1);
}</pre>
  <a href="https://11011.net/software/vspaste"></a></blockquote>
<a href="https://11011.net/software/vspaste"></a>

<p>This is how functions that use explicit continuations are composed together.</p>

<p>What about recursive functions like Factorial?</p>

<blockquote>
  <pre class="code"><span style="color: blue">static void </span>Main()
{
    <span style="color: #2b91af">Console</span>.WriteLine(Factorial(5));
}

<span style="color: blue">static int </span>Factorial(<span style="color: blue">int </span>n)
{
    <span style="color: blue">if </span>(n == 0)
        <span style="color: blue">return </span>1;
    <span style="color: blue">else
        return </span>n * Factorial(n - 1);
}</pre>
</blockquote>
<a href="https://11011.net/software/vspaste"></a>

<p>Recursive functions can be transformed just as easily following the same steps.</p>

<blockquote>
  <pre class="code"><span style="color: blue">static void </span>Main()
{
    Factorial(5, x =&gt; <span style="color: #2b91af">Console</span>.WriteLine(x));
}

<span style="color: blue">static void </span>Factorial(<span style="color: blue">int </span>n, <span style="color: #2b91af">Action</span>&lt;<span style="color: blue">int</span>&gt; k)
{
    <span style="color: blue">if </span>(n == 0)
        k(1);
    <span style="color: blue">else
        </span>Factorial(n - 1, x =&gt; k(n * x));
}</pre>
</blockquote>
<a href="https://11011.net/software/vspaste"></a>

<p>CPS turns a program inside-out.&#160; In the process, the programmer may feel that his brain has been turned inside-out as well.</p>

<p><strong>Why CPS?</strong></p>

<p>What exactly can a programmer do with CPS besides showoff at parties?</p>

<p>Compilers use a more thorough CPS transformation to produce an intermediate form amenable to many analyses.&#160; UI frameworks use CPS to keep the UI responsive while allowing nonlinear program interaction.&#160; Web servers use CPS to allow computation to flow asynchronously across pages.</p>

<p>Most programmers have used functions which take a callback.&#160; Often, the callback is the code that is invoked upon completion of the function.&#160; In these cases, the callback is an explicitly-passed continuation.</p>

<p><strong>Asynchronous Calls</strong></p>

<p>Hiding network latency requires asynchronous calls.&#160; In the first technology preview, Volta allows programmers to add asynchronous versions of methods on tier boundaries.</p>

<blockquote>
  <pre class="code">[<span style="color: #2b91af">RunAtOrigin</span>]
<span style="color: blue">static class </span><span style="color: #2b91af">C
</span>{
    <span style="color: blue">public static int </span>F(<span style="color: blue">string </span>s)
    {
        <span style="color: blue">return </span>s != <span style="color: blue">null </span>? s.Length : 0;
    }
}</pre>
</blockquote>

<p>To make a method asynchronous, define the CPS-equivalent method signature and annotate it with the <em>Async </em>attribute.&#160; Volta will generate the body and modify the call-sites accordingly.</p>

<blockquote>
  <pre class="code">[<span style="color: #2b91af">Async</span>]
<span style="color: blue">public static void </span>F(<span style="color: blue">string </span>s, <span style="color: #2b91af">Action</span>&lt;<span style="color: blue">int</span>&gt; k);</pre>
</blockquote>
<a href="https://11011.net/software/vspaste"></a>

<p>If the programmer invokes an asynchronous method <em>F, </em>then Volta will launch the invocation on another thread and invoke the continuation upon completion of the call to <em>F.</em></p>

<blockquote>
  <pre class="code"><span style="color: #2b91af">C</span>.F(<span style="color: #a31515">&quot;foo&quot;</span>, x =&gt; <span style="color: #2b91af">Console</span>.WriteLine(x));</pre>
</blockquote>
<a href="https://11011.net/software/vspaste"></a>

<p><strong>Wrapping it Up</strong></p>

<p>Continuations are powerful.&#160; CPS gives programmers a way to use continuations in their day-to-day work.&#160; Perhaps, someday soon we'll discuss how to make CPS more palatable, but we will need to discuss the &quot;M&quot; word first.</p>]]></content:encoded>
    </item>
    <item>
      <title>Musings on Software Testing</title>
      <link>https://docs.microsoft.com/archive/blogs/wesdyer/musings-on-software-testing</link>
      <pubDate>Fri, 07 Dec 2007 14:42:24 GMT</pubDate>
      <dc:creator><![CDATA[wesdyer]]></dc:creator>
      <guid
        isPermaLink="false">https://blogs.msdn.microsoft.com/wesdyer/2007/12/07/musings-on-software-testing/</guid>
      <description><![CDATA[It was spring 2003, I had just finished a weekend camping in the southern Arizona desert.&#160; I...]]></description>
      <content:encoded><![CDATA[<p>It was spring 2003, I had just finished a weekend camping in the southern Arizona desert.&#160; I was dusty and physically exhausted from hours of playing paintball.&#160; For those who have never been in those parts, imagine long straight roads with dry sage brush, painful cactus, and jagged mountains.&#160; I needed a book to pass the time during the drive.&#160; Fortunately, I had brought along <a href="https://www.amazon.com/Extreme-Programming-Explained-Embrace-Change/dp/0321278658/ref=pd_bbs_sr_1/104-8800337-6061564?ie=UTF8&amp;s=books&amp;qid=1191966305&amp;sr=8-1">&quot;Extreme Programming Explained&quot;</a> by <a href="https://en.wikipedia.org/wiki/Kent_Beck">Kent Beck</a>.&#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.&#160; Over the next few months, I became acquainted with <a href="https://www.amazon.com/Test-Driven-Development-Addison-Wesley-Signature/dp/0321146530/ref=pd_bxgy_b_img_b/104-8800337-6061564">test-driven development</a>, <a href="https://www.amazon.com/Design-Patterns-Object-Oriented-Addison-Wesley-Professional/dp/0201633612/ref=pd_sim_b_shvl_img_1/104-8800337-6061564">design patterns</a>, <a href="https://www.amazon.com/Refactoring-Improving-Design-Existing-Code/dp/0201485672/ref=pd_bxgy_b_img_b/104-8800337-6061564">refactoring</a> and many of the other topics typically associated with <a href="https://en.wikipedia.org/wiki/Agile_programming">agile programming</a>. </p>  <p><strong>Test Driven Development</strong> </p>  <p>In the spring, I had a course that ended up just teaching agile programming concepts.&#160; One of the things that the professor emphasized was following the test-driven development (TDD) process to the letter. </p>  <p><a href="https://msdnshared.blob.core.windows.net/media/TNBlogsFS/BlogFileStorage/blogs_msdn/wesdyer/WindowsLiveWriter/EscapingtheFixedPointofDevelopment_D551/image_6.png" original-url="https://blogs.msdn.com/blogfiles/wesdyer/WindowsLiveWriter/EscapingtheFixedPointofDevelopment_D551/image_6.png"><img style="border-top-width: 0px; border-left-width: 0px; border-bottom-width: 0px; border-right-width: 0px" height="335" alt="image" src="https://msdnshared.blob.core.windows.net/media/TNBlogsFS/BlogFileStorage/blogs_msdn/wesdyer/WindowsLiveWriter/EscapingtheFixedPointofDevelopment_D551/image_thumb_2.png" original-url="https://blogs.msdn.com/blogfiles/wesdyer/WindowsLiveWriter/EscapingtheFixedPointofDevelopment_D551/image_thumb_2.png" width="518" border="0" /></a> </p> <a href="https://en.wikipedia.org/wiki/Test-driven_development">The TDD Process:</a>   <blockquote>   <p>1.&#160; Add a test </p>    <p>2.&#160; Run all tests and see the new one fail </p>    <p>3.&#160; Write some code </p>    <p>4.&#160; Run the automated tests and see them succeed&#160; </p>    <p>5.&#160; <a href="https://en.wikipedia.org/wiki/Refactor">Refactor</a> code </p>    <p><em>Repeat</em></p> </blockquote>  <p>When I say refactor, I mean it in the strictest sense.&#160; I mean changing how a program is arranged internally without changing the semantics of the program at all.&#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.</p>  <p>During step three a programmer should remember, &quot;It is important that the code written is <i>only</i> designed to pass the test; no further (and therefore untested) functionality should be predicted and 'allowed for' at any stage&quot;.</p>  <p><strong>Machine Learning</strong> </p>  <p> I fully bought into this rigorous approach to TDD until one summer day when I was reading through <a href="https://www.cs.cmu.edu/~tom/">Tom Mitchell</a>'s marvelous book <a href="https://www.amazon.com/Machine-Learning-Tom-M-Mitchell/dp/0070428077/ref=sr_1_2/104-8800337-6061564?ie=UTF8&amp;s=books&amp;qid=1191967459&amp;sr=1-2">&quot;Machine Learning&quot;</a>.&#160; The book begins by defining <a href="https://en.wikipedia.org/wiki/Machine_learning">machine learning</a>: </p>  <blockquote>   <p>A computer program is said to <strong>learn</strong> from experience <em>E</em> with respect to some class of tasks <em>T</em> and performance measure <em>P</em>, if its performance at tasks in <em>T</em>, as measured by <em>P</em>, improves with experience <em>E.</em></p> </blockquote>  <p>Intuitively, the learning process is trying to learn some unknown concept.&#160; The learner has access to its past experiences (the training data) and uses them to generate a hypothesis of the unknown concept.&#160; This hypothesis is then evaluated and the new experiences are added to the training data.&#160; The learning process then repeats itself as the learner forms a better approximation of the underlying concept.&#160; </p>  <p>TDD is a learning process.&#160; Where the training experience <em>E</em> is the automated tests, the task <em>T </em>is improving the quality of the program, and the performance measure <em>P</em> is the percentage of tests passed.&#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.&#160; Note that unless the tests exhaustively specify the desired behavior of a program, then the tests <em>are not</em> the target concept that needs to be learned but rather a few data points where the target concept is manifest.&#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. </p>  <p><a href="https://msdnshared.blob.core.windows.net/media/TNBlogsFS/BlogFileStorage/blogs_msdn/wesdyer/WindowsLiveWriter/EscapingtheFixedPointofDevelopment_D551/j0385807_2.jpg" original-url="https://blogs.msdn.com/blogfiles/wesdyer/WindowsLiveWriter/EscapingtheFixedPointofDevelopment_D551/j0385807_2.jpg"><img style="border-top-width: 0px; border-left-width: 0px; border-bottom-width: 0px; border-right-width: 0px" height="288" alt="j0385807" src="https://msdnshared.blob.core.windows.net/media/TNBlogsFS/BlogFileStorage/blogs_msdn/wesdyer/WindowsLiveWriter/EscapingtheFixedPointofDevelopment_D551/j0385807_thumb.jpg" original-url="https://blogs.msdn.com/blogfiles/wesdyer/WindowsLiveWriter/EscapingtheFixedPointofDevelopment_D551/j0385807_thumb.jpg" width="404" border="0" /></a> </p>  <p><strong>Bias and Learning</strong> </p>  <p>A learner is characterized by its hypothesis space and <a href="https://jmvidal.cse.sc.edu/talks/conceptlearning/learningassearch.xml?style=White">how it searches through that space</a>.&#160; Notice that since each learner has a hypothesis space, a given concept may have not be in that space.&#160; One solution to this problem is to make a learner's hypothesis space <a href="https://jmvidal.cse.sc.edu/talks/conceptlearning/unbiasedlearner.xml?style=White">include all hypotheses</a>, but this leads to a <a href="https://jmvidal.cse.sc.edu/talks/conceptlearning/futilityofnobias.xml?style=White">fundamental problem</a>: &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.&quot;&#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. </p>  <p>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.&#160; If I am told that giraffes, lions, mice, bats, and whales are mammals but snakes, butterflies, frogs, lobsters, and&#160; penguins are not, then I only have the ability to answer questions regarding those animals for which I already know the answer.&#160; I could have done much better by trying to guess at what makes an animal a mammal even if I got it wrong! </p>  <p>Returning to TDD, note that at no time is a programmer supposed to write code that generalizes to the target concept.&#160; The programmer should only write either the minimal code to make a test pass or refactor the code and not change the semantics.&#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.&#160; A critic might respond that more test cases are needed.&#160; In some cases where the input space is finite and small, this might well help, but in general this is impractical. </p>  <p><strong>Sufficiently Large Projects</strong> </p>  <p>A similar situation arises in projects that are sufficiently large.&#160; These projects are characterized by the fact that they cannot be held inside any one person's head.&#160; This means that when someone is making a change, they cannot know all of the consequences of their change.&#160; Often in projects of this size, when people ask if a particular change is good, the response is, &quot;It passed the tests.&quot;&#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.&#160; Most likely, the target concept is not normally fully determined by the tests. </p>  <p>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.&#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.</p>  <p>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.</p>  <p><strong>Testing an Infinite Space</strong> </p>  <p>I had a development lead who liked to say that testing is just sampling.&#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.&#160; Think of a program as a state machine encoded in your <a href="https://en.wikipedia.org/wiki/Process_calculus">favorite process calculus</a>.&#160; A test then verifies that a particular path of edges corresponding to the transitions based on the input ends in a particular state.&#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. </p>  <p>Testing creates tests by drawing input sequences out of the input sequence space.&#160; It is easy to imagine that tests could be generated randomly by selecting random input sequences.&#160; Random selection has several advantages.&#160; First, it enables statistical measures of quality.&#160; For example, if we sample uniformly then the pass/fail rate should be representative of the whole given a large enough sample.&#160; We could also keep generating more and more tests to improve our confidence that the program is indeed correct.&#160; Second, random tests have the added benefit of not allowing the programmers to just &quot;pass the tests&quot; since the programmers cannot anticipate what tests will be run.&#160; This forces the programmers to generate a hypothesis that more closely matches the target concept instead of the training data. </p>  <p>There are however some disadvantages.&#160; The first apparent problem is repeatability of the tests.&#160; This can be remedied by storing the seed that generates a set of tests.&#160; A second more serious problem is that a uniform random sample doesn't necessarily deliver the best results. </p>  <p><strong>On Bugs</strong> </p>  <p>Not all bugs are created equal.&#160; Practices such as testing the boundary conditions and integration testing are based on that fact.&#160; Various testing practices explore parts of the input space that are richer in bugs or are more likely to contain serious bugs. </p>  <p><a href="https://msdnshared.blob.core.windows.net/media/TNBlogsFS/BlogFileStorage/blogs_msdn/wesdyer/WindowsLiveWriter/EscapingtheFixedPointofDevelopment_D551/image_8.png" original-url="https://blogs.msdn.com/blogfiles/wesdyer/WindowsLiveWriter/EscapingtheFixedPointofDevelopment_D551/image_8.png"><img style="border-top-width: 0px; border-left-width: 0px; border-bottom-width: 0px; border-right-width: 0px" height="168" alt="image" src="https://msdnshared.blob.core.windows.net/media/TNBlogsFS/BlogFileStorage/blogs_msdn/wesdyer/WindowsLiveWriter/EscapingtheFixedPointofDevelopment_D551/image_thumb_3.png" original-url="https://blogs.msdn.com/blogfiles/wesdyer/WindowsLiveWriter/EscapingtheFixedPointofDevelopment_D551/image_thumb_3.png" width="628" border="0" /></a></p>  <p>The cost of a bug can be quantified as the total monetary loss due to the presence of that bug in the software.&#160; This includes all sorts of things like lost sales through negative customer perception, cost of software patches, legal action, etc.&#160; While this is an accurate measure of cost, it is not very practical because it is very hard to estimate.</p>  <p>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.&#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. </p>  <p><strong>Back to Training</strong></p>  <p>The testing ideal is to minimize the total cost of bugs.&#160; There are many good methods for writing test cases.&#160; In addition to these, we could also select input sequences based upon the probability that a user would select such an input sequence.</p>  <p>Imagine if it were possible to collect all of the input sequences that would ever be given to a program including duplicates.&#160; Then our problem would be reduced to uniformly selecting input sequences out of this collection.&#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.</p>  <p><strong>Markov Chains</strong></p>  <p>One way that this could be done is by returning to the formulation of a computer program as a state machine.&#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.&#160; This can be formulated as a <a href="https://en.wikipedia.org/wiki/Markov_chain">Markov chain</a>.</p>  <p>Consider generating random test cases for a parser.&#160; A straightforward approach is to randomly derive a <a href="https://en.wikipedia.org/wiki/String_%28computer_science%29">string</a> in the <a href="https://en.wikipedia.org/wiki/Formal_language">language</a> from the root <a href="https://en.wikipedia.org/wiki/Nonterminal_symbol">non-terminal</a>; however, it will quickly become apparent that the least used parts of your language are getting undue attention.&#160; Some more sophisticated tools allow productions in the <a href="https://en.wikipedia.org/wiki/Formal_grammar">grammar</a> to be attributed with weights.&#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 <a href="https://en.wikipedia.org/wiki/Production_%28computer_science%29">production</a> for a non-terminal will be used is also based on the history of previously expanded productions.</p>  <p>A better approach is to learn weights for the Markov chain corresponding to the <a href="https://en.wikipedia.org/wiki/Pushdown_automata">pushdown automata</a>.&#160; Since a parser for an arbitrary <a href="https://en.wikipedia.org/wiki/Context-free_grammar">context-free grammar</a> 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.&#160; The instrumented automaton can then be fed a large number of user-written programs.&#160; Finally, a generator can be created that uses the data to generate programs that syntactically look like user-written programs.</p>  <p>Another approach might be to instrument branches and event sequences in a program and then train against user input.&#160; The learner could then build a Markov chain that can be used to generate input sequences roughly like user input.</p>  <p><strong>Conclusion</strong></p>  <p>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. </p>]]></content:encoded>
    </item>
    <item>
      <title>Volta and You</title>
      <link>https://docs.microsoft.com/archive/blogs/wesdyer/volta-and-you</link>
      <pubDate>Thu, 06 Dec 2007 12:37:27 GMT</pubDate>
      <dc:creator><![CDATA[wesdyer]]></dc:creator>
      <guid
        isPermaLink="false">https://blogs.msdn.microsoft.com/wesdyer/2007/12/06/volta-and-you/</guid>
      <description><![CDATA[Yesterday, Volta was made publicly available for the first time.&#160; It is an experimental project...]]></description>
      <content:encoded><![CDATA[<p>Yesterday, Volta was made publicly available for the first time.&#160; It is an <em>experimental</em> project in the early stages of development.&#160; The team decided to release an early technology preview so that developers everywhere can help guide the project through experience and feedback.&#160; We want your feedback.</p>  <p>The first release provides the basic feature set that will be improved upon with time.&#160; It has some obvious shortcomings that we are aware of and are actively addressing.&#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.</p>  <p>Perhaps you disagree.&#160; Maybe the most important feature to you is the completeness of a final product.&#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.</p>  <p>At some point, Volta may become, feed into, or inform a product, but that is a little way off yet.&#160; So let's enjoy the unique opportunity of working together to make something great.</p>  <p>In the coming months, I will alternate between three types of posts:</p>  <blockquote>   <p>1.&#160; Volta focused posts: explaining the motivation, features, and technical details</p>    <p>2.&#160; C#: this includes both 3.0 and eventually 4.0 features</p>    <p>3.&#160; Random thoughts: like it says; two that will be discussed soon are programmer tests and continuations</p> </blockquote>  <p>I hope you enjoy the posts and I look forward to engaging with you in discussion.</p>]]></content:encoded>
    </item>
    <item>
      <title>Volta: Redefining Web Development</title>
      <link>https://docs.microsoft.com/archive/blogs/wesdyer/volta-redefining-web-development</link>
      <pubDate>Wed, 05 Dec 2007 14:14:36 GMT</pubDate>
      <dc:creator><![CDATA[wesdyer]]></dc:creator>
      <guid
        isPermaLink="false">https://blogs.msdn.microsoft.com/wesdyer/2007/12/05/volta-redefining-web-development/</guid>
      <description><![CDATA[Anyone who writes web applications knows that web development is not easy.&#160; Developers wrangle...]]></description>
      <content:encoded><![CDATA[<p>Anyone who writes web applications knows that web development is not easy.&#160; Developers wrangle with a soup of technologies distributed across multiple tiers.&#160; We live in a world where programmers accept the fact that they need to know <a href="https://en.wikipedia.org/wiki/Web_development">four or five different languages, tools, and environments</a> just to get a site up and running.&#160; In ancient times, the Egyptians built marvelous structures despite <a href="https://books.google.com/books?id=MXaR-s9N4uEC&amp;pg=PA136&amp;lpg=PA136&amp;dq=copper+chisels&amp;source=web&amp;ots=nanvWmY6qx&amp;sig=LA6IC5LOR6pMssDO6OH3m_MzGc0#PPP1,M1">the primitive tools</a> that <a href="https://books.google.com/books?id=-sFpPTDMyrMC&amp;pg=PA211&amp;lpg=PA211&amp;dq=copper+chisels&amp;source=web&amp;ots=P5yoKMAI01&amp;sig=xAtHpZye37I-OerXxStPD3PZbvI">the workmen used</a>.&#160; Building a pyramid took most of the national resources of wealth and labor.&#160; Today, we build structures which are vastly more complicated and yet require only a tiny fraction of the resources.&#160; The difference is in the tools and the infrastructure.</p>  <p>In a similar way, Volta significantly improves web development.&#160; Programmers write web applications using familiar .NET languages, libraries, and tools.&#160; Volta splits the application into multiple parts potentially running on different tiers, say, client and server.&#160; Client code needs only a minimal, JavaScript-enabled browser, though Volta will take advantage of additional runtimes that may be present.</p>  <p>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.&#160; The developer enjoys all of the benefits of .NET: a great debugger, test tools, profiling, intellisense, refactorings, etc.</p>  <p>Just how simple is Volta?&#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.</p>  <p><a href="https://msdnshared.blob.core.windows.net/media/TNBlogsFS/BlogFileStorage/blogs_msdn/wesdyer/WindowsLiveWriter/VoltaRedefiningWebDevelopment_D283/image_4.png" original-url="https://blogs.msdn.com/blogfiles/wesdyer/WindowsLiveWriter/VoltaRedefiningWebDevelopment_D283/image_4.png"><img style="border-top-width: 0px; border-left-width: 0px; border-bottom-width: 0px; border-right-width: 0px" height="297" alt="image" src="https://msdnshared.blob.core.windows.net/media/TNBlogsFS/BlogFileStorage/blogs_msdn/wesdyer/WindowsLiveWriter/VoltaRedefiningWebDevelopment_D283/image_thumb_1.png" original-url="https://blogs.msdn.com/blogfiles/wesdyer/WindowsLiveWriter/VoltaRedefiningWebDevelopment_D283/image_thumb_1.png" width="470" border="0" /></a> </p>  <p>Now, let's write the code for the web page.&#160; We need a <em>Div</em> for the output and an <em>Input </em>for the interaction.&#160; Of course, we could have constructed the page elements with HTML/CSS instead.</p>  <pre class="code"><span style="color: blue">using </span>System;
<span style="color: blue">using </span>Microsoft.LiveLabs.Volta.Html;
<span style="color: blue">using </span>Microsoft.LiveLabs.Volta.Xml;

<span style="color: blue">namespace </span>HelloWorld
{
    <span style="color: blue">public partial class </span><span style="color: #2b91af">VoltaPage1 </span>: <span style="color: #2b91af">Page
    </span>{
        <span style="color: blue">public </span>VoltaPage1()
        {
            <span style="color: blue">var </span>output = <span style="color: blue">new </span><span style="color: #2b91af">Div</span>();

            <span style="color: blue">var </span>b = <span style="color: blue">new </span><span style="color: #2b91af">Input</span>();
            b.Type = <span style="color: #a31515">&quot;button&quot;</span>;
            b.Value = <span style="color: #a31515">&quot;Get Message&quot;</span>;
            b.Click += () =&gt; output.InnerHtml = <span style="color: #2b91af">C</span>.GetMessage();

            Document.Body.AppendChild(output);
            Document.Body.AppendChild(b);
        }
    }

    <span style="color: blue">class </span><span style="color: #2b91af">C
    </span>{
        <span style="color: blue">public static string </span>GetMessage()
        {
            <span style="color: blue">return </span><span style="color: #a31515">&quot;Hello, World&quot;</span>;
        }
    }
}</pre>
<a href="https://11011.net/software/vspaste"></a>

<p>But we want to produce the message on the server.&#160; Time to refactor.</p>

<p>&#160;<a href="https://msdnshared.blob.core.windows.net/media/TNBlogsFS/BlogFileStorage/blogs_msdn/wesdyer/WindowsLiveWriter/VoltaRedefiningWebDevelopment_D283/image8.png" original-url="https://blogs.msdn.com/blogfiles/wesdyer/WindowsLiveWriter/VoltaRedefiningWebDevelopment_D283/image8.png"><img style="border-top-width: 0px; border-left-width: 0px; border-bottom-width: 0px; border-right-width: 0px" height="355" alt="image" src="https://msdnshared.blob.core.windows.net/media/TNBlogsFS/BlogFileStorage/blogs_msdn/wesdyer/WindowsLiveWriter/VoltaRedefiningWebDevelopment_D283/image8_thumb.png" original-url="https://blogs.msdn.com/blogfiles/wesdyer/WindowsLiveWriter/VoltaRedefiningWebDevelopment_D283/image8_thumb.png" width="484" border="0" /></a></p>

<p>Browser clients call the server, the &quot;Origin&quot;, because this ensures the message will come from the same server that supplied the HTML.</p>

<pre class="code">[<span style="color: #2b91af">RunAtOrigin</span>]
<span style="color: blue">class </span><span style="color: #2b91af">C
</span>{
    <span style="color: blue">public static string </span>GetMessage()
    {
        <span style="color: blue">return </span><span style="color: #a31515">&quot;Hello, World&quot;</span>;
    }
} </pre>

<p>That is it.&#160; Try it out.</p>

<p><a href="https://msdnshared.blob.core.windows.net/media/TNBlogsFS/BlogFileStorage/blogs_msdn/wesdyer/WindowsLiveWriter/VoltaRedefiningWebDevelopment_D283/image12.png" original-url="https://blogs.msdn.com/blogfiles/wesdyer/WindowsLiveWriter/VoltaRedefiningWebDevelopment_D283/image12.png"><img style="border-top-width: 0px; border-left-width: 0px; border-bottom-width: 0px; border-right-width: 0px" height="252" alt="image" src="https://msdnshared.blob.core.windows.net/media/TNBlogsFS/BlogFileStorage/blogs_msdn/wesdyer/WindowsLiveWriter/VoltaRedefiningWebDevelopment_D283/image12_thumb.png" original-url="https://blogs.msdn.com/blogfiles/wesdyer/WindowsLiveWriter/VoltaRedefiningWebDevelopment_D283/image12_thumb.png" width="513" border="0" /></a> </p>

<p>Now, click &quot;Get Message&quot;.</p>

<p><a href="https://msdnshared.blob.core.windows.net/media/TNBlogsFS/BlogFileStorage/blogs_msdn/wesdyer/WindowsLiveWriter/VoltaRedefiningWebDevelopment_D283/image16.png" original-url="https://blogs.msdn.com/blogfiles/wesdyer/WindowsLiveWriter/VoltaRedefiningWebDevelopment_D283/image16.png"><img style="border-top-width: 0px; border-left-width: 0px; border-bottom-width: 0px; border-right-width: 0px" height="249" alt="image" src="https://msdnshared.blob.core.windows.net/media/TNBlogsFS/BlogFileStorage/blogs_msdn/wesdyer/WindowsLiveWriter/VoltaRedefiningWebDevelopment_D283/image16_thumb.png" original-url="https://blogs.msdn.com/blogfiles/wesdyer/WindowsLiveWriter/VoltaRedefiningWebDevelopment_D283/image16_thumb.png" width="506" border="0" /></a> </p>

<p>Great.&#160; But is it cross-browser compatible?</p>

<p><a href="https://msdnshared.blob.core.windows.net/media/TNBlogsFS/BlogFileStorage/blogs_msdn/wesdyer/WindowsLiveWriter/VoltaRedefiningWebDevelopment_D283/image20.png" original-url="https://blogs.msdn.com/blogfiles/wesdyer/WindowsLiveWriter/VoltaRedefiningWebDevelopment_D283/image20.png"><img style="border-top-width: 0px; border-left-width: 0px; border-bottom-width: 0px; border-right-width: 0px" height="225" alt="image" src="https://msdnshared.blob.core.windows.net/media/TNBlogsFS/BlogFileStorage/blogs_msdn/wesdyer/WindowsLiveWriter/VoltaRedefiningWebDevelopment_D283/image20_thumb.png" original-url="https://blogs.msdn.com/blogfiles/wesdyer/WindowsLiveWriter/VoltaRedefiningWebDevelopment_D283/image20_thumb.png" width="499" border="0" /></a></p>

<p>Yes.&#160; And you can debug it. </p>

<p>&#160;<a href="https://msdnshared.blob.core.windows.net/media/TNBlogsFS/BlogFileStorage/blogs_msdn/wesdyer/WindowsLiveWriter/VoltaRedefiningWebDevelopment_D283/image30.png" original-url="https://blogs.msdn.com/blogfiles/wesdyer/WindowsLiveWriter/VoltaRedefiningWebDevelopment_D283/image30.png"><img style="border-top-width: 0px; border-left-width: 0px; border-bottom-width: 0px; border-right-width: 0px" height="759" alt="image" src="https://msdnshared.blob.core.windows.net/media/TNBlogsFS/BlogFileStorage/blogs_msdn/wesdyer/WindowsLiveWriter/VoltaRedefiningWebDevelopment_D283/image30_thumb.png" original-url="https://blogs.msdn.com/blogfiles/wesdyer/WindowsLiveWriter/VoltaRedefiningWebDevelopment_D283/image30_thumb.png" width="899" border="0" /></a> </p>

<p>You can even debug across tiers.</p>

<p><a href="https://msdnshared.blob.core.windows.net/media/TNBlogsFS/BlogFileStorage/blogs_msdn/wesdyer/WindowsLiveWriter/VoltaRedefiningWebDevelopment_D283/image35.png" original-url="https://blogs.msdn.com/blogfiles/wesdyer/WindowsLiveWriter/VoltaRedefiningWebDevelopment_D283/image35.png"><img style="border-top-width: 0px; border-left-width: 0px; border-bottom-width: 0px; border-right-width: 0px" height="761" alt="image" src="https://msdnshared.blob.core.windows.net/media/TNBlogsFS/BlogFileStorage/blogs_msdn/wesdyer/WindowsLiveWriter/VoltaRedefiningWebDevelopment_D283/image35_thumb.png" original-url="https://blogs.msdn.com/blogfiles/wesdyer/WindowsLiveWriter/VoltaRedefiningWebDevelopment_D283/image35_thumb.png" width="900" border="0" /></a>&#160;</p>

<p>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.</p>

<p>Still skeptical?&#160; Try it out for yourself.</p>

<p><a href="https://labs.live.com/volta">https://labs.live.com/volta</a></p>

<p><a href="https://msdnshared.blob.core.windows.net/media/TNBlogsFS/BlogFileStorage/blogs_msdn/wesdyer/WindowsLiveWriter/VoltaRedefiningWebDevelopment_D283/image_2.png" original-url="https://blogs.msdn.com/blogfiles/wesdyer/WindowsLiveWriter/VoltaRedefiningWebDevelopment_D283/image_2.png"><img style="border-top-width: 0px; border-left-width: 0px; border-bottom-width: 0px; border-right-width: 0px" height="168" alt="image" src="https://msdnshared.blob.core.windows.net/media/TNBlogsFS/BlogFileStorage/blogs_msdn/wesdyer/WindowsLiveWriter/VoltaRedefiningWebDevelopment_D283/image_thumb.png" original-url="https://blogs.msdn.com/blogfiles/wesdyer/WindowsLiveWriter/VoltaRedefiningWebDevelopment_D283/image_thumb.png" width="354" border="0" /></a></p>]]></content:encoded>
    </item>
    <item>
      <title>More on Partial Methods</title>
      <link>https://docs.microsoft.com/archive/blogs/wesdyer/more-on-partial-methods</link>
      <pubDate>Thu, 31 May 2007 01:34:45 GMT</pubDate>
      <dc:creator><![CDATA[wesdyer]]></dc:creator>
      <guid
        isPermaLink="false">https://blogs.msdn.microsoft.com/wesdyer/2007/05/31/more-on-partial-methods/</guid>
      <description><![CDATA[Thank you everyone for the feedback.&nbsp; If you have any more to say then please do express your...]]></description>
      <content:encoded><![CDATA[<p>Thank you everyone for the feedback.&nbsp; If you have any more to say then please do express your opinion (and yes it is valued ;).&nbsp; I think there has been a bit of misunderstanding about what partial methods really are.&nbsp; So let's set the matter straight.&nbsp; Here is the current spec (quoting from here on out):</p> <p>Partial methods are a new feature complementing partial classes with the option of declaring “hook” – or compile time events – in the code.  <p>Here is an example  <blockquote> <p><font face="Courier New">partial class Customer</font>  <p><font face="Courier New">{</font>  <p><font face="Courier New">&nbsp; public string Name {</font>  <p><font face="Courier New">&nbsp; &nbsp; get { … }</font>  <p><font face="Courier New">&nbsp;&nbsp;&nbsp; set {</font>  <p><font face="Courier New">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; OnNameChanging(value);</font>  <p><font face="Courier New">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; _name = value;</font>  <p><font face="Courier New">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; OnNameChanged();</font>  <p><font face="Courier New">&nbsp;&nbsp;&nbsp; }</font>  <p><font face="Courier New">&nbsp; }</font>  <p><font face="Courier New">&nbsp; partial void OnNameChanging(string value);</font>  <p><font face="Courier New">&nbsp; partial void onNameChanged();</font>  <p><font face="Courier New">}</font></p></blockquote> <p>Partial methods are only allowed in partial types; either classes or structs. There are no other kinds of partial members.  <p>There are two parts of a partial method; the <i>defining</i> and the <i>implementing</i> 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.  <p>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.  <p>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.  <p>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.  <p>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.  <p>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.  <p>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.  <p>Because partial methods are always private, they cannot implement interface methods, neither implicitly or explicitly.  <p>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.  <p>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.  <p><a></a> <p>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.  <p>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.</p>]]></content:encoded>
    </item>
    <item>
      <title>In Case You Haven't Heard</title>
      <link>https://docs.microsoft.com/archive/blogs/wesdyer/in-case-you-havent-heard</link>
      <pubDate>Wed, 23 May 2007 14:19:06 GMT</pubDate>
      <dc:creator><![CDATA[wesdyer]]></dc:creator>
      <guid
        isPermaLink="false">https://blogs.msdn.microsoft.com/wesdyer/2007/05/23/in-case-you-havent-heard/</guid>
      <description><![CDATA[It has been a while since I have posted.&nbsp;&nbsp;We have been&nbsp;working hard to get Orcas beta...]]></description>
      <content:encoded><![CDATA[<p>It has been a while since I have posted.&nbsp;&nbsp;We have been&nbsp;working hard to get Orcas beta 1 and beta 2 done.&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.</p> <p>Now that beta 1 is out there, what do you all think of it?&nbsp; Beta 1 has <em>most</em> of the features that we intend to put into Orcas but not all of them.&nbsp; Some notable differences you will see in later releases are improved performance, error messages, error recovery, stability, and a few refinements.&nbsp; Basically the kind of polish that people expect as a product nears completion.</p> <p><strong>Partial Methods</strong></p> <p>One feature that you may have not heard of yet is a feature called partial methods.&nbsp; This is some of the work that I did in the last coding milestone a few months back.&nbsp; Partial methods are methods that enable lightweight event handling.&nbsp; Here is an example declaration:</p> <blockquote> <p><font face="Courier New"></font> <p><font face="Courier New">partial class C<br>{<br>&nbsp; static partial void M(int i);<br>}</font></p></blockquote> <p>There are a few notable things here:</p> <blockquote> <p>1.&nbsp; Partial methods must be declared within partial classes</p> <p>2.&nbsp; Partial methods are indicated by the partial modifier</p> <p>3.&nbsp; Partial methods do not always have a body (well look at this more below)</p> <p>4.&nbsp; Partial methods must return void</p> <p>5.&nbsp; Partial methods <em>can</em> be static</p> <p>6.&nbsp; Partial methods can have arguments (including this, ref, and params modifiers)</p> <p><strong>7.&nbsp; Partial methods <em>must</em> be private</strong></p></blockquote> <p>Now suppose that I make a call to C.M.</p> <blockquote> <p><font face="Courier New">partial class C<br>{</font>  <p><font face="Courier New">&nbsp; static void Main()<br>&nbsp; {<br>&nbsp;&nbsp;&nbsp; C.M(Calculation());<br>&nbsp; }<br>}</font></p></blockquote> <p>Since M has no body, all calls to C.M are removed at compile time <em>as well as the evaluation of the arguments</em>.&nbsp; So the above program is equivalent to:</p> <blockquote> <p><font face="Courier New">partial class C<br>{</font>  <p><font face="Courier New">&nbsp; static void Main()<br>&nbsp; {<br>&nbsp; }<br>}</font></p></blockquote> <p>In this sense, partial methods are the distant cousins of conditional methods which also sometimes remove the call and the evaluation of the arguments.&nbsp; But partial methods go even further.&nbsp; When a partial method has no body then the partial method is not even emitted to metadata.</p> <p>So far this might seem a little confusing.&nbsp; C# now allows users to declare methods for which the calls, the evaluation of the arguments, and the method itself are not emitted.&nbsp; Fortunately, the story doesn't end there.&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.</p> <blockquote> <p><font face="Courier New">partial class C<br>{<br>&nbsp; static partial void M(int i); // defining declaration<br>&nbsp; static partial void M(int i)&nbsp; // implementing declaration<br>&nbsp; {<br>&nbsp; }<br>}</font></p></blockquote> <p>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.&nbsp; These definitions don't have to be in the same partial class declaration.&nbsp; There may only be one defining declaration and if a defining declaration exists then there may be an implementing declaration.</p> <p><strong>Why Partial Methods?</strong></p> <p>So how are these partial methods used?&nbsp; The common scenario is to use them to do lightweight event handling.&nbsp; For example a tool that generates code may wish to have hooks for users to customize what code is run.&nbsp; For example, imagine that a tool generated a bunch of code for a class representing a customer.&nbsp; It might look like this:</p> <blockquote> <p><font face="Courier New">partial class Customer<br>{<br>&nbsp; string name; </font> <p><font face="Courier New">&nbsp; public string Name<br>&nbsp; {<br>&nbsp;&nbsp;&nbsp; get<br>&nbsp;&nbsp;&nbsp; {<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; return name;<br>&nbsp;&nbsp;&nbsp;&nbsp;}<br>&nbsp;&nbsp;&nbsp; set<br>&nbsp;&nbsp;&nbsp; {<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; OnBeforeUpdateName();<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; OnUpdateName();<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; name = value;<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; OnAfterUpdateName();<br>&nbsp;&nbsp;&nbsp; }<br>&nbsp;&nbsp;} </font> <p><font face="Courier New">&nbsp; partial void OnBeforeUpdateName();<br>&nbsp; partial void OnAfterUpdateName();<br>&nbsp; partial void OnUpdateName();<br>}</font></p></blockquote> <p>If the user doesn't add any implementing definitions then this code is equivalent to:</p> <blockquote> <p><font face="Courier New">partial class Customer<br>{<br>&nbsp; string name; </font> <p><font face="Courier New">&nbsp; public string Name<br>&nbsp; {<br>&nbsp;&nbsp;&nbsp; get<br>&nbsp;&nbsp;&nbsp; {<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; return name;<br>&nbsp;&nbsp;&nbsp;&nbsp;}<br>&nbsp;&nbsp;&nbsp; set<br>&nbsp;&nbsp;&nbsp; {<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; name = value;<br>&nbsp;&nbsp;&nbsp; }<br>&nbsp;&nbsp;} </font> <p><font face="Courier New">}</font></p></blockquote> <p>No extra metadata for things that are not used and no extra instructions for useless operations.&nbsp; On the other hand if the user listened to the OnUpdateName "event" like this:</p> <blockquote> <p><font face="Courier New">partial class Customer<br>{<br>&nbsp; partial void OnUpdateName()<br>&nbsp; {<br>&nbsp;&nbsp;&nbsp; DoSomething();<br>&nbsp; }<br>}</font></p></blockquote> <p>Then the original definition is equivalent to:</p> <blockquote> <p><font face="Courier New">partial class Customer<br>{<br>&nbsp; string name; </font> <p><font face="Courier New">&nbsp; public string Name<br>&nbsp; {<br>&nbsp;&nbsp;&nbsp; get<br>&nbsp;&nbsp;&nbsp; {<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; return name;<br>&nbsp;&nbsp;&nbsp;&nbsp;}<br>&nbsp;&nbsp;&nbsp; set<br>&nbsp;&nbsp;&nbsp; {<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; OnUpdateName();<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; name = value;<br>&nbsp;&nbsp;&nbsp; }<br>&nbsp;&nbsp;} </font> <p><font face="Courier New">&nbsp; partial void OnUpdateName();<br>}</font></p></blockquote> <p><strong>Comparing Partial Methods to the Alternatives</strong></p> <p>At this point, it is sensible to ask why not just use subclassing and virtual methods?&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.&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.</p> <p><strong>A Few Fine Points</strong></p> <p>Consider the following program...</p> <blockquote> <p><font face="Courier New">partial class C<br>{<br>&nbsp; static void Main()<br>&nbsp; {<br>&nbsp;&nbsp;&nbsp; int i = 3;<br>&nbsp;&nbsp;&nbsp; C.M(i = 5);<br>&nbsp;&nbsp;&nbsp; Console.WriteLine(i);<br>&nbsp; }<br>}</font></p></blockquote> <p>What does it write to the console?&nbsp; 3, 5, ...?</p> <p>Actually, it is impossible to tell from just this code.&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.&nbsp; The same is true for conditional methods.&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.&nbsp; Of course, the same trick can be used to hide expensive calculations.</p> <blockquote> <p><font face="Courier New">partial class C<br>{<br>&nbsp; static void Main()<br>&nbsp; {<br>&nbsp;&nbsp;&nbsp; C.M(VeryVeryExpensiveCalculation());<br>&nbsp; }<br>}</font></p></blockquote> <p>If there is no implementing declaration then the very very expensive calculation will never be performed.</p> <p>Now what about attributes, how does those work?</p> <blockquote> <p><font face="Courier New">partial class D<br>{<br>&nbsp; [W]<br>&nbsp; [return:X]<br>&nbsp; partial void M&lt;[Y]T&gt;([Z]int foo)<br>&nbsp; {<br>&nbsp; } </font> <p><font face="Courier New">&nbsp; [Z]<br>&nbsp; [return:W]<br>&nbsp; partial void M&lt;[X]T&gt;([Y]int foo);<br>}</font></p></blockquote> <p>What attributes are actually emitted on M?&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.</p> <p>Enjoy!</p>]]></content:encoded>
    </item>
    <item>
      <title>All About Iterators</title>
      <link>https://docs.microsoft.com/archive/blogs/wesdyer/all-about-iterators</link>
      <pubDate>Fri, 23 Mar 2007 04:26:00 GMT</pubDate>
      <dc:creator><![CDATA[wesdyer]]></dc:creator>
      <guid
        isPermaLink="false">https://blogs.msdn.microsoft.com/wesdyer/2007/03/23/all-about-iterators/</guid>
      <description><![CDATA[Design patterns have been all of the rage for a number of years now.&nbsp; We have design patterns...]]></description>
      <content:encoded><![CDATA[<p><a href="https://en.wikipedia.org/wiki/Design_pattern_(computer_science)">Design patterns</a> have been all of the rage for a number of years now.&nbsp; We have design patterns for concurrency, user interfaces, data access, object creation, and so many other things.&nbsp; The seminal work on the topic is the <a href="https://en.wikipedia.org/wiki/Gang_of_Four_%28software%29">Gang of Four</a>'s book, <a href="https://www.amazon.com/Design-Patterns-Object-Oriented-Addison-Wesley-Professional/dp/0201633612/ref=pd_bbs_1/002-3886557-6494420?ie=UTF8&amp;s=books&amp;qid=1174622120&amp;sr=8-1">Design Patterns</a>.&nbsp; When used appropriately they are a fantastic way to codify the wisdom gleaned from the battles we have fought building software systems.</p> <p><a href="https://www.paulgraham.com/icad.html">One</a> <a href="https://perl.plover.com/yak/design/">of</a> <a href="https://discuss.joelonsoftware.com/default.asp?joel.3.219431.12">the</a> <a href="https://norvig.com/design-patterns/ppframe.htm">criticisms</a> <a href="https://www.parand.com/say/index.php/2005/07/18/i-hate-patterns/">leveled</a> <a href="https://citeseer.ist.psu.edu/felleisen90expressive.html">at</a> <a href="https://etymon.blogspot.com/2006/04/perils-of-avoiding-heresy-or-what-are.html">design</a> <a href="https://blog.plover.com/prog/design-patterns.html">patterns</a> is that they are simply formalisms to address&nbsp;weaknesses in&nbsp;programming languages.&nbsp; They require&nbsp;the human compiler to generate code&nbsp;whenever a&nbsp;specific recurring problem is encountered that cannot be solved directly with language support.&nbsp; Now this might sound like heresy to some, but&nbsp;there is some truth to the criticism.&nbsp; Programmers adapt to the shortcomings in the languages they use by generating pattern like code either by hand or with <a href="https://en.wikipedia.org/wiki/Metaprogramming">metaprogramming</a> (generics, dynamic code generation, reflection, expression trees, macros).</p> <p>Let's take a look at one such example.</p> <p><strong>The Iterator Design Pattern</strong></p> <p>Among the many patterns&nbsp;in the literature is the <a href="https://en.wikipedia.org/wiki/Iterator_pattern">iterator pattern</a>.</p> <p><img height="275" alt="Iterator Design Pattern" src="https://msdnshared.blob.core.windows.net/media/TNBlogsFS/BlogFileStorage/blogs_msdn/wesdyer/WindowsLiveWriter/TheCostofIterators_A895/image015.png" original-url="https://blogs.msdn.com/blogfiles/wesdyer/WindowsLiveWriter/TheCostofIterators_A895/image015.png" width="420">&nbsp;</p> <p>In .NET this pattern is embodied by <a href="https://msdn2.microsoft.com/en-us/library/system.collections.ienumerable.aspx">IEnumerable</a>/<a href="https://msdn2.microsoft.com/en-us/library/9eekhta0.aspx">IEnumerable&lt;T&gt;<t></a> and <a href="https://msdn2.microsoft.com/en-us/library/system.collections.ienumerator.aspx">IEnumerator</a>/<a href="https://msdn2.microsoft.com/en-us/library/78dfe2yb.aspx">IEnumerator&lt;T&gt;<t></a>.</p> <p><img height="78" alt="IEnumerable&lt;T&gt; and IEnumerator&lt;T&gt;" src="https://msdnshared.blob.core.windows.net/media/TNBlogsFS/BlogFileStorage/blogs_msdn/wesdyer/WindowsLiveWriter/TheCostofIterators_A895/image014.png" original-url="https://blogs.msdn.com/blogfiles/wesdyer/WindowsLiveWriter/TheCostofIterators_A895/image014.png" width="425"> </p> <p>An IEnumerable&lt;T&gt; is something that can be enumerated (iterated) by calling GetEnumerator which will return an IEnumerator&lt;T&gt; (iterator).&nbsp; The IEnumerator&lt;T&gt; is used to move a virtual cursor over the items that are iterated.</p> <p>Implementing the iterator pattern is a bit onerous.&nbsp; For example, here is the suggested iterator implementation for List&lt;T&gt;&nbsp;from the Design Pattern book.</p> <blockquote> <p><font face="Courier New">class ListIterator&lt;T&gt; : IEnumerator&lt;T&gt;<br>{<br>&nbsp; List&lt;T&gt; list;<br>&nbsp; int current; </font> <p><font face="Courier New">&nbsp; public ListIterator(List&lt;T&gt; list)<br>&nbsp; {<br>&nbsp;&nbsp;&nbsp; this.list = list;<br>&nbsp;&nbsp;&nbsp; current = -1;<br>&nbsp; } </font> <p><font face="Courier New">&nbsp; public T Current {&nbsp;get { return list[current]; } } </font> <p><font face="Courier New">&nbsp; public bool MoveNext()<br>&nbsp; {<br>&nbsp;&nbsp;&nbsp; return ++current &lt; list.Count;<br>&nbsp; } </font> <p><font face="Courier New">&nbsp; public void Reset()<br>&nbsp; {<br>&nbsp;&nbsp;&nbsp; current = -1;<br>&nbsp; }<br>}</font></p></blockquote> <p>Since we can't change the list itself, we can introduce a ListIterable&lt;T&gt; that wraps a list.</p> <blockquote> <p><font face="Courier New">class ListIterable&lt;T&gt; : IEnumerable&lt;T&gt;<br>{<br>&nbsp; List&lt;T&gt; list; </font> <p><font face="Courier New">&nbsp; public ListIterable(List&lt;T&gt; list)<br>&nbsp; {<br>&nbsp;&nbsp;&nbsp; this.list = list;<br>&nbsp; } </font> <p><font face="Courier New">&nbsp; public IEnumerator&lt;T&gt; GetEnumerator()<br>&nbsp; {<br>&nbsp;&nbsp;&nbsp; return new ListIterator&lt;T&gt;(list);<br>&nbsp; } </font> <p><font face="Courier New">} </font></p></blockquote> <p>And finally, we can write a method called GetElements which returns an IEnumerable&lt;T&gt; over the elements of a List&lt;T&gt;.</p> <blockquote> <p><font face="Courier New">static IEnumerable&lt;T&gt; GetElements&lt;T&gt;(this List&lt;T&gt; list)<br>{<br>&nbsp; return new ListIterable&lt;T&gt;(list);<br>}</font></p></blockquote> <p><strong>Iterators in C#</strong></p> <p>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.&nbsp; Instead of writing the iterator above, we can simply write the following:</p> <blockquote> <p><font face="Courier New">static IEnumerable&lt;T&gt; GetElements&lt;T&gt;(this List&lt;T&gt; list)<br>{<br>&nbsp; for (int index = 0; index &lt; list.Count; ++index)<br>&nbsp;&nbsp;&nbsp; yield return list[index];<br>}</font></p></blockquote> <p>When the C# compiler sees this method, it translates it into something very similar to the ListIterator&lt;T&gt; and ListIterable&lt;T&gt;&nbsp;above.&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;):  <blockquote><pre></pre>
<p><font face="Courier New">private static IEnumerable&lt;T&gt; GetElements&lt;T&gt;(this List&lt;T&gt; list)<br>{<br>&nbsp; GetElementsIterator&lt;T&gt; temp = new GetElementsIterator&lt;T&gt;(-2);<br>&nbsp; temp.listParameter = list;<br>&nbsp; return temp;<br>}</font><pre></pre></blockquote>
<p>This is remarkably closer to the first GetElements&nbsp;we wrote rather than the second.&nbsp;&nbsp;Like in the first GetElements, we create an object that implements IEnumerable&lt;T&gt; and parameterize this object with the list that was passed in.&nbsp; The <em>only</em> other thing that happens in this implementation that doesn't in the first GetElements method&nbsp;is a -2 is passed into the object.&nbsp; I'll come back to this later, but first let's take a look at the GetElementsIterator&lt;T&gt; class (I omitted a few details and changed names&nbsp;for clarity). 
<blockquote><pre></pre>
<p><font face="Courier New">private sealed class GetElementsIterator&lt;T&gt; : IEnumerable&lt;T&gt;, IEnumerator&lt;T&gt;<br>{<br>&nbsp; int state;<br>&nbsp; T current;<br>&nbsp; public List&lt;T&gt; listParameter;<br>&nbsp; int initialThreadId;<br>&nbsp; public int index;<br>&nbsp; public List&lt;T&gt; list; </font>
<p><font face="Courier New">&nbsp; public GetElementsIterator(int state);<br>&nbsp; private bool MoveNext();<br>&nbsp; IEnumerator&lt;T&gt; IEnumerable&lt;T&gt;.GetEnumerator();<br>&nbsp; void IEnumerator.Reset(); </font>
<p><font face="Courier New">&nbsp; T IEnumerator&lt;T&gt;.Current { get; }<br>}</font></p></blockquote>
<p>The most important thing to note at this time is that GetElementsIterator implements <em>both </em>IEnumerable&lt;T&gt; and IEnumerator&lt;T&gt;.&nbsp; A strange combination, but we will see why in a little while.&nbsp; Now let's look at what actually happened when we ran the constructor.&nbsp; <pre></pre>
<p>
<blockquote>
<p><font face="Courier New">public GetElementsIterator(int state)<br>{<br>&nbsp; this.state = state;<br>&nbsp; this.initialThreadId = Thread.CurrentThread.ManagedThreadId;<br>}</font></p></blockquote>
<p>Did the constructor run the for loop?&nbsp; No, it didn't.&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).&nbsp; The state variable marks what state the GetElementsIterator is in.&nbsp; The number -2 is the "I'm an IEnumerable&lt;T&gt;" state.&nbsp; Now, let's look at the GetEnumerator method. 
<blockquote><pre></pre>
<p><font face="Courier New">IEnumerator&lt;T&gt; IEnumerable&lt;T&gt;.GetEnumerator()<br>{<br>&nbsp; GetElementsIterator&lt;T&gt; temp;<br>&nbsp; if ((Thread.CurrentThread.ManagedThreadId == initialThreadId) &amp;&amp; (state == -2))<br>&nbsp; {<br>&nbsp;&nbsp;&nbsp; state = 0;<br>&nbsp;&nbsp;&nbsp; temp = this;<br>&nbsp; }<br>&nbsp; else<br>&nbsp; {<br>&nbsp;&nbsp;&nbsp; temp = new GetElementsIterator&lt;T&gt;(0);<br>&nbsp; }<br>&nbsp; temp.list = this.listParameter;<br>&nbsp; return temp;<br>}</font></p></blockquote><pre></pre>
<p>The method first checks to see if the thread that is calling GetEnumerator is the same thread that created the GetElementsIterator object.&nbsp; If it is the same thread and if the GetElementsIterator is in the "I'm an IEnumerable&lt;T&gt;" state then the state is changed to the "I'm an initialized IEnumerator&lt;T&gt;" state.&nbsp; Otherwise, a new object of the same type is created but it is immediately put in the "I'm an initialized IEnumerator&lt;T&gt;" state so that thread safety is maintained.&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. 
<p>In Whidbey code, you will see that the if statement is different because an Interlock.Exchange was used to perform the same task.&nbsp; The change was made to improve performance (especially for iterators that have 0 or 1 items to iterate over). 
<p>Now we have seen why GetElementsIterator implements both IEnumerable&lt;T&gt; and IEnumerator&lt;T&gt;, because it can morph from the IEnumerable&lt;T&gt; role into the IEnumerator&lt;T&gt; role without creating any new objects in most cases. 
<p>The Current property is very simple. 
<blockquote><pre></pre>
<p><font face="Courier New">T IEnumerator&lt;T&gt;.Current<br>{<br>&nbsp; get<br>&nbsp; {<br>&nbsp;&nbsp;&nbsp; return current;<br>&nbsp; }<br>}</font></p></blockquote><pre></pre>
<p>The Reset method simply throws a NotSupportedException. 
<p>This leaves us with only the MoveNext to examine.&nbsp; We still haven't seen where the for loop went.&nbsp; Hopefully, it is in the MoveNext.&nbsp; The following code is produced with the /o+ compiler option (optimizations turned on). 
<blockquote><pre></pre>
<p><font face="Courier New">private bool MoveNext()<br>{<br>&nbsp; switch (state)<br>&nbsp; {<br>&nbsp; case 0:<br>&nbsp;&nbsp;&nbsp; state = -1;<br>&nbsp;&nbsp;&nbsp; index = 0;<br>&nbsp;&nbsp;&nbsp; break; </font>
<p><font face="Courier New">&nbsp; case 1:<br>&nbsp;&nbsp;&nbsp; state = -1;<br>&nbsp;&nbsp;&nbsp; index++;<br>&nbsp;&nbsp;&nbsp; break; </font>
<p><font face="Courier New">&nbsp; default:<br>&nbsp;&nbsp;&nbsp; goto Done;<br>&nbsp; }<br>&nbsp; if (index &lt; list.Count)<br>&nbsp; {<br>&nbsp;&nbsp;&nbsp; current = list[index];<br>&nbsp;&nbsp;&nbsp; state = 1;<br>&nbsp;&nbsp;&nbsp; return true;<br>&nbsp; }<br>Done:<br>&nbsp; return false;<br>}</font></p></blockquote><pre></pre>
<p>Hm...a switch statement over a variable called state with a number integer case labels.&nbsp; It looks like a state machine and indeed it is.&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.&nbsp; Then we check to see if the index is less than the number of things in the list.&nbsp; If so then we set current to the current list element based on the index and set the state to 1.&nbsp; We return true indicating that there is something to consume. 
<p>The second call to MoveNext will run case 1 since the state is equal to 1.&nbsp; It will again set the state to -1 and increment the index.&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. 
<p>This continues until there nothing left to consume and false is returned. 
<p>Finally, we found our for loop.&nbsp; It is encoded in the MoveNext.&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.&nbsp; It never computes more than it needs to.&nbsp; This is why iterators are an example of deferred execution.&nbsp; When the actual GetElements method was called, no elements were realized at all!&nbsp; Later as MoveNext is called, one element at a time is realized.&nbsp; This of course enables all of sorts of <a href="https://blogs.msdn.com/wesdyer/archive/2007/02/13/the-virtues-of-laziness.aspx">great scenarios</a> such as the pay-as-you-go model and the ability to have infinite lists. 
<p><strong>The Cost of Iterators</strong> 
<p>Iterators are very performant.&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.&nbsp; But sometimes you can get into trouble. 
<p>Consider the definition of the Concat sequence operator in Linq to Objects.&nbsp; It looks something like this: 
<blockquote>
<p><font face="Courier New">static IEnumerable&lt;T&gt; Concat&lt;T&gt;(this IEnumerable&lt;T&gt; sequence1, IEnumerable&lt;T&gt; sequence2)<br>{<br>&nbsp; foreach (var item in sequence1)<br>&nbsp;&nbsp;&nbsp; yield return item;<br>&nbsp; foreach (var item in sequence2)<br>&nbsp;&nbsp;&nbsp; yield return item;<br>}</font></p></blockquote>
<p>Let's write a little benchmark to evaluate the performance of concat. 
<blockquote>
<p><font face="Courier New">var stopWatch = new Stopwatch();<br>for (int length = 0; length &lt;= 10000; length += 1000)<br>{<br>&nbsp; var list = new[] { 1 };<br>&nbsp; IEnumerable&lt;int&gt; ones = list;<br>&nbsp; for (int i = 0; i &lt; length; ++i)<br>&nbsp;&nbsp;&nbsp; ones = ones.Concat(list); </font>
<p><font face="Courier New">&nbsp; stopWatch.Reset();<br>&nbsp; stopWatch.Start(); </font>
<p><font face="Courier New">&nbsp; foreach (var item in ones) ; </font>
<p><font face="Courier New">&nbsp; stopWatch.Stop();<br>&nbsp; Console.WriteLine("Length: {0} Time: {1}", length, stopWatch.ElapsedMilliseconds);<br>}</font></p></blockquote>
<p>The results may be perhaps surprising.&nbsp; The time to evalute the foreach statement is not linearly proportional to the number of concats that are composed together.&nbsp; In fact it is proportional to the square of the number of concats composed together.</p><a href="https://msdnshared.blob.core.windows.net/media/TNBlogsFS/BlogFileStorage/blogs_msdn/wesdyer/WindowsLiveWriter/TheCostofIterators_A895/image022.png" original-url="https://blogs.msdn.com/blogfiles/wesdyer/WindowsLiveWriter/TheCostofIterators_A895/image022.png" atomicselection="true"><img style="border-top-width: 0px; border-left-width: 0px; border-bottom-width: 0px; border-right-width: 0px" height="307" src="https://msdnshared.blob.core.windows.net/media/TNBlogsFS/BlogFileStorage/blogs_msdn/wesdyer/WindowsLiveWriter/TheCostofIterators_A895/image0_thumb14.png" original-url="https://blogs.msdn.com/blogfiles/wesdyer/WindowsLiveWriter/TheCostofIterators_A895/image0_thumb14.png" width="520" border="0"></a> 
<p>Upon closer inspection the reason why is obvious.&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.&nbsp; But note that in this example, n is always 1.&nbsp; The outermost call is O(m+1).&nbsp; The next call has O((m-1)+1), then O((m-2)+1), ... O(1+1).&nbsp; There are m of these calls so the running time should be O(m^2).&nbsp; Essentially, composing concats together like this causes O(m^2) yield returns to be executed. 
<p>Of course, using a List&lt;T&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. 
<p>Iterators are even more fun if the data structure that is being enumerated is more complicated.&nbsp; For example, consider iterating over n-ary trees.&nbsp; Here is a quick definition of a n-ary tree. 
<blockquote>
<p><font face="Courier New"></font>
<p><font face="Courier New">class Tree&lt;T&gt;<br>{<br>&nbsp; public T Value { get; private set; }<br>&nbsp; public Tree&lt;T&gt; NextSibling { get; private set; }<br>&nbsp; public Tree&lt;T&gt; FirstChild { get; private set; } </font>
<p><font face="Courier New">&nbsp; public Tree(T value, Tree&lt;T&gt; nextSibling, Tree&lt;T&gt; firstChild)<br>&nbsp; {<br>&nbsp;&nbsp;&nbsp; Value = value;<br>&nbsp;&nbsp;&nbsp; NextSibling = nextSibling;<br>&nbsp;&nbsp;&nbsp; FirstChild = firstChild;<br>&nbsp; } </font>
<p><font face="Courier New">&nbsp; public IEnumerable&lt;Tree&lt;T&gt;&gt; GetChildren()<br>&nbsp; {<br>&nbsp;&nbsp;&nbsp; for (var current = FirstChild; current != null; current = current.NextSibling)<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; yield return current;<br>&nbsp; }<br>}</font></p></blockquote>
<p>Now it is easy to define an iterator that performs a preorder traversal of a n-ary tree. 
<blockquote>
<p><font face="Courier New"></font>
<p><font face="Courier New">static IEnumerable&lt;T&gt; PreOrderWalk&lt;T&gt;(this Tree&lt;T&gt; tree)<br>{<br>&nbsp; if (tree == null)<br>&nbsp;&nbsp;&nbsp; yield break;<br>&nbsp; yield return tree.Value;<br>&nbsp; foreach (var subTree in tree.GetChildren())<br>&nbsp;&nbsp;&nbsp; foreach (var item in subTree.PreOrderWalk())<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; yield return item;<br>}</font></p></blockquote>
<p>Just the way that I like code: clear and concise.&nbsp; The only problem is that the iterator could be more efficient.&nbsp; This may or may not be a problem.&nbsp; In a library it will almost certainly be a problem. 
<p>We can improve the efficiency somewhat by changing the code: 
<blockquote>
<p><font face="Courier New">static IEnumerable&lt;T&gt; PreOrderWalk&lt;T&gt;(this Tree&lt;T&gt; tree)<br>{<br>&nbsp; var stack = new Stack&lt;Tree&lt;T&gt;&gt;();<br>&nbsp; if (tree != null)<br>&nbsp;&nbsp;&nbsp; stack.Push(tree);<br>&nbsp; while (stack.Count &gt; 0)<br>&nbsp; {<br>&nbsp;&nbsp;&nbsp; for (var current = stack.Pop(); current != null; current = current.FirstChild)<br>&nbsp; &nbsp; {<br>&nbsp;&nbsp;&nbsp; &nbsp; yield return current.Value;<br>&nbsp; &nbsp;&nbsp;&nbsp; if (current.NextSibling != null)<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &nbsp; stack.Push(current.NextSibling);<br>&nbsp;&nbsp;&nbsp; }<br>&nbsp; }<br>}</font></p></blockquote>
<p>This second iterator doesn't recursively call iterators thus&nbsp;avoiding both the recursive call and the extra allocations.&nbsp; Instead, it maintains a stack of work to do after the leftmost path has been exhausted.&nbsp; Once the leftmost path has been exhausted then a node is popped off and the leftmost traversal is resumed at that node. 
<p>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,&nbsp;dominates the cost of the traversal.&nbsp; In the graph below, the green line indicates the total number of nodes in the tree.&nbsp; The trees have a branching factor of 2. 
<p><a href="https://msdnshared.blob.core.windows.net/media/TNBlogsFS/BlogFileStorage/blogs_msdn/wesdyer/WindowsLiveWriter/TheCostofIterators_A895/image026.png" original-url="https://blogs.msdn.com/blogfiles/wesdyer/WindowsLiveWriter/TheCostofIterators_A895/image026.png" atomicselection="true"><img style="border-top-width: 0px; border-left-width: 0px; border-bottom-width: 0px; border-right-width: 0px" height="310" src="https://msdnshared.blob.core.windows.net/media/TNBlogsFS/BlogFileStorage/blogs_msdn/wesdyer/WindowsLiveWriter/TheCostofIterators_A895/image0_thumb16.png" original-url="https://blogs.msdn.com/blogfiles/wesdyer/WindowsLiveWriter/TheCostofIterators_A895/image0_thumb16.png" width="517" border="0"></a> 
<p>So the key takeaway here is that iterators have great performance but as always <em>measure the performance of your code</em>.&nbsp; If you find that performance is suffering, use a combination of profiling and analysis to find the problem.&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.&nbsp; In other cases, it might be the usage of the iterators as&nbsp;with pathological Concats. 
<p><strong>One Possibility for Language Improvement (not in Orcas)</strong> 
<p>The Concat sequence operator is interesting because there is a lot of code that is seemingly redundant.&nbsp; It takes two sequences and then has to iterate over them and yield their elements.&nbsp; It's like it needs to expand their insides just to package them up together again.&nbsp; As we have seen this doesn't lead to the best performance and the code is overly verbose. 
<p>Bart Jacobs, Erik Meijer, Frank Piessens, and Wolfram Shulte wrote <a href="https://citeseer.ist.psu.edu/cache/papers/cs2/355/http:zSzzSzwww.cs.kuleuven.ac.bezSz~frankzSzPAPERSzSzFTfJP2005.pdf/iterators-revisited-proof-rules.pdf">a very interesting paper</a> on a possible language improvement that would improve both the usability and the performance of iterators.&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. 
<p>For example with this language feature, the Concat sequence operator would look something like this: 
<blockquote>
<p><font face="Courier New">static IEnumerable&lt;T&gt; Concat&lt;T&gt;(this IEnumerable&lt;T&gt; sequence1, IEnumerable&lt;T&gt; sequence2)<br>{<br>&nbsp; yield foreach sequence1;<br>&nbsp; yield foreach sequence2;<br>}</font></p></blockquote>
<p>Notice that the code is simplier and it is also more performant. 
<p>A&nbsp;programmer could use yield return, yield break, and yield foreach in the same iterator.&nbsp; An iterator FromTo can be defined recursively as follows: 
<blockquote>
<p><font face="Courier New">static IEnumerable&lt;int&gt; FromTo(int b, int e)<br>{<br>&nbsp; if (b &gt; e)<br>&nbsp;&nbsp;&nbsp; yield break;<br>&nbsp; yield return b;<br>&nbsp; yield foreach FromTo(b + 1, e);<br>}</font></p></blockquote>
<p>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. 
<p><a href="https://msdnshared.blob.core.windows.net/media/TNBlogsFS/BlogFileStorage/blogs_msdn/wesdyer/WindowsLiveWriter/TheCostofIterators_A895/image031.png" original-url="https://blogs.msdn.com/blogfiles/wesdyer/WindowsLiveWriter/TheCostofIterators_A895/image031.png" atomicselection="true"><img style="border-top-width: 0px; border-left-width: 0px; border-bottom-width: 0px; border-right-width: 0px" height="368" src="https://msdnshared.blob.core.windows.net/media/TNBlogsFS/BlogFileStorage/blogs_msdn/wesdyer/WindowsLiveWriter/TheCostofIterators_A895/image0_thumb19.png" original-url="https://blogs.msdn.com/blogfiles/wesdyer/WindowsLiveWriter/TheCostofIterators_A895/image0_thumb19.png" width="558" border="0"></a> 
<p>The next post will pick up on understanding the performance of Linq to objects queries. 
]]></content:encoded>
    </item>
    <item>
      <title>Performance Engineering</title>
      <link>https://docs.microsoft.com/archive/blogs/wesdyer/performance-engineering</link>
      <pubDate>Tue, 20 Mar 2007 05:52:56 GMT</pubDate>
      <dc:creator><![CDATA[wesdyer]]></dc:creator>
      <guid
        isPermaLink="false">https://blogs.msdn.microsoft.com/wesdyer/2007/03/20/performance-engineering/</guid>
      <description><![CDATA[Recently, many people have asked me about the performance of Linq.&nbsp; The questions have ranged...]]></description>
      <content:encoded><![CDATA[<p>Recently, many people have asked me about the performance of Linq.&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?"</p> <p>I want to address these questions.&nbsp;&nbsp;So before I dive into some of them individually, I want to set up a framework for discussions about performance.&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.</p> <p>Performance&nbsp;is&nbsp;critical to the success of any application and <em>engineering</em> performance is a fundamental part of what developers should be doing on a day to day basis.&nbsp; Great performance doesn't just happen.&nbsp; It must have requirements, be designed, implemented, and tested just like any other feature.&nbsp; Individuals and teams must foster a culture of performance.</p> <p><strong>Performance Requirements</strong></p> <p>Rico Mariani wrote a great post about why performance must be <a href="https://blogs.msdn.com/ricom/archive/2006/12/21/do-performance-analysis-in-context.aspx">measured in context</a>.&nbsp; That means that performance goals should be made in relation to what the user sees and cares about.&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.&nbsp; Many times when performance is tuned in one dimension it can degrade in other dimensions.&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.&nbsp; So how does a programmer know which dimension is most important?&nbsp; Consider the performance in context.&nbsp; Furthermore, the performance tuning that a programmer makes might not even matter when considered in context.&nbsp; So spend your time where in counts.&nbsp;&nbsp;Finally, it is much easier to consider trade-offs between performance requirements and other requirements when the performance requirements are in context.&nbsp; Set up a performance budget in terms that are material and important&nbsp;to the customer.</p> <p><strong>Designing for Performance</strong></p> <p>Designing for performance is important.&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.&nbsp; However, care must be taken because often these poor design choices were made for the sake of "better performance".&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&nbsp;operations that it precludes concurrency.</p> <p>Most of these poor design choices are caused by the design not solving the right problem (performance requirements)&nbsp;or because the requirements changed over time and the earlier design made it difficult to adapt to the new requirements.</p> <p><strong>Understanding Performance</strong></p> <p>There are at least two basic tools for understanding performance.</p> <p><strong>1.&nbsp; </strong><a href="https://en.wikipedia.org/wiki/Asymptotic_analysis"><strong>Asymptotic Analysis</strong></a></p> <p>I am sure that my readers know and love asymptotic analysis.&nbsp; It is so important that developers know what they are doing when they call a System.* function, which&nbsp;has an O(n) time complexity, n times -- O(n^2) behavior.&nbsp; Know what is going on in terms of both space and time.</p> <p><strong>2.&nbsp; Benchmarks / Profilers</strong></p> <p>So often when a performance problem exists, developers will convince themselves that they know what the problem is&nbsp;without accurately measuring the behavior of the system.&nbsp; They will proceed to "fix" the problem only to discover that what they thought would be of great benefit is in fact unimportant.</p> <p>I've done that.&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.&nbsp; My first application was a&nbsp;good sized&nbsp;application that including a custom scripting engine inside of it.&nbsp; The performance wasn't great and so I set about fixing it.&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.&nbsp; But I found that it didn't help matters at all.</p> <p>At this point, I broke out a profiler and began measuring the actual behavior of the system.&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.&nbsp; It was using the + operator on strings.&nbsp; Since this was my first .NET application, I had no idea that concatenating hundreds of thousands of strings was a bad idea.</p> <p>When I changed the code to use a StringBuilder instead, it sailed.&nbsp; I made a few other improvements (all of which were targeted and very small), and the application was running fine.</p> <p>Now the point of all of this is <em>not</em> that the + operator on strings should not be used.&nbsp; If that were true then we would make the C# compiler issue a warning when you used it.&nbsp; The point is that a programmer should be aware of the costs and tradeoffs involved with a programming decision and act accordingly.&nbsp; Measurement is a powerful tool.&nbsp; Knowing where the problems lie is&nbsp;the key to success.&nbsp; Measure early and often.</p> <p>The result of profiling is a large set of various statistics about an application.&nbsp; If the measurements are taken in context then they are a powerful tool.&nbsp; As with any statistics, what is being measured is as important as the actual measurement.</p> <p>Analyzing an application is very rewarding.&nbsp; You are able to see the material benefits of any improvement in a very quantitative way.&nbsp; Apply the scientific method in the process of analyzing a problem.&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)&nbsp;from an operation (the suspect code) across various trials.</p> <p>Try to think big and understand not only what is the problem but why it is a problem.&nbsp; The best solutions attack not only the symptoms but the fundamental causes of the problem.&nbsp; Look to understand the nature of the problem.</p> <p><strong>Some Good Performance Resources</strong></p> <p><a href="https://blogs.msdn.com/ricom/">Rico Mariani's (Visual Studio&nbsp;Performance Architect) Blog</a></p> <p><a href="https://blogs.msdn.com/vancem/">Vance Morrison's (CLR Performance Architect) Blog</a></p>]]></content:encoded>
    </item>
  </channel>
</rss>