<?xml version="1.0" encoding="UTF-8" ?>
<?xml-stylesheet type="text/xsl" href="http://blogs.bartdesmet.net/utility/FeedStylesheets/rss.xsl" media="screen"?><rss version="2.0" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:slash="http://purl.org/rss/1.0/modules/slash/" xmlns:wfw="http://wellformedweb.org/CommentAPI/"><channel><title>B# .NET Blog : Rx</title><link>http://blogs.bartdesmet.net/blogs/bart/archive/tags/Rx/default.aspx</link><description>Tags: Rx</description><dc:language>en</dc:language><generator>CommunityServer 2007 (Build: 20423.869)</generator><item><title>Where’s Bart’s Blog Been?</title><link>http://blogs.bartdesmet.net/blogs/bart/archive/2010/07/02/where-s-bart-s-blog-been.aspx</link><pubDate>Fri, 02 Jul 2010 07:19:44 GMT</pubDate><guid isPermaLink="false">863c5522-913f-4a64-ac0a-bd5f05abad0f:21608</guid><dc:creator>bart</dc:creator><slash:comments>3</slash:comments><wfw:commentRss xmlns:wfw="http://wellformedweb.org/CommentAPI/">http://blogs.bartdesmet.net/blogs/bart/rsscomments.aspx?PostID=21608</wfw:commentRss><comments>http://blogs.bartdesmet.net/blogs/bart/archive/2010/07/02/where-s-bart-s-blog-been.aspx#comments</comments><description>&lt;p&gt;A quick update to my readers on a few little subjects. First of all, some people have noticed my blog welcomed readers with &lt;strong&gt;a not-so-sweet 404 error message&lt;/strong&gt; the last few days. Turned out my monthly bandwidth was exceeded which was enough reason for my hosting provider to take the thing offline.&lt;/p&gt;  &lt;p&gt;&lt;a href="http://bartdesmet.info/images_wlw/WheresBartsBlogBeen_49D/image.png"&gt;&lt;img style="border-right-width:0px;display:inline;border-top-width:0px;border-bottom-width:0px;border-left-width:0px;" title="image" border="0" alt="image" src="http://bartdesmet.info/images_wlw/WheresBartsBlogBeen_49D/image_thumb.png" width="550" height="300" /&gt;&lt;/a&gt; &lt;/p&gt;  &lt;p&gt;Since this is quite inconvenient I’ve started some migration of image content to another domain, which is work in progress and should (hopefully) prevent the issue from occurring again. Other measures will be taken to limit the download volumes.&lt;/p&gt;  &lt;p&gt;Secondly, many others have noticed &lt;strong&gt;it’s been quite silent on my blog lately&lt;/strong&gt;. As my colleague &lt;a href="http://blogs.msdn.com/wesdyer"&gt;Wes&lt;/a&gt; warned me, once you start enjoying every day of functional programming hacking on Erik’s team, time for blogging steadily decreases. What we call “hacking” has been applied to many projects we’ve been working on over here in the Cloud Programmability Team, some of which are yet undisclosed. The most visible one today is obviously the &lt;a href="http://msdn.microsoft.com/en-us/devlabs/ee794896.aspx"&gt;Reactive Extensions&lt;/a&gt; both for .NET and for JavaScript, which I’ve been evangelizing both within and outside the company. Another one which I can only give the name for is dubbed “LINQ to Anything” that’s – as you can imagine – keeping me busy and inspired on a daily and nightly basis. On top of all of this, I’ve got some other writing projects going on that are nearing completion (finally).&lt;/p&gt;  &lt;p&gt;Anyway, the big plan is to &lt;strong&gt;&lt;font color="#ff0000"&gt;break the silence&lt;/font&gt;&lt;/strong&gt; and start blogging again about our established technologies, including Rx in all its glory. Subjects will include continuation passing style, duality between IEnumerable&amp;lt;T&amp;gt; and IObservable&amp;lt;T&amp;gt;, parameterization for concurrency, discussion of the plethora of operators available, a good portion of monads for sure, the IQbservable&amp;lt;T&amp;gt; interface (no, I won’t discuss the &lt;a href="http://en.wikipedia.org/wiki/Color_of_the_bikeshed"&gt;color of the bikeshed&lt;/a&gt;) and one of its applications (LINQ to WMI Events), etc. Stay tuned for a series on those subjects starting in the hopefully very near future.&lt;/p&gt;  &lt;p&gt;See you soon!&lt;/p&gt;&lt;img src="http://blogs.bartdesmet.net/aggbug.aspx?PostID=21608" width="1" height="1"&gt;</description><category domain="http://blogs.bartdesmet.net/blogs/bart/archive/tags/IIgnorable/default.aspx">IIgnorable</category><category domain="http://blogs.bartdesmet.net/blogs/bart/archive/tags/Rx/default.aspx">Rx</category></item><item><title>Some introductory Rx samples</title><link>http://blogs.bartdesmet.net/blogs/bart/archive/2010/04/19/some-introductory-rx-samples.aspx</link><pubDate>Mon, 19 Apr 2010 07:45:00 GMT</pubDate><guid isPermaLink="false">863c5522-913f-4a64-ac0a-bd5f05abad0f:15110</guid><dc:creator>bart</dc:creator><slash:comments>17</slash:comments><wfw:commentRss xmlns:wfw="http://wellformedweb.org/CommentAPI/">http://blogs.bartdesmet.net/blogs/bart/rsscomments.aspx?PostID=15110</wfw:commentRss><comments>http://blogs.bartdesmet.net/blogs/bart/archive/2010/04/19/some-introductory-rx-samples.aspx#comments</comments><description>&lt;p&gt;During my last tour I’ve been collecting quite some fundamental and introductory Rx samples as illustrations with my presentations on the topic. As promised, I’m sharing those out through my blog. More Rx content is to follow in the (hopefully near) future, with an exhaustive discussion of various design principles and choices, the underlying theoretical foundation of Rx and coverage of lots of operators.&lt;/p&gt;  &lt;p&gt;In the meantime, &lt;a href="http://www.bartdesmet.net/download/Rx40Samples.zip"&gt;download the sample project here&lt;/a&gt;. While the project targets Visual Studio 2010 RTM, you can simply take the Program.cs file and build a Visual Studio 2008 project around it, referencing the necessary Rx assemblies (which you can download from &lt;a href="http://msdn.microsoft.com/en-us/devlabs/ee794896.aspx"&gt;DevLabs&lt;/a&gt;).&lt;/p&gt;  &lt;p&gt;Enjoy!&lt;/p&gt;&lt;img src="http://blogs.bartdesmet.net/aggbug.aspx?PostID=15110" width="1" height="1"&gt;</description><category domain="http://blogs.bartdesmet.net/blogs/bart/archive/tags/Rx/default.aspx">Rx</category></item><item><title>Come and join me for an Rx talk at VISUG on April 6th in Zaventem, Belgium</title><link>http://blogs.bartdesmet.net/blogs/bart/archive/2010/03/28/come-and-join-me-for-an-rx-talk-at-visug-on-april-6th-in-zaventem-belgium.aspx</link><pubDate>Sun, 28 Mar 2010 10:08:00 GMT</pubDate><guid isPermaLink="false">863c5522-913f-4a64-ac0a-bd5f05abad0f:15103</guid><dc:creator>bart</dc:creator><slash:comments>3</slash:comments><wfw:commentRss xmlns:wfw="http://wellformedweb.org/CommentAPI/">http://blogs.bartdesmet.net/blogs/bart/rsscomments.aspx?PostID=15103</wfw:commentRss><comments>http://blogs.bartdesmet.net/blogs/bart/archive/2010/03/28/come-and-join-me-for-an-rx-talk-at-visug-on-april-6th-in-zaventem-belgium.aspx#comments</comments><description>&lt;p&gt;As part of my three week African and European tour I have the honor to talk to the local Belgian Visual Studio User Group (VISUG) on April 6th in the Microsoft Belux offices in Zaventem, Belgium. Seats are limited, but there’s still time for you to register. More info &lt;a href="http://www.visug.be/Eventdetails/tabid/95/EventId/24/Default.aspx"&gt;can be found here&lt;/a&gt;. Oh, and there will be catering as well :-). Other opportunities to see me are on TechDays Belgium and DevDays Netherlands, which are both held next week. I’ll post resources about Rx talks to my blog later on and hope to find the bandwidth to write an extensive series on the topic, so stay tuned!&lt;/p&gt;
&lt;p&gt;&lt;a href="http://msdn.microsoft.com/en-us/devlabs/ee794896.aspx"&gt;&lt;img style="BORDER-BOTTOM:0px;BORDER-LEFT:0px;BORDER-TOP:0px;BORDER-RIGHT:0px;" title="" border="0" alt="" align="left" src="http://i.msdn.microsoft.com/ee794896.DevLabs_Rx_Project(en-us).png" /&gt;&lt;/a&gt;&lt;/p&gt;&lt;img src="http://blogs.bartdesmet.net/aggbug.aspx?PostID=15103" width="1" height="1"&gt;</description><category domain="http://blogs.bartdesmet.net/blogs/bart/archive/tags/Rx/default.aspx">Rx</category></item><item><title>New drop of the Reactive Extensions for .NET (Rx) available</title><link>http://blogs.bartdesmet.net/blogs/bart/archive/2010/03/05/new-drop-of-the-reactive-extensions-for-net-rx-available.aspx</link><pubDate>Fri, 05 Mar 2010 23:02:00 GMT</pubDate><guid isPermaLink="false">863c5522-913f-4a64-ac0a-bd5f05abad0f:15080</guid><dc:creator>bart</dc:creator><slash:comments>10</slash:comments><wfw:commentRss xmlns:wfw="http://wellformedweb.org/CommentAPI/">http://blogs.bartdesmet.net/blogs/bart/rsscomments.aspx?PostID=15080</wfw:commentRss><comments>http://blogs.bartdesmet.net/blogs/bart/archive/2010/03/05/new-drop-of-the-reactive-extensions-for-net-rx-available.aspx#comments</comments><description>&lt;p&gt;It&amp;#39;s been a long time I&amp;#39;ve written epic blog posts over here, but for a good reason. We&amp;#39;ve been working very hard on getting a new Rx release out the door and I&amp;#39;m proud to announce it&amp;#39;s available now through &lt;a href="http://msdn.microsoft.com/en-us/devlabs/ee794896.aspx"&gt;http://msdn.microsoft.com/en-us/devlabs/ee794896.aspx&lt;/a&gt;. Notice we got a .NET 4 RC compatible download available as well, so you can play with the latest and greatest of technologies in one big jar :-). More goodness will follow later, so stay tuned!&lt;/p&gt;
&lt;p&gt;At some point in the foreseeable future, I&amp;#39;ll start a series on how Rx works and what its operators are as well. If you have any particular topics you&amp;#39;d like to see covered, don&amp;#39;t hesitate to let me know through my blog. In the meantime, make sure to evaporate all your feedback on the forums at &lt;a href="http://social.msdn.microsoft.com/Forums/en-US/rx/threads"&gt;http://social.msdn.microsoft.com/Forums/en-US/rx/threads&lt;/a&gt;. We love to hear what you think, what operators you believe are missing, any bugs you find, etc.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Update:&lt;/strong&gt; We also have published a video on the new release at &lt;a href="http://channel9.msdn.com/posts/J.Van.Gogh/Your-RxNET-Prescription-Has-Been-Refilled"&gt;http://channel9.msdn.com/posts/J.Van.Gogh/Your-RxNET-Prescription-Has-Been-Refilled&lt;/a&gt;.&lt;/p&gt;
&lt;p&gt;Have fun!&lt;br /&gt;Bart @ Rx&lt;/p&gt;&lt;img src="http://blogs.bartdesmet.net/aggbug.aspx?PostID=15080" width="1" height="1"&gt;</description><category domain="http://blogs.bartdesmet.net/blogs/bart/archive/tags/LINQ/default.aspx">LINQ</category><category domain="http://blogs.bartdesmet.net/blogs/bart/archive/tags/Rx/default.aspx">Rx</category></item><item><title>2010 – A Personal Change: putting my “Head In The Cloud”</title><link>http://blogs.bartdesmet.net/blogs/bart/archive/2010/01/10/2010-a-personal-change-putting-my-head-in-the-cloud.aspx</link><pubDate>Mon, 11 Jan 2010 01:26:00 GMT</pubDate><guid isPermaLink="false">863c5522-913f-4a64-ac0a-bd5f05abad0f:15042</guid><dc:creator>bart</dc:creator><slash:comments>5</slash:comments><wfw:commentRss xmlns:wfw="http://wellformedweb.org/CommentAPI/">http://blogs.bartdesmet.net/blogs/bart/rsscomments.aspx?PostID=15042</wfw:commentRss><comments>http://blogs.bartdesmet.net/blogs/bart/archive/2010/01/10/2010-a-personal-change-putting-my-head-in-the-cloud.aspx#comments</comments><description>&lt;p&gt;Slightly over two years after arriving here in Redmond to work on the WPF team, time has come for me to make a switch and pursue other opportunities within the company. Starting January 13th, I’ll be working on the &lt;strong&gt;SQL Cloud Data Programmability Team&lt;/strong&gt; on various projects related to &lt;em&gt;democratizing the cloud&lt;/em&gt;. While we have much more rabbits sitting in our magician hats, &lt;a href="http://blogs.bartdesmet.net/blogs/bart/archive/tags/Rx/default.aspx"&gt;Rx&lt;/a&gt; is the first big deliverable we’re working on.&lt;/p&gt;
&lt;blockquote&gt;
&lt;p&gt;&lt;a href="http://msdn.microsoft.com/en-us/devlabs/ee794896.aspx"&gt;&lt;img style="BORDER-BOTTOM:0px;BORDER-LEFT:0px;DISPLAY:inline;MARGIN-LEFT:0px;BORDER-TOP:0px;MARGIN-RIGHT:0px;BORDER-RIGHT:0px;" title="" border="0" alt="" src="http://i.msdn.microsoft.com/ee794896.DevLabs_Rx_Project(en-us).png" /&gt;&lt;/a&gt;&lt;/p&gt;&lt;/blockquote&gt;
&lt;p&gt;For my blog, there won’t be much change as I’ve always written on topics related to what I’ll be working on: language innovation, data access, LINQ, type systems, lambda fun, etc. I’m planning to stay committed to blogging and other evangelism activities, including speaking engagements from time to time, so feel free to ping me if I’m in your proximity (or if you’re visiting our campus). Next up and confirmed are TechDays “low lands” in &lt;a href="http://www.techdays.be/"&gt;Belgium&lt;/a&gt; and the &lt;a href="http://www.devdays.nl/"&gt;Netherlands&lt;/a&gt;, end of March.&lt;/p&gt;
&lt;p&gt;Needless to say, I’m thrilled to have this opportunity of working together with a relatively small group of smart and passionate people, on the things I’d spend all my free time on anyway. Having this one-to-one alignment between day-to-day professional activities at work and all sorts of free time hacking projects is like a dream coming true. Thanks &lt;a href="http://blogs.msdn.com/dannyvv"&gt;Danny&lt;/a&gt;, &lt;a href="http://research.microsoft.com/en-us/um/people/emeijer/"&gt;Erik&lt;/a&gt;, &lt;a href="http://blogs.msdn.com/jeffva"&gt;Jeffrey&lt;/a&gt;, &lt;a href="http://www.cartesianclosed.com/"&gt;Mark&lt;/a&gt; and &lt;a href="http://blogs.msdn.com/wesdyer"&gt;Wes&lt;/a&gt; for taking me on board.&lt;/p&gt;
&lt;p&gt;Expect to see more Rx blogging love over here, and watch out for more goodness to come your way in the foreseeable future. In the meantime, check out the following resources on the matter:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;a href="http://msdn.microsoft.com/en-us/devlabs/ee794896.aspx"&gt;MSDN DevLabs Rx homepage&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="http://channel9.msdn.com/tags/Rx/"&gt;Channel 9 Rx videos&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="http://blogs.bartdesmet.net/blogs/bart/archive/tags/Rx/default.aspx"&gt;My Rx blog category&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="http://social.msdn.microsoft.com/Forums/en-US/rx/threads"&gt;Our forums&lt;/a&gt;&lt;/li&gt;&lt;/ul&gt;
&lt;p&gt;Please keep the feedback on Rx coming: help us, help you!&lt;/p&gt;&lt;img src="http://blogs.bartdesmet.net/aggbug.aspx?PostID=15042" width="1" height="1"&gt;</description><category domain="http://blogs.bartdesmet.net/blogs/bart/archive/tags/Personal/default.aspx">Personal</category><category domain="http://blogs.bartdesmet.net/blogs/bart/archive/tags/IIgnorable/default.aspx">IIgnorable</category><category domain="http://blogs.bartdesmet.net/blogs/bart/archive/tags/Rx/default.aspx">Rx</category></item><item><title>More LINQ with System.Interactive – Functional fun and taming side-effects</title><link>http://blogs.bartdesmet.net/blogs/bart/archive/2010/01/07/more-linq-with-system-interactive-functional-fun-and-taming-side-effects.aspx</link><pubDate>Thu, 07 Jan 2010 11:43:42 GMT</pubDate><guid isPermaLink="false">863c5522-913f-4a64-ac0a-bd5f05abad0f:15025</guid><dc:creator>bart</dc:creator><slash:comments>13</slash:comments><wfw:commentRss xmlns:wfw="http://wellformedweb.org/CommentAPI/">http://blogs.bartdesmet.net/blogs/bart/rsscomments.aspx?PostID=15025</wfw:commentRss><comments>http://blogs.bartdesmet.net/blogs/bart/archive/2010/01/07/more-linq-with-system-interactive-functional-fun-and-taming-side-effects.aspx#comments</comments><description>&lt;p&gt;With the recent release of the &lt;a href="http://msdn.microsoft.com/en-us/devlabs/ee794896.aspx"&gt;Reactive Extensions for .NET (Rx)&lt;/a&gt; on &lt;a href="http://msdn.microsoft.com/en-us/devlabs/default.aspx"&gt;DevLabs&lt;/a&gt;, you’ll hear quite a bit about reactive programming, based on the IObservable&amp;lt;T&amp;gt; and IObserver&amp;lt;T&amp;gt; interfaces. A great amount of resources is available &lt;a href="http://channel9.msdn.com/tags/Rx/"&gt;on Channel 9&lt;/a&gt;. In this series, I’ll focus on the &lt;a href="http://channel9.msdn.com/shows/Going+Deep/Expert-to-Expert-Brian-Beckman-and-Erik-Meijer-Inside-the-NET-Reactive-Framework-Rx/"&gt;dual&lt;/a&gt; of the System.Reactive assembly, which is System.Interactive, providing a bunch of extensions to the &lt;a href="http://www.codeplex.com/LINQSQO"&gt;LINQ Standard Query Operators&lt;/a&gt; for IEnumerable&amp;lt;T&amp;gt;. In today’s installment we’ll talk about EnumerableEx’s facilities to tame side-effects in a functionally inspired manner:&lt;/p&gt;  &lt;p&gt;&lt;a href="http://bartdesmet.net/images_wlw/Mor.InteractiveFunctionalfunandtamingsid_9DCC/image.png"&gt;&lt;img style="border-right-width:0px;display:inline;border-top-width:0px;border-bottom-width:0px;border-left-width:0px;" title="image" border="0" alt="image" src="http://bartdesmet.net/images_wlw/Mor.InteractiveFunctionalfunandtamingsid_9DCC/image_thumb.png" width="526" height="480" /&gt;&lt;/a&gt;&lt;/p&gt;  &lt;p&gt;&amp;#160;&lt;/p&gt;  &lt;h1&gt;To side effect or not to side effect?&lt;/h1&gt;  &lt;p&gt;Being rooted in query comprehensions as seen in various functional programming languages (including (the) pure one(s)), one would expect LINQ to have a very functional basis. Indeed it has, but being hosted in various not functionally pure languages like C# and Visual Basic, odds are off reasoning about side-effects in a meaningful and doable manner. As we’ve seen before, when talking about the Do and Run operators, it’s perfectly possible for a query to exhibit side-effects during iteration. You don’t even have to look that far, since every lambda passed to a query operator is an opportunity of introducing effects. The delayed execution nature of LINQ queries makes that those effects appear at the point of query execution. So far, nothing new.&lt;/p&gt;  &lt;p&gt;So, the philosophical question ought to be whether or not we should embrace side-effects or go for absolute purity. While the latter would be preferable for various reasons, it’s not enforceable through the hosting languages for LINQ, so maybe we should exploit side-effects if we really want to do so. The flip side of this train of thought is that those side-effects could come and get us if we’re not careful, especially when queries get executed multiple times, potentially as part of a bigger query. In such a case, you’d likely not want effects to be duplicated. Below is a sample of such a problematic query expression:&lt;/p&gt;  &lt;blockquote&gt;   &lt;pre class="code"&gt;&lt;span style="color:blue;"&gt;var &lt;/span&gt;xrs = &lt;span style="color:#2b91af;"&gt;EnumerableEx&lt;/span&gt;.Generate(&lt;span style="color:blue;"&gt;new &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;Random&lt;/span&gt;(), rnd =&amp;gt; &lt;span style="color:#2b91af;"&gt;EnumerableEx&lt;/span&gt;.Return(rnd.Next(100)), &lt;span style="color:green;"&gt;/* iterate */ &lt;/span&gt;_ =&amp;gt; _);
xrs.Zip(xrs, (l, r) =&amp;gt; l + r).Take(10).Run(&lt;span style="color:#2b91af;"&gt;Console&lt;/span&gt;.WriteLine);&lt;/pre&gt;
&lt;/blockquote&gt;

&lt;p&gt;Using Generate, we generate a sequence of random numbers. Recall the first argument is the state of the anamorphic Generate operator, which we get passed in the lambdas following it: once to produce an output sequence (just a single random number in our case) and once to iterate (just keeping the same random number generator here). What’s more important is we’re relying on the side-effect of reading the random number generator which, as the name implies, provides random answers to the Next inquiry every time it gets called. In essence, the side-effect can (not) be seen by looking at the signature of Random.Next, which says it returns an int. In .NET this means the method &lt;em&gt;may&lt;/em&gt; return the &lt;em&gt;same&lt;/em&gt; int every time it gets called, but there are no guarantees whatsoever (as there would be in pure functional programming languages).&lt;/p&gt;

&lt;p&gt;This side-effect, innocent and intentional as it may seem, comes and gets us if we perform a Zip on the sequence with itself. Since Zip iterates both sides, we’re really triggering separate enumeration (“GetEnumerator”) over the same sequence two times. Though it’s the same sequence object, each of its iterations will produce different results. As a result, the expected invariant of the Zip’s output being only even numbers (based on the assumption l and r would be the same as they’re produced by the same sequence) doesn’t hold:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;52
    &lt;br /&gt;114

    &lt;br /&gt;112

    &lt;br /&gt;&lt;font color="#ff0000"&gt;103
      &lt;br /&gt;41

      &lt;br /&gt;135&lt;/font&gt;

    &lt;br /&gt;78

    &lt;br /&gt;114

    &lt;br /&gt;&lt;font color="#ff0000"&gt;59
      &lt;br /&gt;137&lt;/font&gt;&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;While random number generation is a pretty innocent side-effect, not having it under control properly can lead to unexpected results as shown above. We can visualize this nicely using another side-effect introduced by Do:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;pre class="code"&gt;&lt;span style="color:blue;"&gt;var &lt;/span&gt;xrs = &lt;span style="color:#2b91af;"&gt;EnumerableEx&lt;/span&gt;.Generate(&lt;span style="color:blue;"&gt;new &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;Random&lt;/span&gt;(), rnd =&amp;gt; &lt;span style="color:#2b91af;"&gt;EnumerableEx&lt;/span&gt;.Return(rnd.Next(100)), &lt;span style="color:green;"&gt;/* iterate */ &lt;/span&gt;_ =&amp;gt; _)
    .Do(xr =&amp;gt; &lt;span style="color:#2b91af;"&gt;Console&lt;/span&gt;.WriteLine(&lt;span style="color:#a31515;"&gt;&amp;quot;! -&amp;gt; &amp;quot; &lt;/span&gt;+ xr));
&lt;font color="#ff0000"&gt;xrs&lt;/font&gt;.Zip(&lt;font color="#ff0000"&gt;xrs&lt;/font&gt;, (l, r) =&amp;gt; l + r).Take(10).Run(&lt;span style="color:#2b91af;"&gt;Console&lt;/span&gt;.WriteLine);&lt;/pre&gt;
  &lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;&lt;/blockquote&gt;

&lt;p&gt;This will print a message for every number flowing out of the random number generating sequence, as shown below:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;! -&amp;gt; 97
    &lt;br /&gt;! -&amp;gt; 78

    &lt;br /&gt;175

    &lt;br /&gt;! -&amp;gt; 11

    &lt;br /&gt;! -&amp;gt; 6

    &lt;br /&gt;17

    &lt;br /&gt;! -&amp;gt; 40

    &lt;br /&gt;! -&amp;gt; 17

    &lt;br /&gt;57

    &lt;br /&gt;! -&amp;gt; 92

    &lt;br /&gt;! -&amp;gt; 63

    &lt;br /&gt;155

    &lt;br /&gt;! -&amp;gt; 70

    &lt;br /&gt;! -&amp;gt; 13

    &lt;br /&gt;83

    &lt;br /&gt;! -&amp;gt; 41

    &lt;br /&gt;! -&amp;gt; 1

    &lt;br /&gt;42

    &lt;br /&gt;! -&amp;gt; 64

    &lt;br /&gt;! -&amp;gt; 76

    &lt;br /&gt;140

    &lt;br /&gt;! -&amp;gt; 30

    &lt;br /&gt;! -&amp;gt; 71

    &lt;br /&gt;101

    &lt;br /&gt;! -&amp;gt; 1

    &lt;br /&gt;! -&amp;gt; 81

    &lt;br /&gt;82

    &lt;br /&gt;! -&amp;gt; 65

    &lt;br /&gt;! -&amp;gt; 45

    &lt;br /&gt;110&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;If we look a bit further to the original query, we come to the conclusion we can’t apply any form of equational reasoning anymore: it seems that the common subexpression “xrs” is not “equal” (as in exposing the same results) in both use sites. The immediate reason in the case of LINQ is the delayed execution, which is a good thing as our Generate call produces an infinite sequence. More broadly, it’s the side-effect that lies at the heart of the problem as equational reasoning breaks down in such a setting. For that very reason, side-effect permitting languages have a much harder time carrying out optimizations to code and need to be very &lt;em&gt;strict&lt;/em&gt; about specifying the order in which operations are performed (e.g. in C#, arguments to a method call – which is always “call-by-value” – are evaluated in a left-to-right order).&lt;/p&gt;

&lt;p&gt;Moving Take(10) up doesn’t change the delayed characteristic either:&lt;/p&gt;

&lt;blockquote&gt;&lt;/blockquote&gt;

&lt;blockquote&gt;
  &lt;pre class="code"&gt;&lt;span style="color:blue;"&gt;var &lt;/span&gt;xrs = &lt;span style="color:#2b91af;"&gt;EnumerableEx&lt;/span&gt;.Generate(&lt;span style="color:blue;"&gt;new &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;Random&lt;/span&gt;(), rnd =&amp;gt; &lt;span style="color:#2b91af;"&gt;EnumerableEx&lt;/span&gt;.Return(rnd.Next(100)), &lt;span style="color:green;"&gt;/* iterate */ &lt;/span&gt;_ =&amp;gt; _)
&lt;strong&gt;&lt;font color="#ff0000"&gt;    .Take(10)&lt;/font&gt;&lt;/strong&gt;
    .Do(xr =&amp;gt; &lt;span style="color:#2b91af;"&gt;Console&lt;/span&gt;.WriteLine(&lt;span style="color:#a31515;"&gt;&amp;quot;! -&amp;gt; &amp;quot; &lt;/span&gt;+ xr));
xrs.Zip(xrs, (l, r) =&amp;gt; l + r).Run(&lt;span style="color:#2b91af;"&gt;Console&lt;/span&gt;.WriteLine);&lt;/pre&gt;
  &lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;&lt;/blockquote&gt;

&lt;p&gt;What would help is forcing the common subexpression’s query to execute, persisting (= caching) its results in memory, before feeding them in to the expression using it multiple times:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;pre class="code"&gt;&lt;span style="color:blue;"&gt;var &lt;/span&gt;xrs = &lt;span style="color:#2b91af;"&gt;EnumerableEx&lt;/span&gt;.Generate(&lt;span style="color:blue;"&gt;new &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;Random&lt;/span&gt;(), rnd =&amp;gt; &lt;span style="color:#2b91af;"&gt;EnumerableEx&lt;/span&gt;.Return(rnd.Next(100)), &lt;span style="color:green;"&gt;/* iterate */ &lt;/span&gt;_ =&amp;gt; _)
    .Take(10)&lt;font color="#00ff00"&gt;.ToArray()&lt;/font&gt;
    .Do(xr =&amp;gt; &lt;span style="color:#2b91af;"&gt;Console&lt;/span&gt;.WriteLine(&lt;span style="color:#a31515;"&gt;&amp;quot;! -&amp;gt; &amp;quot; &lt;/span&gt;+ xr));
xrs.Zip(xrs, (l, r) =&amp;gt; l + r).Run(&lt;span style="color:#2b91af;"&gt;Console&lt;/span&gt;.WriteLine);&lt;/pre&gt;
  &lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;&lt;/blockquote&gt;

&lt;p&gt;Don’t forget the Take(10) call though, as calling ToArray (or ToList) on an infinite sequence is not quite advised on today’s machines with finite amounts of memory. It’s clear such hacking is quite brittle and it breaks the delayed execution nature of the query expression. In other words, you can’t really hand out the resulting expression to a caller for it to call when it needs results (if it ever does). We’re too eager about evaluating (part of) the query, just to be able to tame the side-effect:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;pre class="code"&gt;&lt;span style="color:blue;"&gt;var &lt;/span&gt;xrs = &lt;span style="color:#2b91af;"&gt;EnumerableEx&lt;/span&gt;.Generate(&lt;span style="color:blue;"&gt;new &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;Random&lt;/span&gt;(), rnd =&amp;gt; &lt;span style="color:#2b91af;"&gt;EnumerableEx&lt;/span&gt;.Return(rnd.Next(100)), &lt;span style="color:green;"&gt;/* iterate */ &lt;/span&gt;_ =&amp;gt; _)
    .Take(10)&lt;font color="#ff0000"&gt;.ToArray()&lt;/font&gt;;

&lt;span style="color:blue;"&gt;var &lt;/span&gt;randomEvens = xrs.Zip(xrs, (l, r) =&amp;gt; l + r);&lt;/pre&gt;

  &lt;pre class="code"&gt;&lt;span style="color:green;"&gt;// What if the consumer of randomEvens &lt;em&gt;expects&lt;/em&gt; different results on each enumeration... Hard cheese! &lt;/span&gt;
randomEvens.Run(&lt;span style="color:#2b91af;"&gt;Console&lt;/span&gt;.WriteLine);
randomEvens.Run(&lt;span style="color:#2b91af;"&gt;Console&lt;/span&gt;.WriteLine);&lt;/pre&gt;
  &lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;&lt;/blockquote&gt;

&lt;p&gt;It’s clear that we need some more tools in our toolbox to tame desired side-effects when needed. That’s exactly what this post focuses on.&lt;/p&gt;

&lt;p&gt;&amp;#160;&lt;/p&gt;

&lt;h1&gt;Option 1: Do nothing with Let&lt;/h1&gt;

&lt;p&gt;A first way to approach side-effects is to embrace them as-is. We just allow multiple enumerations of the same sequence to yield different results (or more generally, replicate side-effects). However, we can provide a bit more syntactical convenience in writing queries that reuse the same common subexpression in multiple places. In the above, we had to introduce an intermediate variable to store the common expression in, ready for reuse further on:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;pre class="code"&gt;&lt;span style="color:blue;"&gt;var &lt;/span&gt;xrs = &lt;span style="color:#2b91af;"&gt;EnumerableEx&lt;/span&gt;.Generate(&lt;span style="color:blue;"&gt;new &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;Random&lt;/span&gt;(), rnd =&amp;gt; &lt;span style="color:#2b91af;"&gt;EnumerableEx&lt;/span&gt;.Return(rnd.Next(100)), &lt;span style="color:green;"&gt;/* iterate */ &lt;/span&gt;_ =&amp;gt; _);
xrs.Zip(xrs, (l, r) =&amp;gt; l + r).Take(10).Run(&lt;span style="color:#2b91af;"&gt;Console&lt;/span&gt;.WriteLine);&lt;/pre&gt;
&lt;/blockquote&gt;

&lt;p&gt;&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;Can’t we somehow write this more fluently? The answer is yes, using the Let operator which passes its left-hand side to a lambda expression that can potentially use it multiple times:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;pre class="code"&gt;&lt;span style="color:#2b91af;"&gt;EnumerableEx&lt;/span&gt;.Generate(&lt;span style="color:blue;"&gt;new &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;Random&lt;/span&gt;(), rnd =&amp;gt; &lt;span style="color:#2b91af;"&gt;EnumerableEx&lt;/span&gt;.Return(rnd.Next(100)), &lt;span style="color:green;"&gt;/* iterate */ &lt;/span&gt;_ =&amp;gt; _)
    .Let(xrs =&amp;gt; xrs.Zip(xrs, (l, r) =&amp;gt; l + r)).Take(10).Run(&lt;span style="color:#2b91af;"&gt;Console&lt;/span&gt;.WriteLine);&lt;/pre&gt;
&lt;/blockquote&gt;

&lt;p&gt;&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;You can guess the signature of Let just by looking at the use above, but &lt;em&gt;let&lt;/em&gt;’s include it for completeness:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;pre class="code"&gt;&lt;span style="color:blue;"&gt;public static &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;IEnumerable&lt;/span&gt;&amp;lt;TResult&amp;gt; Let&amp;lt;TSource, TResult&amp;gt;(&lt;span style="color:blue;"&gt;this &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;IEnumerable&lt;/span&gt;&amp;lt;TSource&amp;gt; source, &lt;span style="color:#2b91af;"&gt;Func&lt;/span&gt;&amp;lt;&lt;span style="color:#2b91af;"&gt;IEnumerable&lt;/span&gt;&amp;lt;TSource&amp;gt;, &lt;span style="color:#2b91af;"&gt;IEnumerable&lt;/span&gt;&amp;lt;TResult&amp;gt;&amp;gt; function);&lt;/pre&gt;
  &lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;&lt;/blockquote&gt;

&lt;p&gt;Because of the call-by-value nature of the languages we’re talking about, the expression used for the source parameter will be fully evaluated (not the same as enumerated!) before Let gets called, so we can feed it (again in a call-by-value manner) to the function which then can refer to it multiple times by means of its lambda expression parameter (in the sample above this is “xrs”). Let comes from the world of functional languages where it takes the following form:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;let x = y in z&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;means (in C#-ish syntax)&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;(x =&amp;gt; z)(y)&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;In other words, there’s a hidden function x =&amp;gt; z sitting in a let-expression and the “value” for x (which is y in the sample) gets passed to it, providing the result for the entire let-expression. In EnumerableEx.Let, the function is clear as the second parameter, and the role of “y” is fulfilled by the source parameter. One could create a Let-form for any object as follows (not recommended because of the unrestricted extension method):&lt;/p&gt;

&lt;blockquote&gt;
  &lt;pre class="code"&gt;&lt;span style="color:blue;"&gt;public static &lt;/span&gt;R Let&amp;lt;T, R&amp;gt;(&lt;span style="color:blue;"&gt;this &lt;/span&gt;T t, &lt;span style="color:#2b91af;"&gt;Func&lt;/span&gt;&amp;lt;T, R&amp;gt; f)
{
    &lt;span style="color:blue;"&gt;return &lt;/span&gt;f(t);
}&lt;/pre&gt;
&lt;/blockquote&gt;

&lt;p&gt;&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;With this, you can write things like this:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;pre class="code"&gt;&lt;span style="color:#2b91af;"&gt;Console&lt;/span&gt;.WriteLine(&lt;span style="color:#2b91af;"&gt;DateTime&lt;/span&gt;.Now.Let(x =&amp;gt; x - x).Ticks);&lt;/pre&gt;
&lt;/blockquote&gt;

&lt;p&gt;This will print 0 ticks for sure, since the same DateTime.Now is used for x on both sides of the subtraction. If we were to expand this expression by substituting DateTime.Now for x, we’d get something different due to the duplicate evaluation of DateTime.Now, exposing the side-effect of reading from the system clock:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;pre class="code"&gt;&lt;span style="color:#2b91af;"&gt;Console&lt;/span&gt;.WriteLine((&lt;span style="color:#2b91af;"&gt;DateTime&lt;/span&gt;.Now - &lt;span style="color:#2b91af;"&gt;DateTime&lt;/span&gt;.Now).Ticks);&lt;/pre&gt;
  &lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;&lt;/blockquote&gt;

&lt;p&gt;(Pop quiz: What sign will the above Ticks result have? Is it possible for the above to return 0 sometimes?)&lt;/p&gt;

&lt;p&gt;&amp;#160;&lt;/p&gt;

&lt;h1&gt;Option 2: Cache on demand a.k.a. MemoizeAll&lt;/h1&gt;

&lt;p&gt;As we’ve seen before, on way to get rid of the side-effect replication is by forcing eager evaluation of the sequence through operators like ToArray or ToList. However, those are a bit too eager in various ways:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;They &lt;em&gt;persist &lt;/em&gt;the whole sequence, which won’t work for infinite sequences.&lt;/li&gt;

  &lt;li&gt;They do so &lt;em&gt;on the spot&lt;/em&gt;, i.e. the eagerness can’t be delayed till a later point (‘on demand”).&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;The last problem can be worked around using the Defer operator, but the first one is still a problem requiring another operator. Both those things are what MemoizeAll provides for, essentially persisting the sequence bit-by-bit upon consumption. This is achieved by exposing the enumerable while only maintaining a single enumerator to its source:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;&lt;a href="http://bartdesmet.net/images_wlw/Mor.InteractiveFunctionalfunandtamingsid_9DCC/image_3.png"&gt;&lt;img style="border-bottom:0px;border-left:0px;display:inline;border-top:0px;border-right:0px;" title="image" border="0" alt="image" src="http://bartdesmet.net/images_wlw/Mor.InteractiveFunctionalfunandtamingsid_9DCC/image_thumb_3.png" width="640" height="456" /&gt;&lt;/a&gt; &lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;In the figure above, this is illustrated. Red indicates a fetch operation where the original source’s iterator makes progress as an element is requested that hasn’t been fetched before. Green indicates persisted (cached, memoized) objects. Gray indicates elements in the source that have been fetched and hence belong to the past from the (single) source-iterators point of view: MemoizeAll won’t ever request those again. Applying this operator to our running sample using Zip will produce results with the expected invariant:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;pre class="code"&gt;&lt;span style="color:blue;"&gt;var &lt;/span&gt;xrs = &lt;span style="color:#2b91af;"&gt;EnumerableEx&lt;/span&gt;.Generate(&lt;span style="color:blue;"&gt;new &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;Random&lt;/span&gt;(), rnd =&amp;gt; &lt;span style="color:#2b91af;"&gt;EnumerableEx&lt;/span&gt;.Return(rnd.Next(100)), &lt;span style="color:green;"&gt;/* iterate */ &lt;/span&gt;_ =&amp;gt; _)
    .Do(xr =&amp;gt; &lt;span style="color:#2b91af;"&gt;Console&lt;/span&gt;.WriteLine(&lt;span style="color:#a31515;"&gt;&amp;quot;! -&amp;gt; &amp;quot; &lt;/span&gt;+ xr))
    .MemoizeAll();
xrs.Do(xr =&amp;gt; &lt;span style="color:#2b91af;"&gt;Console&lt;/span&gt;.WriteLine(&lt;span style="color:#a31515;"&gt;&amp;quot;L -&amp;gt; &amp;quot; &lt;/span&gt;+ xr)).Zip(
    xrs.Do(xr =&amp;gt; &lt;span style="color:#2b91af;"&gt;Console&lt;/span&gt;.WriteLine(&lt;span style="color:#a31515;"&gt;&amp;quot;R -&amp;gt; &amp;quot; &lt;/span&gt;+ xr)),
    (l, r) =&amp;gt; l + r).Take(10).Run(&lt;span style="color:#2b91af;"&gt;Console&lt;/span&gt;.WriteLine);&lt;/pre&gt;
  &lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;&lt;/blockquote&gt;

&lt;p&gt;Now we’ll see the xrs-triggered Do messages being printed only 10 times since the same element will be consumed by the two uses of xrs within Zip. The result looks as follows, showing how the right consumer of Zip never causes a fetch back to the random number generating source due to the internal caching by MemoizeAll:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;! -&amp;gt; 71
    &lt;br /&gt;L -&amp;gt; 71

    &lt;br /&gt;R -&amp;gt; 71

    &lt;br /&gt;142

    &lt;br /&gt;! -&amp;gt; 18

    &lt;br /&gt;L -&amp;gt; 18

    &lt;br /&gt;R -&amp;gt; 18

    &lt;br /&gt;36

    &lt;br /&gt;! -&amp;gt; 12

    &lt;br /&gt;L -&amp;gt; 12

    &lt;br /&gt;R -&amp;gt; 12

    &lt;br /&gt;24

    &lt;br /&gt;! -&amp;gt; 96

    &lt;br /&gt;L -&amp;gt; 96

    &lt;br /&gt;R -&amp;gt; 96

    &lt;br /&gt;192

    &lt;br /&gt;! -&amp;gt; 1

    &lt;br /&gt;L -&amp;gt; 1

    &lt;br /&gt;R -&amp;gt; 1

    &lt;br /&gt;2

    &lt;br /&gt;! -&amp;gt; 54

    &lt;br /&gt;L -&amp;gt; 54

    &lt;br /&gt;R -&amp;gt; 54

    &lt;br /&gt;108

    &lt;br /&gt;! -&amp;gt; 9

    &lt;br /&gt;L -&amp;gt; 9

    &lt;br /&gt;R -&amp;gt; 9

    &lt;br /&gt;18

    &lt;br /&gt;! -&amp;gt; 87

    &lt;br /&gt;L -&amp;gt; 87

    &lt;br /&gt;R -&amp;gt; 87

    &lt;br /&gt;174

    &lt;br /&gt;! -&amp;gt; 18

    &lt;br /&gt;L -&amp;gt; 18

    &lt;br /&gt;R -&amp;gt; 18

    &lt;br /&gt;36

    &lt;br /&gt;! -&amp;gt; 12

    &lt;br /&gt;L -&amp;gt; 12

    &lt;br /&gt;R -&amp;gt; 12

    &lt;br /&gt;24&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;What about lifetime of the source’s single enumerator? As soon as one of the consumers reaches the end of the underlying sequence, we got all elements cached and are prepared to any possible inquiry for elements on the output side of the MemoizeAll operator, hence it’s possible to dispose of the original enumerator. It should also be noted that memoization operators use materialization internally to capture the behavior of the sequence to expose to all consumers. This means exceptions are captured as Notification&amp;lt;T&amp;gt; so they’re repeatable to all consumers:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;pre class="code"&gt;&lt;span style="color:blue;"&gt;var &lt;/span&gt;xes = &lt;span style="color:#2b91af;"&gt;EnumerableEx&lt;/span&gt;.Throw&amp;lt;&lt;span style="color:blue;"&gt;int&lt;/span&gt;&amp;gt;(&lt;span style="color:blue;"&gt;new &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;Exception&lt;/span&gt;()).StartWith(1).MemoizeAll();
xes.Catch((&lt;span style="color:#2b91af;"&gt;Exception &lt;/span&gt;_) =&amp;gt; &lt;span style="color:#2b91af;"&gt;EnumerableEx&lt;/span&gt;.Return(42)).Run(&lt;span style="color:#2b91af;"&gt;Console&lt;/span&gt;.WriteLine);
xes.Catch((&lt;span style="color:#2b91af;"&gt;Exception &lt;/span&gt;_) =&amp;gt; &lt;span style="color:#2b91af;"&gt;EnumerableEx&lt;/span&gt;.Return(42)).Run(&lt;span style="color:#2b91af;"&gt;Console&lt;/span&gt;.WriteLine);&lt;/pre&gt;
&lt;/blockquote&gt;

&lt;p&gt;&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;The above will therefore print 1, 42 twice. In other words, the source blowing up during fetching by MemoizeAll doesn’t terminate other consumers that haven’t reached the faulty state yet (but if they iterate long enough, they’ll eventually see it exactly as the original consumer did).&lt;/p&gt;

&lt;p&gt;Finally, what’s All about MemoizeAll? In short: the cache used by the operator can grow infinitely large. The difference compared to ToArray and ToList has been explained before, but it’s worth repeating it: MemoizeAll doesn’t fetch its source’s results on the spot but only makes progress through the source’s enumerator when one of the consumers requests an element that hasn’t been retrieved yet. Call it a piecemeal ToList if you want.&lt;/p&gt;

&lt;p&gt;&amp;#160;&lt;/p&gt;

&lt;h1&gt;Option 3: Memoize, but less “conservative”&lt;/h1&gt;

&lt;p&gt;While MemoizeAll does the trick to avoid repetition of side-effects, it’s quite conservative in its caching as it never throws away elements it has retrieved. You never know whether someone – like a slow enumerator or a whole new enumerator over the memoized result – will request the data again, so a general-purpose Memoize can’t throw away a thing. However, if you know the behavior of the consumers of the memoized source, you can be more efficient about it and use Memoize specifying a buffer size. In our running sample of Zip we know that both uses of the source for the left and right inputs to Zip will be enumerated at the same pace, so it suffices to keep the last element in the cache in order for the right enumerator to be able to see the element the left enumerator just saw. Memoize with buffer size 1 does exactly that:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;pre class="code"&gt;&lt;span style="color:blue;"&gt;var &lt;/span&gt;xrs = &lt;span style="color:#2b91af;"&gt;EnumerableEx&lt;/span&gt;.Generate(&lt;span style="color:blue;"&gt;new &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;Random&lt;/span&gt;(), rnd =&amp;gt; &lt;span style="color:#2b91af;"&gt;EnumerableEx&lt;/span&gt;.Return(rnd.Next(100)), &lt;span style="color:green;"&gt;/* iterate */ &lt;/span&gt;_ =&amp;gt; _)
    .Do(xr =&amp;gt; &lt;span style="color:#2b91af;"&gt;Console&lt;/span&gt;.WriteLine(&lt;span style="color:#a31515;"&gt;&amp;quot;! -&amp;gt; &amp;quot; &lt;/span&gt;+ xr))
    .Memoize(1);
xrs.Do(xr =&amp;gt; &lt;span style="color:#2b91af;"&gt;Console&lt;/span&gt;.WriteLine(&lt;span style="color:#a31515;"&gt;&amp;quot;L -&amp;gt; &amp;quot; &lt;/span&gt;+ xr)).Zip(
    xrs.Do(xr =&amp;gt; &lt;span style="color:#2b91af;"&gt;Console&lt;/span&gt;.WriteLine(&lt;span style="color:#a31515;"&gt;&amp;quot;R -&amp;gt; &amp;quot; &lt;/span&gt;+ xr)),
    (l, r) =&amp;gt; l + r).Take(10).Run(&lt;span style="color:#2b91af;"&gt;Console&lt;/span&gt;.WriteLine);&lt;/pre&gt;
  &lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;&lt;/blockquote&gt;

&lt;p&gt;In pictures, this looks as follows:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;&lt;a href="http://bartdesmet.net/images_wlw/Mor.InteractiveFunctionalfunandtamingsid_9DCC/image_4.png"&gt;&lt;img style="border-bottom:0px;border-left:0px;display:inline;border-top:0px;border-right:0px;" title="image" border="0" alt="image" src="http://bartdesmet.net/images_wlw/Mor.InteractiveFunctionalfunandtamingsid_9DCC/image_thumb_4.png" width="640" height="456" /&gt;&lt;/a&gt; &lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;Another valid buffer size – also the default – is zero. It’s left to the reader, as an exercise, to come up with a plausible theory for what that one’s behavior should be and to depict this case graphically.&lt;/p&gt;

&lt;p&gt;(Question: Would it be possible to provide a “smart” memoization operator that knows exactly when it can abandon items in the front of its cache? Why (not)?)&lt;/p&gt;

&lt;p&gt;&amp;#160;&lt;/p&gt;

&lt;h1&gt;Derived forms&lt;/h1&gt;

&lt;p&gt;The difference between Let and the Memoize operators is that the former feeds in a view on an IEnumerable&amp;lt;T&amp;gt; source to a function, allowing that one to refer to the source multiple times in the act of producing a source in return. Let is, as we saw, nothing but fancy function application in a “fluent” left-to-right dataflowy way. Derived forms of Memoize exist that have the same form where a function is fed a memoized data source:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;Replay is Memoize on steroids&lt;/li&gt;

  &lt;li&gt;Publish is MemoizeAll on steroids&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;The following snippets show just what those operators do (modulo parameter checks):&lt;/p&gt;

&lt;blockquote&gt;
  &lt;pre class="code"&gt;&lt;span style="color:blue;"&gt;public static &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;IEnumerable&lt;/span&gt;&amp;lt;TResult&amp;gt; Publish&amp;lt;TSource, TResult&amp;gt;(&lt;span style="color:blue;"&gt;this &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;IEnumerable&lt;/span&gt;&amp;lt;TSource&amp;gt; source,&lt;br /&gt;                                                             Func&amp;lt;&lt;span style="color:#2b91af;"&gt;IEnumerable&lt;/span&gt;&amp;lt;TSource&amp;gt;, &lt;span style="color:#2b91af;"&gt;IEnumerable&lt;/span&gt;&amp;lt;TResult&amp;gt;&amp;gt; function)
{
    &lt;span style="color:blue;"&gt;return &lt;/span&gt;function(source.MemoizeAll());
}

&lt;span style="color:blue;"&gt;public static &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;IEnumerable&lt;/span&gt;&amp;lt;TResult&amp;gt; Publish&amp;lt;TSource, TResult&amp;gt;(&lt;span style="color:blue;"&gt;this &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;IEnumerable&lt;/span&gt;&amp;lt;TSource&amp;gt; source,&lt;br /&gt;                                                             Func&amp;lt;&lt;span style="color:#2b91af;"&gt;IEnumerable&lt;/span&gt;&amp;lt;TSource&amp;gt;, &lt;span style="color:#2b91af;"&gt;IEnumerable&lt;/span&gt;&amp;lt;TResult&amp;gt;&amp;gt; function,&lt;br /&gt;                                                             TSource initialValue)
{
    &lt;span style="color:blue;"&gt;return &lt;/span&gt;function(source.MemoizeAll().StartWith(initialValue));
}

&lt;span style="color:blue;"&gt;public static &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;IEnumerable&lt;/span&gt;&amp;lt;TResult&amp;gt; Replay&amp;lt;TSource, TResult&amp;gt;(&lt;span style="color:blue;"&gt;this &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;IEnumerable&lt;/span&gt;&amp;lt;TSource&amp;gt; source,&lt;br /&gt;                                                            Func&amp;lt;&lt;span style="color:#2b91af;"&gt;IEnumerable&lt;/span&gt;&amp;lt;TSource&amp;gt;, &lt;span style="color:#2b91af;"&gt;IEnumerable&lt;/span&gt;&amp;lt;TResult&amp;gt;&amp;gt; function)
{
    &lt;span style="color:blue;"&gt;return &lt;/span&gt;function(source.Memoize());
}

&lt;span style="color:blue;"&gt;public static &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;IEnumerable&lt;/span&gt;&amp;lt;TResult&amp;gt; Replay&amp;lt;TSource, TResult&amp;gt;(&lt;span style="color:blue;"&gt;this &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;IEnumerable&lt;/span&gt;&amp;lt;TSource&amp;gt; source,&lt;br /&gt;                                                            Func&amp;lt;&lt;span style="color:#2b91af;"&gt;IEnumerable&lt;/span&gt;&amp;lt;TSource&amp;gt;, &lt;span style="color:#2b91af;"&gt;IEnumerable&lt;/span&gt;&amp;lt;TResult&amp;gt;&amp;gt; function,&lt;br /&gt;                                                            &lt;span style="color:blue;"&gt;int &lt;/span&gt;bufferSize)
{
    &lt;span style="color:blue;"&gt;return &lt;/span&gt;function(source.Memoize(bufferSize));
}&lt;/pre&gt;
  &lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;&lt;/blockquote&gt;

&lt;p&gt;So we could rewrite our Zip sample in a variety of ways, the following being the cleanest one-sized buffer variant:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;pre class="code"&gt;&lt;span style="color:#2b91af;"&gt;EnumerableEx&lt;/span&gt;.Generate(&lt;span style="color:blue;"&gt;new &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;Random&lt;/span&gt;(), rnd =&amp;gt; &lt;span style="color:#2b91af;"&gt;EnumerableEx&lt;/span&gt;.Return(rnd.Next(100)), &lt;span style="color:green;"&gt;/* iterate */ &lt;/span&gt;_ =&amp;gt; _)
    .Do(xr =&amp;gt; &lt;span style="color:#2b91af;"&gt;Console&lt;/span&gt;.WriteLine(&lt;span style="color:#a31515;"&gt;&amp;quot;! -&amp;gt; &amp;quot; &lt;/span&gt;+ xr))
    .Replay(&lt;font color="#ff0000"&gt;xrs&lt;/font&gt; =&amp;gt; &lt;font color="#ff0000"&gt;xrs&lt;/font&gt;.Do(xr =&amp;gt; &lt;span style="color:#2b91af;"&gt;Console&lt;/span&gt;.WriteLine(&lt;span style="color:#a31515;"&gt;&amp;quot;L -&amp;gt; &amp;quot; &lt;/span&gt;+ xr)).Zip(
                   &lt;font color="#ff0000"&gt;xrs&lt;/font&gt;.Do(xr =&amp;gt; &lt;span style="color:#2b91af;"&gt;Console&lt;/span&gt;.WriteLine(&lt;span style="color:#a31515;"&gt;&amp;quot;R -&amp;gt; &amp;quot; &lt;/span&gt;+ xr)),
                   (l, r) =&amp;gt; l + r),
            1)
    .Take(10).Run(&lt;span style="color:#2b91af;"&gt;Console&lt;/span&gt;.WriteLine);&lt;/pre&gt;
  &lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;&lt;/blockquote&gt;

&lt;p&gt;&amp;#160;&lt;/p&gt;

&lt;h1&gt;Option 4: Fair (?) sharing with Share and Prune&lt;/h1&gt;

&lt;p&gt;The Share operator shares an IEnumerator&amp;lt;T&amp;gt; for any number of consumers of an IEnumerable&amp;lt;T&amp;gt;, hence avoiding duplication of side-effects. In addition, it also guarantees that no two consumers can see the same element, so in effect the Share operator has the potential of distributing elements across different consumers. Looking at it from another angle, one consumer can steal elements from the source, preventing another consumer from seeing it. Prune is derived from Share as follows:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;pre class="code"&gt;&lt;span style="color:blue;"&gt;public static &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;IEnumerable&lt;/span&gt;&amp;lt;TResult&amp;gt; Prune&amp;lt;TSource, TResult&amp;gt;(&lt;span style="color:blue;"&gt;this &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;IEnumerable&lt;/span&gt;&amp;lt;TSource&amp;gt; source,&lt;br /&gt;                                                           Func&amp;lt;&lt;span style="color:#2b91af;"&gt;IEnumerable&lt;/span&gt;&amp;lt;TSource&amp;gt;, &lt;span style="color:#2b91af;"&gt;IEnumerable&lt;/span&gt;&amp;lt;TResult&amp;gt;&amp;gt; function)
{
    &lt;span style="color:blue;"&gt;return &lt;/span&gt;function(source.Share());
}&lt;/pre&gt;
  &lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;&lt;/blockquote&gt;

&lt;p&gt;The naming for Prune follows from the effect consumers inside the function have on the sequence being shared: each one consuming data effectively prunes elements from the head of the sequence, so that others cannot see those anymore. An example is shown below, showing another way a Zip could go &lt;em&gt;wrong&lt;/em&gt; (practical scenarios for this operator would involve sharing) since the left and right consumers both advance the cursor of the same shared enumerator under the hood:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;pre class="code"&gt;&lt;span style="color:#2b91af;"&gt;EnumerableEx&lt;/span&gt;.Generate(&lt;span style="color:blue;"&gt;new &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;Random&lt;/span&gt;(), rnd =&amp;gt; &lt;span style="color:#2b91af;"&gt;EnumerableEx&lt;/span&gt;.Return(rnd.Next(100)), &lt;span style="color:green;"&gt;/* iterate */ &lt;/span&gt;_ =&amp;gt; _)
    .Do(xr =&amp;gt; &lt;span style="color:#2b91af;"&gt;Console&lt;/span&gt;.WriteLine(&lt;span style="color:#a31515;"&gt;&amp;quot;! -&amp;gt; &amp;quot; &lt;/span&gt;+ xr))
    .Prune(xrs =&amp;gt; xrs.Do(xr =&amp;gt; &lt;span style="color:#2b91af;"&gt;Console&lt;/span&gt;.WriteLine(&lt;span style="color:#a31515;"&gt;&amp;quot;L -&amp;gt; &amp;quot; &lt;/span&gt;+ xr)).Zip(
                   xrs.Do(xr =&amp;gt; &lt;span style="color:#2b91af;"&gt;Console&lt;/span&gt;.WriteLine(&lt;span style="color:#a31515;"&gt;&amp;quot;R -&amp;gt; &amp;quot; &lt;/span&gt;+ xr)),
                   (l, r) =&amp;gt; l + r))
    .Take(10).Run(&lt;span style="color:#2b91af;"&gt;Console&lt;/span&gt;.WriteLine);&lt;/pre&gt;
&lt;/blockquote&gt;

&lt;p&gt;&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;The result of this is of interest since the logging will reveal the sharing characteristic. Looking at the first Do’s output we’ll see it gets triggered by any consumer on the inside of Prune:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;! -&amp;gt; 37
    &lt;br /&gt;L -&amp;gt; 37

    &lt;br /&gt;! -&amp;gt; 51

    &lt;br /&gt;R -&amp;gt; 51

    &lt;br /&gt;88

    &lt;br /&gt;! -&amp;gt; 98

    &lt;br /&gt;L -&amp;gt; 98

    &lt;br /&gt;! -&amp;gt; 89

    &lt;br /&gt;R -&amp;gt; 89

    &lt;br /&gt;187

    &lt;br /&gt;! -&amp;gt; 4

    &lt;br /&gt;L -&amp;gt; 4

    &lt;br /&gt;! -&amp;gt; 71

    &lt;br /&gt;R -&amp;gt; 71

    &lt;br /&gt;75

    &lt;br /&gt;! -&amp;gt; 43

    &lt;br /&gt;L -&amp;gt; 43

    &lt;br /&gt;! -&amp;gt; 30

    &lt;br /&gt;R -&amp;gt; 30

    &lt;br /&gt;73

    &lt;br /&gt;! -&amp;gt; 18

    &lt;br /&gt;L -&amp;gt; 18

    &lt;br /&gt;! -&amp;gt; 24

    &lt;br /&gt;R -&amp;gt; 24

    &lt;br /&gt;42

    &lt;br /&gt;! -&amp;gt; 17

    &lt;br /&gt;L -&amp;gt; 17

    &lt;br /&gt;! -&amp;gt; 41

    &lt;br /&gt;R -&amp;gt; 41

    &lt;br /&gt;58

    &lt;br /&gt;! -&amp;gt; 45

    &lt;br /&gt;L -&amp;gt; 45

    &lt;br /&gt;! -&amp;gt; 68

    &lt;br /&gt;R -&amp;gt; 68

    &lt;br /&gt;113

    &lt;br /&gt;! -&amp;gt; 83

    &lt;br /&gt;L -&amp;gt; 83

    &lt;br /&gt;! -&amp;gt; 53

    &lt;br /&gt;R -&amp;gt; 53

    &lt;br /&gt;136

    &lt;br /&gt;! -&amp;gt; 64

    &lt;br /&gt;L -&amp;gt; 64

    &lt;br /&gt;! -&amp;gt; 69

    &lt;br /&gt;R -&amp;gt; 69

    &lt;br /&gt;133

    &lt;br /&gt;! -&amp;gt; 0

    &lt;br /&gt;L -&amp;gt; 0

    &lt;br /&gt;! -&amp;gt; 22

    &lt;br /&gt;R -&amp;gt; 22

    &lt;br /&gt;22&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;In pictures, this looks as follows:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;&lt;a href="http://bartdesmet.net/images_wlw/Mor.InteractiveFunctionalfunandtamingsid_9DCC/image_5.png"&gt;&lt;img style="border-bottom:0px;border-left:0px;display:inline;border-top:0px;border-right:0px;" title="image" border="0" alt="image" src="http://bartdesmet.net/images_wlw/Mor.InteractiveFunctionalfunandtamingsid_9DCC/image_thumb_5.png" width="640" height="456" /&gt;&lt;/a&gt; &lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;Exercise: Can you guess how Memoize(0) differs from Share?&lt;/p&gt;

&lt;p&gt;Quiz: What should be the behavior of the following fragment? (Tip: you got to know what two from clauses result in and how they execute)&lt;/p&gt;

&lt;blockquote&gt;
  &lt;pre class="code"&gt;&lt;span style="color:#2b91af;"&gt;Enumerable&lt;/span&gt;.Range(0, 10)&lt;font color="#008000"&gt;&lt;br /&gt;&lt;/font&gt;&lt;span style="color:green;"&gt;    &lt;/span&gt;.Prune(xs =&amp;gt; &lt;span style="color:blue;"&gt;from &lt;/span&gt;x &lt;span style="color:blue;"&gt;in &lt;/span&gt;xs.Zip(xs, (l, r) =&amp;gt; l + r)
                 &lt;span style="color:blue;"&gt;from &lt;/span&gt;y &lt;span style="color:blue;"&gt;in &lt;/span&gt;xs
                 &lt;span style="color:blue;"&gt;select &lt;/span&gt;x + y)
    .Run(&lt;span style="color:#2b91af;"&gt;Console&lt;/span&gt;.WriteLine);&lt;/pre&gt;
  &lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;&lt;/blockquote&gt;

&lt;p&gt;&amp;#160;&lt;/p&gt;

&lt;h1&gt;Next on More LINQ&lt;/h1&gt;

&lt;p&gt;A look at the Asynchronous and Remotable operators, dealing with some infrastructure-related concepts, wrapping up this series for now.&lt;/p&gt;&lt;img src="http://blogs.bartdesmet.net/aggbug.aspx?PostID=15025" width="1" height="1"&gt;</description><category domain="http://blogs.bartdesmet.net/blogs/bart/archive/tags/LINQ/default.aspx">LINQ</category><category domain="http://blogs.bartdesmet.net/blogs/bart/archive/tags/Rx/default.aspx">Rx</category></item><item><title>The Essence of LINQ – MinLINQ</title><link>http://blogs.bartdesmet.net/blogs/bart/archive/2010/01/01/the-essence-of-linq-minlinq.aspx</link><pubDate>Fri, 01 Jan 2010 13:46:59 GMT</pubDate><guid isPermaLink="false">863c5522-913f-4a64-ac0a-bd5f05abad0f:14981</guid><dc:creator>bart</dc:creator><slash:comments>19</slash:comments><wfw:commentRss xmlns:wfw="http://wellformedweb.org/CommentAPI/">http://blogs.bartdesmet.net/blogs/bart/rsscomments.aspx?PostID=14981</wfw:commentRss><comments>http://blogs.bartdesmet.net/blogs/bart/archive/2010/01/01/the-essence-of-linq-minlinq.aspx#comments</comments><description>&lt;h1&gt;Introduction&lt;/h1&gt;  &lt;p&gt;Before reaching the catharsis in the &lt;a href="http://blogs.bartdesmet.net/blogs/bart/archive/tags/Rx/default.aspx"&gt;“More LINQ with System.Interactive” series&lt;/a&gt; over here, I wanted to ensure a solid understanding of the essence of LINQ in my reader base. Often people forget the true essence of a technology due to the large number of auxiliary frameworks and extensions that are being provided. Or worse, sometimes a sense for the essence never materialized.&lt;/p&gt;  &lt;p&gt;Searching for essence is nothing other than a “group by” operation, partitioning the world in fundamentals and derived portions. One succeeds in this mission if the former group is much smaller than the latter. In this post, we’ll try to reach that point for the IEnumerable&amp;lt;T&amp;gt; and IObservable&amp;lt;T&amp;gt; LINQ implementations, illustrating both are fundamentally similar (and dare I say, dual?). You can already guess much of the essence lies in the concept of &lt;strong&gt;monads&lt;/strong&gt;. By the end of the post, we’ll have distilled the core of LINQ, which I refer to as MinLINQ since &lt;a href="http://en.wikipedia.org/wiki/MinWin"&gt;small is beautiful&lt;/a&gt;.&lt;/p&gt;  &lt;p&gt;&amp;#160;&lt;/p&gt;  &lt;h1&gt;Interfaces are overrated?&lt;/h1&gt;  &lt;p&gt;While loved by object-oriented practitioners, interfaces are essentially nothing but &lt;em&gt;records of functions&lt;/em&gt;. And functions, as we all know, are the fundamental pillars of functional programming languages. This trivial observation is illustrated below. I’ll leave it to the reader to think about various implications of the use of a (covariant) IRecord representation for objects:&lt;/p&gt;  &lt;blockquote&gt;   &lt;pre class="code"&gt;&lt;span style="color:blue;"&gt;class &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;Program
&lt;/span&gt;{
    &lt;span style="color:blue;"&gt;static void &lt;/span&gt;Main()
    {
        &lt;span style="color:blue;"&gt;for &lt;/span&gt;(&lt;span style="color:blue;"&gt;var &lt;/span&gt;c = &lt;span style="color:blue;"&gt;new &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;Counter&lt;/span&gt;(); c.Get() &amp;lt; &lt;span style="color:brown;"&gt;10&lt;/span&gt;; c.Inc(&lt;span style="color:brown;"&gt;1&lt;/span&gt;))
            &lt;span style="color:#2b91af;"&gt;Console&lt;/span&gt;.WriteLine(c.Get());
    }
}

&lt;span style="color:blue;"&gt;interface &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;IRecord&lt;/span&gt;&amp;lt;&lt;span style="color:blue;"&gt;out &lt;/span&gt;T1, &lt;span style="color:blue;"&gt;out &lt;/span&gt;T2&amp;gt;
{
    T1 First { &lt;span style="color:blue;"&gt;get&lt;/span&gt;; }
    T2 Second { &lt;span style="color:blue;"&gt;get&lt;/span&gt;; }
}

&lt;span style="color:blue;"&gt;class &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;Counter &lt;/span&gt;: &lt;span style="color:#2b91af;"&gt;IRecord&lt;/span&gt;&amp;lt;&lt;span style="color:#2b91af;"&gt;Func&lt;/span&gt;&amp;lt;&lt;span style="color:blue;"&gt;int&lt;/span&gt;&amp;gt;, &lt;span style="color:#2b91af;"&gt;Action&lt;/span&gt;&amp;lt;&lt;span style="color:blue;"&gt;int&lt;/span&gt;&amp;gt;&amp;gt;
{
    &lt;span style="color:green;"&gt;// Data
    &lt;/span&gt;&lt;span style="color:blue;"&gt;private int &lt;/span&gt;_value;

    &lt;span style="color:green;"&gt;// Code - explicit implementation to hide First, Second
    &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;Func&lt;/span&gt;&amp;lt;&lt;span style="color:blue;"&gt;int&lt;/span&gt;&amp;gt; &lt;span style="color:#2b91af;"&gt;IRecord&lt;/span&gt;&amp;lt;&lt;span style="color:#2b91af;"&gt;Func&lt;/span&gt;&amp;lt;&lt;span style="color:blue;"&gt;int&lt;/span&gt;&amp;gt;, &lt;span style="color:#2b91af;"&gt;Action&lt;/span&gt;&amp;lt;&lt;span style="color:blue;"&gt;int&lt;/span&gt;&amp;gt;&amp;gt;.First { &lt;span style="color:blue;"&gt;get &lt;/span&gt;{ &lt;span style="color:blue;"&gt;return &lt;/span&gt;() =&amp;gt; _value; } }
    &lt;span style="color:#2b91af;"&gt;Action&lt;/span&gt;&amp;lt;&lt;span style="color:blue;"&gt;int&lt;/span&gt;&amp;gt; &lt;span style="color:#2b91af;"&gt;IRecord&lt;/span&gt;&amp;lt;&lt;span style="color:#2b91af;"&gt;Func&lt;/span&gt;&amp;lt;&lt;span style="color:blue;"&gt;int&lt;/span&gt;&amp;gt;, &lt;span style="color:#2b91af;"&gt;Action&lt;/span&gt;&amp;lt;&lt;span style="color:blue;"&gt;int&lt;/span&gt;&amp;gt;&amp;gt;.Second { &lt;span style="color:blue;"&gt;get &lt;/span&gt;{ &lt;span style="color:blue;"&gt;return &lt;/span&gt;i =&amp;gt; _value += i; } }

    &lt;span style="color:green;"&gt;// Code - friendly &amp;quot;interface&amp;quot;
    &lt;/span&gt;&lt;span style="color:blue;"&gt;public &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;Func&lt;/span&gt;&amp;lt;&lt;span style="color:blue;"&gt;int&lt;/span&gt;&amp;gt; Get { &lt;span style="color:blue;"&gt;get &lt;/span&gt;{ &lt;span style="color:blue;"&gt;return &lt;/span&gt;((&lt;span style="color:#2b91af;"&gt;IRecord&lt;/span&gt;&amp;lt;&lt;span style="color:#2b91af;"&gt;Func&lt;/span&gt;&amp;lt;&lt;span style="color:blue;"&gt;int&lt;/span&gt;&amp;gt;, &lt;span style="color:#2b91af;"&gt;Action&lt;/span&gt;&amp;lt;&lt;span style="color:blue;"&gt;int&lt;/span&gt;&amp;gt;&amp;gt;)&lt;span style="color:blue;"&gt;this&lt;/span&gt;).First; } }
    &lt;span style="color:blue;"&gt;public &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;Action&lt;/span&gt;&amp;lt;&lt;span style="color:blue;"&gt;int&lt;/span&gt;&amp;gt; Inc { &lt;span style="color:blue;"&gt;get &lt;/span&gt;{ &lt;span style="color:blue;"&gt;return &lt;/span&gt;((&lt;span style="color:#2b91af;"&gt;IRecord&lt;/span&gt;&amp;lt;&lt;span style="color:#2b91af;"&gt;Func&lt;/span&gt;&amp;lt;&lt;span style="color:blue;"&gt;int&lt;/span&gt;&amp;gt;, &lt;span style="color:#2b91af;"&gt;Action&lt;/span&gt;&amp;lt;&lt;span style="color:blue;"&gt;int&lt;/span&gt;&amp;gt;&amp;gt;)&lt;span style="color:blue;"&gt;this&lt;/span&gt;).Second; } }
}&lt;/pre&gt;
  &lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;&lt;/blockquote&gt;

&lt;p&gt;Why do we care? Well, it turns out that IEnumerable&amp;lt;T&amp;gt; and IObservable&amp;lt;T&amp;gt; tend to obscure the true meaning of the objects a bit by having many different methods to facilitate the task of enumeration and observation, respectively. The source of this apparent bloating is irrelevant (and in fact follows design guidelines of an object-oriented inspired framework); what matters more is to see how the two mentioned interfaces can be boiled down to their essence.&lt;/p&gt;

&lt;p&gt;Minimalistic as we are, we’re going to drop the notion of error cases that manifest themselves through MoveNext throwing an exception and OnError getting called, respectively on IEnumerator&amp;lt;T&amp;gt; and IObserver&amp;lt;T&amp;gt;. For similar reasons of simplification, we’ll also not concern ourselves with the disposal of enumerators or subscriptions. The resulting picture looks as follows:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;&lt;a href="http://bartdesmet.net/images_wlw/TheEssenceofLINQMinLINQ_13EBD/image.png"&gt;&lt;img style="border-right-width:0px;display:inline;border-top-width:0px;border-bottom-width:0px;border-left-width:0px;" title="image" border="0" alt="image" src="http://bartdesmet.net/images_wlw/TheEssenceofLINQMinLINQ_13EBD/image_thumb.png" width="640" height="343" /&gt;&lt;/a&gt; &lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;To consolidate things a bit further, we’ll collapse MoveNext/Current on the left, and OnNext/OnCompleted on the right. How so? Well, either getting or receiving the next element can provide a value or a termination signal. This is nothing but a pair of an optional value and a Boolean. Turns out we have such a thing in the framework, called Nullable&amp;lt;T&amp;gt; but since one can’t nest those guys or use them on reference types, it doesn’t help much. Instead, we’ll represent the presence or absence of a value using an Option&amp;lt;T&amp;gt; type:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;pre class="code"&gt;&lt;span style="color:blue;"&gt;public abstract class &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;Option&lt;/span&gt;&amp;lt;T&amp;gt;
{
    &lt;span style="color:blue;"&gt;public abstract bool &lt;/span&gt;HasValue { &lt;span style="color:blue;"&gt;get&lt;/span&gt;; }
    &lt;span style="color:blue;"&gt;public abstract &lt;/span&gt;T Value { &lt;span style="color:blue;"&gt;get&lt;/span&gt;; }

    &lt;span style="color:blue;"&gt;public sealed class &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;None &lt;/span&gt;: &lt;span style="color:#2b91af;"&gt;Option&lt;/span&gt;&amp;lt;T&amp;gt;
    {
        &lt;span style="color:blue;"&gt;public override bool &lt;/span&gt;HasValue
        {
            &lt;span style="color:blue;"&gt;get &lt;/span&gt;{ &lt;span style="color:blue;"&gt;return false&lt;/span&gt;; }
        }

        &lt;span style="color:blue;"&gt;public override &lt;/span&gt;T Value
        {
            &lt;span style="color:blue;"&gt;get &lt;/span&gt;{ &lt;span style="color:blue;"&gt;throw new &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;InvalidOperationException&lt;/span&gt;(); }
        }

        &lt;span style="color:blue;"&gt;public override string &lt;/span&gt;ToString()
        {
            &lt;span style="color:blue;"&gt;return &lt;/span&gt;&lt;span style="color:#a31515;"&gt;&amp;quot;None&amp;lt;&amp;quot; &lt;/span&gt;+ &lt;span style="color:blue;"&gt;typeof&lt;/span&gt;(T).Name + &lt;span style="color:#a31515;"&gt;&amp;quot;&amp;gt;()&amp;quot;&lt;/span&gt;;
        }
    }

    &lt;span style="color:blue;"&gt;public sealed class &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;Some &lt;/span&gt;: &lt;span style="color:#2b91af;"&gt;Option&lt;/span&gt;&amp;lt;T&amp;gt;
    {
        &lt;span style="color:blue;"&gt;private &lt;/span&gt;T _value;

        &lt;span style="color:blue;"&gt;public &lt;/span&gt;Some(T value)
        {
            _value = value;
        }

        &lt;span style="color:blue;"&gt;public override bool &lt;/span&gt;HasValue
        {
            &lt;span style="color:blue;"&gt;get &lt;/span&gt;{ &lt;span style="color:blue;"&gt;return true&lt;/span&gt;; }
        }

        &lt;span style="color:blue;"&gt;public override &lt;/span&gt;T Value
        {
            &lt;span style="color:blue;"&gt;get &lt;/span&gt;{ &lt;span style="color:blue;"&gt;return &lt;/span&gt;_value; }
        }

        &lt;span style="color:blue;"&gt;public override string &lt;/span&gt;ToString()
        {
            &lt;span style="color:blue;"&gt;return &lt;/span&gt;&lt;span style="color:#a31515;"&gt;&amp;quot;Some&amp;lt;&amp;quot; &lt;/span&gt;+ &lt;span style="color:blue;"&gt;typeof&lt;/span&gt;(T).Name + &lt;span style="color:#a31515;"&gt;&amp;quot;&amp;gt;(&amp;quot; &lt;/span&gt;+ (_value == &lt;span style="color:blue;"&gt;null &lt;/span&gt;? &lt;span style="color:#a31515;"&gt;&amp;quot;null&amp;quot; &lt;/span&gt;: _value.ToString()) + &lt;span style="color:#a31515;"&gt;&amp;quot;)&amp;quot;&lt;/span&gt;;
        }
    }
}&lt;/pre&gt;
  &lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;&lt;/blockquote&gt;

&lt;p&gt;The subtypes None and Some are optional though convenient, hence I’ll leave them in. With this, IEnumerator&amp;lt;T&amp;gt; would boil down to an interface with a single method retrieving an Option&amp;lt;T&amp;gt;. When it returns a Some object, there was a next element and we got it; when it returns None, we’ve reached the end of the enumeration. Similar for IObserver&amp;lt;T&amp;gt;, OnNext and OnCompleted are merged into a single method receiving an Option&amp;lt;T&amp;gt;. Interfaces with a single method have a name: they’re delegates. So both those types can be abbreviated to:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;pre class="code"&gt;&lt;span style="color:#2b91af;"&gt;IObserver&lt;/span&gt;&amp;lt;T&amp;gt;&amp;#160; –&amp;gt;  &lt;span style="color:#2b91af;"&gt;Action&lt;/span&gt;&amp;lt;&lt;span style="color:#2b91af;"&gt;Option&lt;/span&gt;&amp;lt;T&amp;gt;&amp;gt;
&lt;span style="color:#2b91af;"&gt;IEnumerator&lt;/span&gt;&amp;lt;T&amp;gt;&amp;#160; –&amp;gt;  &lt;span style="color:#2b91af;"&gt;Func&lt;/span&gt;&amp;lt;&lt;span style="color:#2b91af;"&gt;Option&lt;/span&gt;&amp;lt;T&amp;gt;&amp;gt;&lt;/pre&gt;
  &lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;&lt;/blockquote&gt;

&lt;p&gt;A quick recap: an observer is something you can give a value or tell it has reached the end of the observable object, hence it takes in an Option&amp;lt;T&amp;gt;; an enumerator is something you can get a value from but it can also signal the end of the enumerable object, hence it produces an Option&amp;lt;T&amp;gt;. In a more functional notation, one could write:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;Option&amp;lt;T&amp;gt; –&amp;gt; () 
    &lt;br /&gt;() –&amp;gt; Option&amp;lt;T&amp;gt;&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;Here the arrow indicates “goes to”, just as in lambda expressions, with the argument on the left and the return type on the right. All that has happened is reverting the arrows to go from an observer to an enumerator and vice versa. That’s the essence of &lt;strong&gt;dualization&lt;/strong&gt;.&lt;/p&gt;

&lt;p&gt;But we’re not done yet. Look one level up at the IEnumerable&amp;lt;T&amp;gt; and IObserver&amp;lt;T&amp;gt; interfaces. Those are single-method ones too, hence we can play the same trick as we did before. The IEnumerable&amp;lt;T&amp;gt; interface’s single method returns an IEnumerator&amp;lt;T&amp;gt;, which we already collapsed into a simple function above. And in a dual manner, IObservable&amp;lt;T&amp;gt;’s single method takes in an IObserver&amp;lt;T&amp;gt;, which we also collapsed above. The yields the following result:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;pre class="code"&gt;&lt;span style="color:#2b91af;"&gt;IObservable&lt;/span&gt;&amp;lt;T&amp;gt;  –&amp;gt;  &lt;span style="color:#2b91af;"&gt;Action&lt;/span&gt;&amp;lt;&lt;span style="color:#2b91af;"&gt;Action&lt;/span&gt;&amp;lt;&lt;span style="color:#2b91af;"&gt;Option&lt;/span&gt;&amp;lt;T&amp;gt;&amp;gt;&amp;gt;
&lt;span style="color:#2b91af;"&gt;IEnumerable&lt;/span&gt;&amp;lt;T&amp;gt;  –&amp;gt;  &lt;span style="color:#2b91af;"&gt;Func&lt;/span&gt;&amp;lt;&lt;span style="color:#2b91af;"&gt;Func&lt;/span&gt;&amp;lt;&lt;span style="color:#2b91af;"&gt;Option&lt;/span&gt;&amp;lt;T&amp;gt;&amp;gt;&amp;gt;&lt;/pre&gt;
  &lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;&lt;/blockquote&gt;

&lt;p&gt;If that isn’t a simplification, I don’t know what would be. An observable is nothing other than an action taking in an action taking in an observed value, while an enumerable is nothing other than a function returning a function returning a yielded value. Or, in concise functional notation:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;(Option&amp;lt;T&amp;gt; –&amp;gt; ()) –&amp;gt; () 
    &lt;br /&gt;() –&amp;gt; (() –&amp;gt; Option&amp;lt;T&amp;gt;)&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;Again, to go from one world to the other, it suffices to reverse the arrows to reach the dual form. In summary, have a look at the following figure:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;&lt;a href="http://bartdesmet.net/images_wlw/TheEssenceofLINQMinLINQ_13EBD/image_3.png"&gt;&lt;img style="border-right-width:0px;display:inline;border-top-width:0px;border-bottom-width:0px;border-left-width:0px;" title="image" border="0" alt="image" src="http://bartdesmet.net/images_wlw/TheEssenceofLINQMinLINQ_13EBD/image_thumb_3.png" width="660" height="500" /&gt;&lt;/a&gt;&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;&amp;#160;&lt;/p&gt;

&lt;h1&gt;Flat functions – FEnumerable and FObservable&lt;/h1&gt;

&lt;p&gt;Since we’ve flattened &lt;em&gt;imperative &lt;/em&gt;interfaces into &lt;em&gt;flat &lt;/em&gt;functions we’re going to provide several operators over those, we need to have a name for the type to stick those items in. Though we’re not going to make things purely functional on the inside (as we’ll rely on side-effects to implement various operators), I still like to call it function-style enumerable and observable, hence the names FEnumerable and FObservable (not meant to be pronounceable), where F stands for Function as opposed to I for Interface. In addition, Ex additions will materialize to realize some layering as discussed below. The result, including FEnumerableEx2 that’s left as an exercise, is shown below:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;&lt;a href="http://bartdesmet.net/images_wlw/TheEssenceofLINQMinLINQ_13EBD/image_4.png"&gt;&lt;img style="border-right-width:0px;display:inline;border-top-width:0px;border-bottom-width:0px;border-left-width:0px;" title="image" border="0" alt="image" src="http://bartdesmet.net/images_wlw/TheEssenceofLINQMinLINQ_13EBD/image_thumb_4.png" width="438" height="480" /&gt;&lt;/a&gt; &lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;&amp;#160;&lt;/p&gt;

&lt;h1&gt;Five essential operators, or maybe even less&lt;/h1&gt;

&lt;p&gt;To continue on our merry way towards the essence of LINQ, we’ll be providing five essential operators as the building blocks to construct most other operators out of. Needless to say so, those operators will use the above flat function “interfaces” to do their work on. Let’s start with a couple of easy ones: Empty and Return.&lt;/p&gt;

&lt;p&gt;&amp;#160;&lt;/p&gt;

&lt;h2&gt;Empty&lt;/h2&gt;

&lt;p&gt;The Empty operator is very straightforward and never deals with Option&amp;lt;T&amp;gt;.Some values, just signaling an Option&amp;lt;T&amp;gt;.None immediately to signal completion. Hence the produced collection is empty. How do we realize this operator in the enumerable and observable case? Not surprisingly, the implementation is straightforward in both cases:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;pre class="code"&gt;&lt;span style="color:blue;"&gt;public static class &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;FEnumerable
&lt;/span&gt;{
    &lt;span style="color:blue;"&gt;public static &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;Func&lt;/span&gt;&amp;lt;&lt;span style="color:#2b91af;"&gt;Func&lt;/span&gt;&amp;lt;&lt;span style="color:#2b91af;"&gt;Option&lt;/span&gt;&amp;lt;T&amp;gt;&amp;gt;&amp;gt; Empty&amp;lt;T&amp;gt;()
    {
        &lt;span style="color:blue;"&gt;return &lt;/span&gt;() =&amp;gt; () =&amp;gt; &lt;span style="color:blue;"&gt;new &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;Option&lt;/span&gt;&amp;lt;T&amp;gt;.&lt;span style="color:#2b91af;"&gt;None&lt;/span&gt;();
    }&lt;/pre&gt;
  &lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;&lt;/blockquote&gt;

&lt;p&gt;First, the FEnumerable one. All it does is simply returning a function that returns an end-of-sequence None signal in return to getting called. Notice the two levels of nesting needed to be conform with the signature. The outer function is the one retrieving the enumerator, while the inner is the equivalent to MoveNext and Current. For absolute clarity:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;&lt;a href="http://bartdesmet.net/images_wlw/TheEssenceofLINQMinLINQ_13EBD/image_5.png"&gt;&lt;img style="border-right-width:0px;display:inline;border-top-width:0px;border-bottom-width:0px;border-left-width:0px;" title="image" border="0" alt="image" src="http://bartdesmet.net/images_wlw/TheEssenceofLINQMinLINQ_13EBD/image_thumb_5.png" width="597" height="291" /&gt;&lt;/a&gt; &lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;One the FObservable side of things, we find a similar implementation shuffled around a little bit, as shown below:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;pre class="code"&gt;&lt;span style="color:blue;"&gt;public static class &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;FObservable
&lt;/span&gt;{
    &lt;span style="color:blue;"&gt;public static &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;Action&lt;/span&gt;&amp;lt;&lt;span style="color:#2b91af;"&gt;Action&lt;/span&gt;&amp;lt;&lt;span style="color:#2b91af;"&gt;Option&lt;/span&gt;&amp;lt;T&amp;gt;&amp;gt;&amp;gt; Empty&amp;lt;T&amp;gt;()
    {
        &lt;span style="color:blue;"&gt;return &lt;/span&gt;o =&amp;gt; o(&lt;span style="color:blue;"&gt;new &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;Option&lt;/span&gt;&amp;lt;T&amp;gt;.&lt;span style="color:#2b91af;"&gt;None&lt;/span&gt;());
    }&lt;/pre&gt;
&lt;/blockquote&gt;

&lt;p&gt;What used to be output now becomes input: the None constructor call no long appears in an output position but has moved to an input position. Similar for the observer, indicated with o, which has moved to an input position. Upon giving the observable object (the whole thing) an observer (o), the latter gets simply called with a None object indicating the end of the sequence. The inner call is equivalent to OnCompleted, while the whole lambda expression is equivalent to Subscribe.&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;&lt;a href="http://bartdesmet.net/images_wlw/TheEssenceofLINQMinLINQ_13EBD/image_6.png"&gt;&lt;img style="border-right-width:0px;display:inline;border-top-width:0px;border-bottom-width:0px;border-left-width:0px;" title="image" border="0" alt="image" src="http://bartdesmet.net/images_wlw/TheEssenceofLINQMinLINQ_13EBD/image_thumb_6.png" width="660" height="295" /&gt;&lt;/a&gt; &lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;The careful reader may spot an apparent difference in the multiplicity of the involved operations. Where one enumerable can be used to get multiple enumerators, it seems that one observable cannot be used with multiple observers. This is only how it looks, as duality comes to the rescue to explain this again. The statement for enumerables goes as follows: “&lt;em&gt;multiple calls &lt;/em&gt;to GetEnumerator each &lt;em&gt;&lt;strong&gt;return&lt;/strong&gt; one &lt;/em&gt;IEnumerator”. The dual of that becomes “a &lt;em&gt;single call &lt;/em&gt;to Subscribe can &lt;em&gt;&lt;strong&gt;take in &lt;/strong&gt;multiple&lt;/em&gt; IObservers”. While that’s not exactly the case in the real IObserver land, where you either wrap all of your observers in a single IObserver to achieve this effect, or make multiple calls to Subscribe (assuming – and that’s where the MinLinq approach differs slightly – a call to subscribe doesn’t block), it’s incredibly true in FObservable. How so? Well, one can combine delegates using the + operator to achieve the effect of subscribing multiple observers at the same time:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;pre class="code"&gt;&lt;span style="color:#2b91af;"&gt;Action&lt;/span&gt;&amp;lt;&lt;span style="color:#2b91af;"&gt;Option&lt;/span&gt;&amp;lt;&lt;span style="color:blue;"&gt;int&lt;/span&gt;&amp;gt;&amp;gt; observer1 = x =&amp;gt; &lt;span style="color:#2b91af;"&gt;Console&lt;/span&gt;.WriteLine(&lt;span style="color:#a31515;"&gt;&amp;quot;1 &amp;lt;- &amp;quot; &lt;/span&gt;+ x);
&lt;span style="color:#2b91af;"&gt;Action&lt;/span&gt;&amp;lt;&lt;span style="color:#2b91af;"&gt;Option&lt;/span&gt;&amp;lt;&lt;span style="color:blue;"&gt;int&lt;/span&gt;&amp;gt;&amp;gt; observer2 = x =&amp;gt; &lt;span style="color:#2b91af;"&gt;Console&lt;/span&gt;.WriteLine(&lt;span style="color:#a31515;"&gt;&amp;quot;2 &amp;lt;- &amp;quot; &lt;/span&gt;+ x);

&lt;span style="color:blue;"&gt;var &lt;/span&gt;xs = &lt;span style="color:#2b91af;"&gt;FObservable&lt;/span&gt;.Return(1);
xs(observer1 + observer2);&lt;/pre&gt;
&lt;/blockquote&gt;

&lt;p&gt;&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;The above will print Some(1) and None() twice, since both observers are getting it (in invocation order, coinciding with lexical order).&lt;/p&gt;

&lt;p&gt;&amp;#160;&lt;/p&gt;

&lt;h2&gt;Return&lt;/h2&gt;

&lt;p&gt;The previous sample brings us seamlessly to the next operator: Return, which realizes a singleton enumerable or observable collection. Though this one seems easy as well, it’s getting a bit more complex in the enumerable case as we need to maintain state across calls to “MoveNext”. Moreover, we need to do so on a per-enumerator basis as they all need to have their own view on the sequence. In our observable case, for the reasons mentioned above, things are slightly simpler as we can just “fire and forget” all data upon receiving a call to Subscribe. (Exercise: how would you make Subscribe asynchronous with respect to the sequence producing its values? When is this useful and when is it harmful?)&lt;/p&gt;

&lt;p&gt;Let’s first look at the Return operator realization in FEnumerable:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;pre class="code"&gt;&lt;span style="color:blue;"&gt;public static &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;Func&lt;/span&gt;&amp;lt;&lt;span style="color:#2b91af;"&gt;Func&lt;/span&gt;&amp;lt;&lt;span style="color:#2b91af;"&gt;Option&lt;/span&gt;&amp;lt;T&amp;gt;&amp;gt;&amp;gt; Return&amp;lt;T&amp;gt;(T value)
{
    &lt;span style="color:blue;"&gt;return &lt;/span&gt;() =&amp;gt;
    {
        &lt;span style="color:blue;"&gt;int &lt;/span&gt;i = 0;
        &lt;span style="color:blue;"&gt;return &lt;/span&gt;() =&amp;gt;
            i++ == 0
            ? (&lt;span style="color:#2b91af;"&gt;Option&lt;/span&gt;&amp;lt;T&amp;gt;)&lt;span style="color:blue;"&gt;new &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;Option&lt;/span&gt;&amp;lt;T&amp;gt;.&lt;span style="color:#2b91af;"&gt;Some&lt;/span&gt;(value)
            : (&lt;span style="color:#2b91af;"&gt;Option&lt;/span&gt;&amp;lt;T&amp;gt;)&lt;span style="color:blue;"&gt;new &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;Option&lt;/span&gt;&amp;lt;T&amp;gt;.&lt;span style="color:#2b91af;"&gt;None&lt;/span&gt;();
    };
}&lt;/pre&gt;
  &lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;&lt;/blockquote&gt;

&lt;p&gt;The state local to the “enumerator block” contains a counter that keeps track of the number of MoveNext calls that have been made. The first time, we return a Some(value) object, and the second (and subsequent) time(s) we answer with None. Notice this has the implicit contract of considering a None value as a &lt;em&gt;terminal&lt;/em&gt; in the grammar. If you want to enforce this policy, an exception could be raised if i reaches 2.&lt;/p&gt;

&lt;p&gt;In the FObservable world, things are quite easy. Upon a subscription call, we signal a Some and None message on the OnNext function, like this:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;pre class="code"&gt;&lt;span style="color:blue;"&gt;public static &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;Action&lt;/span&gt;&amp;lt;&lt;span style="color:#2b91af;"&gt;Action&lt;/span&gt;&amp;lt;&lt;span style="color:#2b91af;"&gt;Option&lt;/span&gt;&amp;lt;T&amp;gt;&amp;gt;&amp;gt; Return&amp;lt;T&amp;gt;(T value)
{
    &lt;span style="color:blue;"&gt;return &lt;/span&gt;o =&amp;gt;
    {
        o(&lt;span style="color:blue;"&gt;new &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;Option&lt;/span&gt;&amp;lt;T&amp;gt;.&lt;span style="color:#2b91af;"&gt;Some&lt;/span&gt;(value));
        o(&lt;span style="color:blue;"&gt;new &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;Option&lt;/span&gt;&amp;lt;T&amp;gt;.&lt;span style="color:#2b91af;"&gt;None&lt;/span&gt;());
    };
}&lt;/pre&gt;
  &lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;&lt;/blockquote&gt;

&lt;p&gt;&amp;#160;&lt;/p&gt;

&lt;h2&gt;&lt;strong&gt;Bind&lt;/strong&gt;&lt;/h2&gt;

&lt;p&gt;Why says Return and knows about &lt;a href="http://en.wikipedia.org/wiki/Monads_in_functional_programming"&gt;monads&lt;/a&gt; immediately thinks about Bind (&amp;gt;&amp;gt;= in Haskell). The Bind operator, known as SelectMany in LINQ, provides an essential combinator allowing to compose objects in the monad. In our case, those monads are IEnumerable&amp;lt;T&amp;gt; and IObservable&amp;lt;T&amp;gt;. In a previous episode of my More LINQ series, I’ve explained the basic idea of monadic composition a bit further, as summarized in the figure below:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;&lt;a href="http://bartdesmet.net/images_wlw/TheEssenceofLINQMinLINQ_13EBD/image_7.png"&gt;&lt;img style="border-right-width:0px;display:inline;border-top-width:0px;border-bottom-width:0px;border-left-width:0px;" title="image" border="0" alt="image" src="http://bartdesmet.net/images_wlw/TheEssenceofLINQMinLINQ_13EBD/image_thumb_7.png" width="640" height="236" /&gt;&lt;/a&gt; &lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;In the above, M&amp;lt;.&amp;gt; has to be substituted for either Func&amp;lt;Func&amp;lt;.&amp;gt;&amp;gt; or Action&amp;lt;Action&amp;lt;.&amp;gt;&amp;gt; to yield the signature for both FEnumerable’s and FObservable’s Bind operators. The implementation of the operator in the latter case is the more straightforward one of both:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;pre class="code"&gt;&lt;span style="color:blue;"&gt;public static &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;Action&lt;/span&gt;&amp;lt;&lt;span style="color:#2b91af;"&gt;Action&lt;/span&gt;&amp;lt;&lt;span style="color:#2b91af;"&gt;Option&lt;/span&gt;&amp;lt;R&amp;gt;&amp;gt;&amp;gt; Bind&amp;lt;T, R&amp;gt;(&lt;span style="color:blue;"&gt;this &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;Action&lt;/span&gt;&amp;lt;&lt;span style="color:#2b91af;"&gt;Action&lt;/span&gt;&amp;lt;&lt;span style="color:#2b91af;"&gt;Option&lt;/span&gt;&amp;lt;T&amp;gt;&amp;gt;&amp;gt; source, &lt;span style="color:#2b91af;"&gt;Func&lt;/span&gt;&amp;lt;T, &lt;span style="color:#2b91af;"&gt;Action&lt;/span&gt;&amp;lt;&lt;span style="color:#2b91af;"&gt;Action&lt;/span&gt;&amp;lt;&lt;span style="color:#2b91af;"&gt;Option&lt;/span&gt;&amp;lt;R&amp;gt;&amp;gt;&amp;gt;&amp;gt; selector)
{
    &lt;span style="color:blue;"&gt;return &lt;/span&gt;o =&amp;gt; source(x =&amp;gt;
    {
        &lt;span style="color:blue;"&gt;if &lt;/span&gt;(x &lt;span style="color:blue;"&gt;is &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;Option&lt;/span&gt;&amp;lt;T&amp;gt;.&lt;span style="color:#2b91af;"&gt;None&lt;/span&gt;)
        {
            o(&lt;span style="color:blue;"&gt;new &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;Option&lt;/span&gt;&amp;lt;R&amp;gt;.&lt;span style="color:#2b91af;"&gt;None&lt;/span&gt;());
        }
        &lt;span style="color:blue;"&gt;else
        &lt;/span&gt;{
            selector(x.Value)(y =&amp;gt;
            {
                &lt;span style="color:blue;"&gt;if &lt;/span&gt;(y &lt;span style="color:blue;"&gt;is &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;Option&lt;/span&gt;&amp;lt;R&amp;gt;.&lt;span style="color:#2b91af;"&gt;Some&lt;/span&gt;)
                    o(y);
            });
        }
    });
}&lt;/pre&gt;
  &lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;&lt;/blockquote&gt;

&lt;p&gt;Here, upon subscribing to an observable using observer “o”, the operator itself subscribes to the source observable that was fed in to the function. It does so by providing an observer that takes in the received element as “x”. Inside the observer’s body, which gets called for every element raised by the source, “x” is analyzed to see whether or not the source has terminated. If not, Bind does its &lt;em&gt;combining&lt;/em&gt; work by calling the selector function for the received element, getting back a new observable source “f(x.Value)”. The goal of Bind is to surface the values raised on this source to the surface of the operator call. Hence, we subscribe to this computed source “f(x.Value)” by providing an observer that takes in the received value as “y” and raises that to the surface by calling “o” (the external observer). Again we assume None is terminating the sequence, which could be enforced by keeping a bit of state (left as an exercise). We’ll see examples of operator usage later on.&lt;/p&gt;

&lt;p&gt;(Exercise: What if we want the Subscribe method to return immediately, running the Bind in the background. How would you do so?)&lt;/p&gt;

&lt;p&gt;In the FEnumerable case, things get more complex as we need to keep track of where we are in the source and projected sequences across different calls to “MoveNext”. While we could realize this using a state machine (just like iterators would do), I’ve taken on the challenge to write a state-keeping set of loops by hand. It may well be optimized or tweaked but it seems to do its job. Important situations to keep in mind include encountering empty inner sequences (signaled by None), requiring us to loop till we eventually find an object to &lt;em&gt;yield&lt;/em&gt;. It’s also important to properly return a Option&amp;lt;R&amp;gt;.None object when we reach the end of the outer source. One of the most essential parts of the code below is the storage of state outside the inner lambda, hence keeping per-enumerator state. Besides cursors into the outer and current inner sequences, we also keep the inner enumerator (recall the signature corresponding to IEnumerator&amp;lt;T&amp;gt;) in “innerE”.&lt;/p&gt;

&lt;blockquote&gt;
  &lt;pre class="code"&gt;&lt;span style="color:blue;"&gt;public static &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;Func&lt;/span&gt;&amp;lt;&lt;span style="color:#2b91af;"&gt;Func&lt;/span&gt;&amp;lt;&lt;span style="color:#2b91af;"&gt;Option&lt;/span&gt;&amp;lt;R&amp;gt;&amp;gt;&amp;gt; Bind&amp;lt;T, R&amp;gt;(&lt;span style="color:blue;"&gt;this &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;Func&lt;/span&gt;&amp;lt;&lt;span style="color:#2b91af;"&gt;Func&lt;/span&gt;&amp;lt;&lt;span style="color:#2b91af;"&gt;Option&lt;/span&gt;&amp;lt;T&amp;gt;&amp;gt;&amp;gt; source, &lt;span style="color:#2b91af;"&gt;Func&lt;/span&gt;&amp;lt;T, &lt;span style="color:#2b91af;"&gt;Func&lt;/span&gt;&amp;lt;&lt;span style="color:#2b91af;"&gt;Func&lt;/span&gt;&amp;lt;&lt;span style="color:#2b91af;"&gt;Option&lt;/span&gt;&amp;lt;R&amp;gt;&amp;gt;&amp;gt;&amp;gt; f)
{
    &lt;span style="color:blue;"&gt;return &lt;/span&gt;() =&amp;gt;
    {
        &lt;span style="color:blue;"&gt;var &lt;/span&gt;e = source();

        &lt;span style="color:#2b91af;"&gt;Option&lt;/span&gt;&amp;lt;T&amp;gt; lastOuter = &lt;span style="color:blue;"&gt;new &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;Option&lt;/span&gt;&amp;lt;T&amp;gt;.&lt;span style="color:#2b91af;"&gt;None&lt;/span&gt;();
        &lt;span style="color:#2b91af;"&gt;Option&lt;/span&gt;&amp;lt;R&amp;gt; lastInner = &lt;span style="color:blue;"&gt;new &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;Option&lt;/span&gt;&amp;lt;R&amp;gt;.&lt;span style="color:#2b91af;"&gt;None&lt;/span&gt;();
        &lt;span style="color:#2b91af;"&gt;Func&lt;/span&gt;&amp;lt;&lt;span style="color:#2b91af;"&gt;Option&lt;/span&gt;&amp;lt;R&amp;gt;&amp;gt; innerE = &lt;span style="color:blue;"&gt;null&lt;/span&gt;;

        &lt;span style="color:blue;"&gt;return &lt;/span&gt;() =&amp;gt;
        {
            &lt;span style="color:blue;"&gt;do
            &lt;/span&gt;{
                &lt;span style="color:blue;"&gt;while &lt;/span&gt;(lastInner &lt;span style="color:blue;"&gt;is &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;Option&lt;/span&gt;&amp;lt;R&amp;gt;.&lt;span style="color:#2b91af;"&gt;None&lt;/span&gt;)
                {
                    lastOuter = e();

                    &lt;span style="color:blue;"&gt;if &lt;/span&gt;(lastOuter &lt;span style="color:blue;"&gt;is &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;Option&lt;/span&gt;&amp;lt;T&amp;gt;.&lt;span style="color:#2b91af;"&gt;None&lt;/span&gt;)
                    {
                        &lt;span style="color:blue;"&gt;return new &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;Option&lt;/span&gt;&amp;lt;R&amp;gt;.&lt;span style="color:#2b91af;"&gt;None&lt;/span&gt;();
                    }
                    &lt;span style="color:blue;"&gt;else
                    &lt;/span&gt;{
                        innerE = f(lastOuter.Value)();
                    }

                    lastInner = innerE();
                    &lt;span style="color:blue;"&gt;if &lt;/span&gt;(lastInner &lt;span style="color:blue;"&gt;is &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;Option&lt;/span&gt;&amp;lt;R&amp;gt;.&lt;span style="color:#2b91af;"&gt;Some&lt;/span&gt;)
                    {
                        &lt;span style="color:blue;"&gt;return &lt;/span&gt;lastInner;
                    }
                }

                lastInner = innerE();
            } &lt;span style="color:blue;"&gt;while &lt;/span&gt;(lastInner &lt;span style="color:blue;"&gt;is &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;Option&lt;/span&gt;&amp;lt;R&amp;gt;.&lt;span style="color:#2b91af;"&gt;None&lt;/span&gt;);

            &lt;span style="color:blue;"&gt;return &lt;/span&gt;lastInner;
        };
    };
}&lt;/pre&gt;
  &lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;&lt;/blockquote&gt;

&lt;p&gt;The reader is invited to make sense of the above at his or her own pace, keeping in mind the regular LINQ to Objects implementation is the following much more comprehensible code:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;pre class="code"&gt;&lt;span style="color:blue;"&gt;public static &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;IEnumerable&lt;/span&gt;&amp;lt;R&amp;gt; SelectMany&amp;lt;T, R&amp;gt;(&lt;span style="color:blue;"&gt;this &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;IEnumerable&lt;/span&gt;&amp;lt;T&amp;gt; source, &lt;span style="color:#2b91af;"&gt;Func&lt;/span&gt;&amp;lt;T, &lt;span style="color:#2b91af;"&gt;IEnumerable&lt;/span&gt;&amp;lt;R&amp;gt;&amp;gt; f)
{
    &lt;span style="color:blue;"&gt;foreach &lt;/span&gt;(&lt;span style="color:blue;"&gt;var &lt;/span&gt;item &lt;span style="color:blue;"&gt;in &lt;/span&gt;source)
        &lt;span style="color:blue;"&gt;foreach &lt;/span&gt;(&lt;span style="color:blue;"&gt;var &lt;/span&gt;result &lt;span style="color:blue;"&gt;in &lt;/span&gt;f(item))
            &lt;span style="color:blue;"&gt;yield return &lt;/span&gt;result;
}&lt;/pre&gt;
  &lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;&lt;/blockquote&gt;

&lt;p&gt;The interesting thing about the SelectMany implementation is that the types in the signature exactly tell you what to do: the main operation on an IEnumerable is to enumerate using foreach. The only parameter you can do that on is source, but you can’t yield those elements as the output expects elements of type R and we got elements of type T. However, the function “f” accepts a T and produces an IEnumerable&amp;lt;R&amp;gt;, so if we call that one an enumerate the results, we got what we can yield. Simple.&lt;/p&gt;

&lt;p&gt;This operator is essential to LINQ (and monads) in that it allows many other operators to be written in terms of it. Where and Select and two that pop to mind immediately, and we’ll come to those when we talk about FEnumerableEx (and FObservable) later.&lt;/p&gt;

&lt;p&gt;&amp;#160;&lt;/p&gt;

&lt;h2&gt;Ana&lt;/h2&gt;

&lt;p&gt;An anamorphism is the fancy word for an operator that produces an M&amp;lt;T&amp;gt; out of something outside M&amp;lt;.&amp;gt;, by use of unfolding. Given some seed value and an iterator function, one can produce a potentially infinite sequence of elements. Implementation of this operator is straightforward in both cases, again with the enumerable case requiring some state:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;pre class="code"&gt;&lt;span style="color:blue;"&gt;public static &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;Func&lt;/span&gt;&amp;lt;&lt;span style="color:#2b91af;"&gt;Func&lt;/span&gt;&amp;lt;&lt;span style="color:#2b91af;"&gt;Option&lt;/span&gt;&amp;lt;T&amp;gt;&amp;gt;&amp;gt; Ana&amp;lt;T&amp;gt;(T seed, &lt;span style="color:#2b91af;"&gt;Func&lt;/span&gt;&amp;lt;T, &lt;span style="color:blue;"&gt;bool&lt;/span&gt;&amp;gt; condition, &lt;span style="color:#2b91af;"&gt;Func&lt;/span&gt;&amp;lt;T, T&amp;gt; next)
{
    &lt;span style="color:blue;"&gt;return &lt;/span&gt;() =&amp;gt;
    {
        &lt;span style="color:#2b91af;"&gt;Option&lt;/span&gt;&amp;lt;T&amp;gt; value = &lt;span style="color:blue;"&gt;new &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;Option&lt;/span&gt;&amp;lt;T&amp;gt;.&lt;span style="color:#2b91af;"&gt;None&lt;/span&gt;();
        &lt;span style="color:blue;"&gt;return &lt;/span&gt;() =&amp;gt;
            condition((value = &lt;span style="color:blue;"&gt;new &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;Option&lt;/span&gt;&amp;lt;T&amp;gt;.&lt;span style="color:#2b91af;"&gt;Some&lt;/span&gt;(
                value &lt;span style="color:blue;"&gt;is &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;Option&lt;/span&gt;&amp;lt;T&amp;gt;.&lt;span style="color:#2b91af;"&gt;None
                &lt;/span&gt;? seed
                : next(value.Value))).Value)
            ? (&lt;span style="color:#2b91af;"&gt;Option&lt;/span&gt;&amp;lt;T&amp;gt;)&lt;span style="color:blue;"&gt;new &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;Option&lt;/span&gt;&amp;lt;T&amp;gt;.&lt;span style="color:#2b91af;"&gt;Some&lt;/span&gt;(value.Value)
            : (&lt;span style="color:#2b91af;"&gt;Option&lt;/span&gt;&amp;lt;T&amp;gt;)&lt;span style="color:blue;"&gt;new &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;Option&lt;/span&gt;&amp;lt;T&amp;gt;.&lt;span style="color:#2b91af;"&gt;None&lt;/span&gt;();
    };
}&lt;/pre&gt;
&lt;/blockquote&gt;

&lt;p&gt;&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;For fun and giggles I wrote this one using conditional operator expressions only, with an assignment side-effect nicely interwoven. It’s left to the reader to write it in a more imperative style. Again, we’re assuming the enumerator function is not called after a None object has been received. The basic principle of the operator is clear and implementation would look like this in regular C# with iterators:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;pre class="code"&gt;&lt;span style="color:blue;"&gt;public static &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;IEnumerable&lt;/span&gt;&amp;lt;T&amp;gt; Ana&amp;lt;T&amp;gt;(T seed, &lt;span style="color:#2b91af;"&gt;Func&lt;/span&gt;&amp;lt;T, &lt;span style="color:blue;"&gt;bool&lt;/span&gt;&amp;gt; condition, &lt;span style="color:#2b91af;"&gt;Func&lt;/span&gt;&amp;lt;T, T&amp;gt; next)
{
    &lt;span style="color:blue;"&gt;for &lt;/span&gt;(T t = seed; condition(t); t = next(t))
        &lt;span style="color:blue;"&gt;yield return &lt;/span&gt;t;
}&lt;/pre&gt;
&lt;/blockquote&gt;

&lt;p&gt;On the FObservable side, things are simpler again (the main reason being that FEnumerable is hard because of its lazy nature and because we can’t use iterators):&lt;/p&gt;

&lt;blockquote&gt;
  &lt;pre class="code"&gt;&lt;span style="color:blue;"&gt;public static &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;Action&lt;/span&gt;&amp;lt;&lt;span style="color:#2b91af;"&gt;Action&lt;/span&gt;&amp;lt;&lt;span style="color:#2b91af;"&gt;Option&lt;/span&gt;&amp;lt;T&amp;gt;&amp;gt;&amp;gt; Ana&amp;lt;T&amp;gt;(T seed, &lt;span style="color:#2b91af;"&gt;Func&lt;/span&gt;&amp;lt;T, &lt;span style="color:blue;"&gt;bool&lt;/span&gt;&amp;gt; condition, &lt;span style="color:#2b91af;"&gt;Func&lt;/span&gt;&amp;lt;T, T&amp;gt; next)
{
    &lt;span style="color:blue;"&gt;return &lt;/span&gt;o =&amp;gt;
    {
        &lt;span style="color:blue;"&gt;for &lt;/span&gt;(T t = seed; condition(t); t = next(t))
            o(&lt;span style="color:blue;"&gt;new &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;Option&lt;/span&gt;&amp;lt;T&amp;gt;.&lt;span style="color:#2b91af;"&gt;Some&lt;/span&gt;(t));
        o(&lt;span style="color:blue;"&gt;new &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;Option&lt;/span&gt;&amp;lt;T&amp;gt;.&lt;span style="color:#2b91af;"&gt;None&lt;/span&gt;());
    };
}&lt;/pre&gt;
&lt;/blockquote&gt;

&lt;p&gt;Again, the reader is invited to think about what I’d take to have this sequence getting generated on the background, as opposed to blocking the caller.&lt;/p&gt;

&lt;p&gt;As an additional exercise, can you rewrite Return and Empty in terms of Ana, therefore making those two operators no longer primitives? Doing so will bring down the total of essentials to three: Ana, Cata and Bind:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;&lt;a href="http://bartdesmet.net/images_wlw/TheEssenceofLINQMinLINQ_13EBD/image_8.png"&gt;&lt;img style="border-bottom:0px;border-left:0px;display:inline;border-top:0px;border-right:0px;" title="image" border="0" alt="image" src="http://bartdesmet.net/images_wlw/TheEssenceofLINQMinLINQ_13EBD/image_thumb_8.png" width="640" height="339" /&gt;&lt;/a&gt; &lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;&amp;#160;&lt;/p&gt;

&lt;h2&gt;Cata&lt;/h2&gt;

&lt;p&gt;The opposite of an anamorphism is a catamorphism, also known as Aggregate in LINQ. Its goal is to fold a M&amp;lt;T&amp;gt; into something outside M&amp;lt;.&amp;gt;, e.g. computing the sum of a sequence of numbers. Since this is a greedy operation, we can do it on the spot for both the FEnumerable and FObservable cases as shown below:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;pre class="code"&gt;&lt;span style="color:blue;"&gt;public static &lt;/span&gt;R Cata&amp;lt;T, R&amp;gt;(&lt;span style="color:blue;"&gt;this &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;Func&lt;/span&gt;&amp;lt;&lt;span style="color:#2b91af;"&gt;Func&lt;/span&gt;&amp;lt;&lt;span style="color:#2b91af;"&gt;Option&lt;/span&gt;&amp;lt;T&amp;gt;&amp;gt;&amp;gt; source, R seed, &lt;span style="color:#2b91af;"&gt;Func&lt;/span&gt;&amp;lt;R, T, R&amp;gt; f)
{
    &lt;span style="color:blue;"&gt;var &lt;/span&gt;e = source();

    &lt;span style="color:#2b91af;"&gt;Option&lt;/span&gt;&amp;lt;T&amp;gt;.&lt;span style="color:#2b91af;"&gt;Some &lt;/span&gt;value;
    R result = seed;
    &lt;span style="color:blue;"&gt;while &lt;/span&gt;((value = e() &lt;span style="color:blue;"&gt;as &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;Option&lt;/span&gt;&amp;lt;T&amp;gt;.&lt;span style="color:#2b91af;"&gt;Some&lt;/span&gt;) != &lt;span style="color:blue;"&gt;null&lt;/span&gt;)
    {
        result = f(result, value.Value);
    }

    &lt;span style="color:blue;"&gt;return &lt;/span&gt;result;
}&lt;/pre&gt;
&lt;/blockquote&gt;

&lt;p&gt;First for the enumerable case, we simply run till we get a None object, continuously calling the aggregation function, starting with the seed value. In the observable case, things are equally simple:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;pre class="code"&gt;&lt;span style="color:blue;"&gt;public static &lt;/span&gt;R Cata&amp;lt;T, R&amp;gt;(&lt;span style="color:blue;"&gt;this &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;Action&lt;/span&gt;&amp;lt;&lt;span style="color:#2b91af;"&gt;Action&lt;/span&gt;&amp;lt;&lt;span style="color:#2b91af;"&gt;Option&lt;/span&gt;&amp;lt;T&amp;gt;&amp;gt;&amp;gt; source, R seed, &lt;span style="color:#2b91af;"&gt;Func&lt;/span&gt;&amp;lt;R, T, R&amp;gt; f)
{
    R result = seed;

    &lt;span style="color:blue;"&gt;bool &lt;/span&gt;end = &lt;span style="color:blue;"&gt;false&lt;/span&gt;;
    source(x =&amp;gt;
    {
        &lt;span style="color:blue;"&gt;if &lt;/span&gt;(x &lt;span style="color:blue;"&gt;is &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;Option&lt;/span&gt;&amp;lt;T&amp;gt;.&lt;span style="color:#2b91af;"&gt;Some &lt;/span&gt;&amp;amp;&amp;amp; !end)
            result = f(result, x.Value);
        &lt;span style="color:blue;"&gt;else
            &lt;/span&gt;end = &lt;span style="color:blue;"&gt;true&lt;/span&gt;; &lt;span style="color:green;"&gt;// or break using exception
    &lt;/span&gt;});

    &lt;span style="color:blue;"&gt;return &lt;/span&gt;result;
}&lt;/pre&gt;
  &lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;&lt;/blockquote&gt;

&lt;p&gt;This time we have to hook up an observer with the source and analyze what we got back. Notice the code above shows one approach to break out of or immunize an observer after a None message has been received. Notice though that if all constructor functions can be trusted (which is not the case with an Action of Func), such protections wouldn’t be required as we’re defining a closed world of constructors and combinators. If the former group never emits sequences that don’t follow the described protocol and the latter never combines existing sequences into an invalid one (i.e. preserving the protocol properties), it shouldn’t be possible to fall off a cliff.&lt;/p&gt;

&lt;p&gt;&amp;#160;&lt;/p&gt;

&lt;h1&gt;Bridging the brave new world with the old-school one&lt;/h1&gt;

&lt;p&gt;Before getting into more operators layered on top of the essential ones provided above, we should spend a few minutes looking at ways to convert back and forth between the new functionally inspired “flat” world and the familiar interface-centric “bombastic” world of LINQ. In particular, can we establish the following conversions?&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;IEnumerable&amp;lt;T&amp;gt; to Func&amp;lt;Func&amp;lt;Option&amp;lt;T&amp;gt;&amp;gt;&amp;gt;&lt;/li&gt;

  &lt;li&gt;Func&amp;lt;Func&amp;lt;Option&amp;lt;T&amp;gt;&amp;gt;&amp;gt; to IEnumerable&amp;lt;T&amp;gt;&lt;/li&gt;

  &lt;li&gt;IObservable&amp;lt;T&amp;gt; to Action&amp;lt;Action&amp;lt;Option&amp;lt;T&amp;gt;&amp;gt;&amp;gt;&lt;/li&gt;

  &lt;li&gt;Action&amp;lt;Action&amp;lt;Option&amp;lt;T&amp;gt;&amp;gt;&amp;gt; to IObservable&amp;lt;T&amp;gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Obviously the answer is we can. Let’s focus on the first two as a starter. It’s clear that in order to go from an IEnumerable&amp;lt;T&amp;gt; to our new world of FEnumerable we should iterate the specified sequence. We should do so in a lazy manner such that upon every call to FEnumerable’s inner function (playing the enumerator’s role) we fetch an element out of the source IEnumerator&amp;lt;T&amp;gt;, but no earlier. In other words, we have to keep the iteration state which is represented by an IEnumerator&amp;lt;T&amp;gt; as the local state to the enumerator function:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;pre class="code"&gt;&lt;span style="color:blue;"&gt;public static &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;Func&lt;/span&gt;&amp;lt;&lt;span style="color:#2b91af;"&gt;Func&lt;/span&gt;&amp;lt;&lt;span style="color:#2b91af;"&gt;Option&lt;/span&gt;&amp;lt;T&amp;gt;&amp;gt;&amp;gt; AsFEnumerable&amp;lt;T&amp;gt;(&lt;span style="color:blue;"&gt;this &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;IEnumerable&lt;/span&gt;&amp;lt;T&amp;gt; source)
{
    &lt;span style="color:blue;"&gt;return &lt;/span&gt;() =&amp;gt;
    {
        &lt;span style="color:blue;"&gt;var &lt;/span&gt;e = source.GetEnumerator();
        &lt;span style="color:blue;"&gt;return &lt;/span&gt;() =&amp;gt; e.MoveNext()
            ? (&lt;span style="color:#2b91af;"&gt;Option&lt;/span&gt;&amp;lt;T&amp;gt;)&lt;span style="color:blue;"&gt;new &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;Option&lt;/span&gt;&amp;lt;T&amp;gt;.&lt;span style="color:#2b91af;"&gt;Some&lt;/span&gt;(e.Current)
            : (&lt;span style="color:#2b91af;"&gt;Option&lt;/span&gt;&amp;lt;T&amp;gt;)&lt;span style="color:blue;"&gt;new &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;Option&lt;/span&gt;&amp;lt;T&amp;gt;.&lt;span style="color:#2b91af;"&gt;None&lt;/span&gt;();
    };
}&lt;/pre&gt;
&lt;/blockquote&gt;

&lt;p&gt;&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;This should be fairly straightforward code to grasp, ensuring we properly terminate a (finite) sequence with a None object to signal completion. The opposite operation is easy as well, now calling a FEnumerable’s enumerator function, providing results to the caller in a lazy fashion by means of a typical C# iterator:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;pre class="code"&gt;&lt;span style="color:blue;"&gt;public static &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;IEnumerable&lt;/span&gt;&amp;lt;T&amp;gt; AsEnumerable&amp;lt;T&amp;gt;(&lt;span style="color:blue;"&gt;this &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;Func&lt;/span&gt;&amp;lt;&lt;span style="color:#2b91af;"&gt;Func&lt;/span&gt;&amp;lt;&lt;span style="color:#2b91af;"&gt;Option&lt;/span&gt;&amp;lt;T&amp;gt;&amp;gt;&amp;gt; source)
{
    &lt;span style="color:blue;"&gt;var &lt;/span&gt;e = source();
    &lt;span style="color:#2b91af;"&gt;Option&lt;/span&gt;&amp;lt;T&amp;gt;.&lt;span style="color:#2b91af;"&gt;Some &lt;/span&gt;value;
    &lt;span style="color:blue;"&gt;while &lt;/span&gt;((value = e() &lt;span style="color:blue;"&gt;as &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;Option&lt;/span&gt;&amp;lt;T&amp;gt;.&lt;span style="color:#2b91af;"&gt;Some&lt;/span&gt;) != &lt;span style="color:blue;"&gt;null&lt;/span&gt;)
    {
        &lt;span style="color:blue;"&gt;yield return &lt;/span&gt;value.Value;
    }
}&lt;/pre&gt;
  &lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;&lt;/blockquote&gt;

&lt;p&gt;As soon as we encounter a None object, we’ll break out of the loop causing the consuming enumerator to terminate. Using the operators above, we can readily verify the back and forth conversions easily:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;pre class="code"&gt;&lt;span style="color:green;"&gt;// IEnumerable -&amp;gt; FEnumerable
&lt;/span&gt;&lt;span style="color:blue;"&gt;var &lt;/span&gt;xs = &lt;span style="color:#2b91af;"&gt;Enumerable&lt;/span&gt;.Range(0, 10).AsFEnumerable();
{
    &lt;span style="color:blue;"&gt;var &lt;/span&gt;xse = xs();
    &lt;span style="color:#2b91af;"&gt;Option&lt;/span&gt;&amp;lt;&lt;span style="color:blue;"&gt;int&lt;/span&gt;&amp;gt; x;
    &lt;span style="color:blue;"&gt;while &lt;/span&gt;((x = xse() &lt;span style="color:blue;"&gt;as &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;Option&lt;/span&gt;&amp;lt;&lt;span style="color:blue;"&gt;int&lt;/span&gt;&amp;gt;.&lt;span style="color:#2b91af;"&gt;Some&lt;/span&gt;) != &lt;span style="color:blue;"&gt;null&lt;/span&gt;)
        &lt;span style="color:#2b91af;"&gt;Console&lt;/span&gt;.WriteLine(x.Value);
}

&lt;span style="color:green;"&gt;// FEnumerable -&amp;gt; IEnumerable
&lt;/span&gt;&lt;span style="color:blue;"&gt;var &lt;/span&gt;ys = xs.AsEnumerable();
{
    &lt;span style="color:blue;"&gt;foreach &lt;/span&gt;(&lt;span style="color:blue;"&gt;var &lt;/span&gt;y &lt;span style="color:blue;"&gt;in &lt;/span&gt;ys)
        &lt;span style="color:#2b91af;"&gt;Console&lt;/span&gt;.WriteLine(y);
}&lt;/pre&gt;
  &lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;&lt;/blockquote&gt;

&lt;p&gt;This is very convenient as we’ll be able to treat arrays and other enumerable collections as FEnumerable functions in a blink of the eye. Now we can start to mix and match typical LINQ to Objects operators with our own academic playground.&lt;/p&gt;

&lt;p&gt;On to the dual world, we can also provide conversions for IObservable&amp;lt;T&amp;gt; to FObservable&amp;lt;T&amp;gt; back and forth. Both are relatively easy to realize as well but lets starts with old to new:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;pre class="code"&gt;&lt;span style="color:blue;"&gt;public static &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;IObservable&lt;/span&gt;&amp;lt;T&amp;gt; AsObservable&amp;lt;T&amp;gt;(&lt;span style="color:blue;"&gt;this &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;Action&lt;/span&gt;&amp;lt;&lt;span style="color:#2b91af;"&gt;Action&lt;/span&gt;&amp;lt;&lt;span style="color:#2b91af;"&gt;Option&lt;/span&gt;&amp;lt;T&amp;gt;&amp;gt;&amp;gt; source)
{
    &lt;span style="color:blue;"&gt;return &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;Observable&lt;/span&gt;.Create&amp;lt;T&amp;gt;(o =&amp;gt;
    {
        source(x =&amp;gt;
        {
            &lt;span style="color:blue;"&gt;if &lt;/span&gt;(x &lt;span style="color:blue;"&gt;is &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;Option&lt;/span&gt;&amp;lt;T&amp;gt;.&lt;span style="color:#2b91af;"&gt;Some&lt;/span&gt;)
                o.OnNext(x.Value);
            &lt;span style="color:blue;"&gt;else
                &lt;/span&gt;o.OnCompleted();
        });
        &lt;span style="color:blue;"&gt;return &lt;/span&gt;() =&amp;gt; { };
    });
}&lt;/pre&gt;
  &lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;&lt;/blockquote&gt;

&lt;p&gt;Here I’m using Rx’s Observable.Create operator to simplify the creation of an IObservable&amp;lt;T&amp;gt;, passing in an observer’s code body. Lambda parameter “o” is an IObserver&amp;lt;T&amp;gt;, so all we got to do is subscribe to our source (by means of just calling it, passing in a FObserver function) and forward received objects “x” to the external observer. As we don’t have a notion to run asynchronous in our little world, we simply return the no-op action delegate from the observer function. Since all execution happens synchronously upon a Subscribe call to the produced IObservable&amp;lt;T&amp;gt;, there’s little for us to do in a reaction to an unsubscribe invocation.&lt;/p&gt;

&lt;p&gt;In the other direction, things are even simpler. We simply use an Rx extension method for IObservable&amp;lt;T&amp;gt; to subscribe given an OnNext and OnCompleted delegate:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;pre class="code"&gt;&lt;span style="color:blue;"&gt;public static &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;Action&lt;/span&gt;&amp;lt;&lt;span style="color:#2b91af;"&gt;Action&lt;/span&gt;&amp;lt;&lt;span style="color:#2b91af;"&gt;Option&lt;/span&gt;&amp;lt;T&amp;gt;&amp;gt;&amp;gt; AsFObservable&amp;lt;T&amp;gt;(&lt;span style="color:blue;"&gt;this &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;IObservable&lt;/span&gt;&amp;lt;T&amp;gt; source)
{
    &lt;span style="color:blue;"&gt;return &lt;/span&gt;o =&amp;gt;
    {
        source.Subscribe(x =&amp;gt; o(&lt;span style="color:blue;"&gt;new &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;Option&lt;/span&gt;&amp;lt;T&amp;gt;.&lt;span style="color:#2b91af;"&gt;Some&lt;/span&gt;(x)), () =&amp;gt; o(&lt;span style="color:blue;"&gt;new &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;Option&lt;/span&gt;&amp;lt;T&amp;gt;.&lt;span style="color:#2b91af;"&gt;None&lt;/span&gt;()));
    };
}&lt;/pre&gt;
  &lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;&lt;/blockquote&gt;

&lt;p&gt;Again we can test this easily, this time using Observable.Range. Since that one runs asynchronously, we have to do a bit of synchronization to see the results printed nicely:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;pre class="code"&gt;&lt;span style="color:green;"&gt;// IObservable -&amp;gt; FObservable
&lt;/span&gt;&lt;span style="color:blue;"&gt;var &lt;/span&gt;evt = &lt;span style="color:blue;"&gt;new &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;ManualResetEvent&lt;/span&gt;(&lt;span style="color:blue;"&gt;false&lt;/span&gt;);
&lt;span style="color:blue;"&gt;var &lt;/span&gt;xs = &lt;span style="color:#2b91af;"&gt;Observable&lt;/span&gt;.Range(0, 10).AsFObservable();
{
    xs(x =&amp;gt;
    {
        &lt;span style="color:blue;"&gt;if &lt;/span&gt;(x &lt;span style="color:blue;"&gt;is &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;Option&lt;/span&gt;&amp;lt;&lt;span style="color:blue;"&gt;int&lt;/span&gt;&amp;gt;.&lt;span style="color:#2b91af;"&gt;Some&lt;/span&gt;)
            &lt;span style="color:#2b91af;"&gt;Console&lt;/span&gt;.WriteLine(x.Value);
        &lt;span style="color:blue;"&gt;else
            &lt;/span&gt;evt.Set();
    });
}
evt.WaitOne();

&lt;span style="color:green;"&gt;// FObservable -&amp;gt; IObservable
&lt;/span&gt;&lt;span style="color:blue;"&gt;var &lt;/span&gt;ys = xs.AsObservable();
{
    &lt;span style="color:green;"&gt;// We got this one synchronous inside.
    &lt;/span&gt;ys.Subscribe(&lt;span style="color:#2b91af;"&gt;Console&lt;/span&gt;.WriteLine);
}&lt;/pre&gt;
  &lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;&lt;/blockquote&gt;

&lt;p&gt;The result of all this plumbing is summarized in the following diagram. The direct conversion between a FEnumerable and FObservable (and vice versa) is left to the reader as an interesting exercise:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;&lt;a href="http://bartdesmet.net/images_wlw/TheEssenceofLINQMinLINQ_13EBD/image_9.png"&gt;&lt;img style="border-bottom:0px;border-left:0px;display:inline;border-top:0px;border-right:0px;" title="image" border="0" alt="image" src="http://bartdesmet.net/images_wlw/TheEssenceofLINQMinLINQ_13EBD/image_thumb_9.png" width="640" height="285" /&gt;&lt;/a&gt;&amp;#160;&lt;/p&gt;

  &lt;p&gt;&amp;#160;&lt;/p&gt;
&lt;/blockquote&gt;

&lt;h1&gt;Where and Select for monadic dummies&lt;/h1&gt;

&lt;p&gt;While we leave the implementation of operators like Snoc (Cons in reverse, to construct sequences out of a single element and a sequence) and Concat (concatenating arbitrary sequences to one another) to the reader, we should focus on a few operators that can be realized using the essential building blocks provided before. In particular, we’ll implement Where and Select in terms of Bind, Empty and Return.&lt;/p&gt;

&lt;p&gt;Recall what Bind does: it combines a sequence with sequences generated from a function call, collecting the elements all sequences that result from those function calls. In a concrete sample: given a list of products and a way to get all the suppliers for each product we can return a sequence of all suppliers across all products. Or with function arrows: IE&amp;lt;Product&amp;gt; –&amp;gt; (Product –&amp;gt; IE&amp;lt;Supplier&amp;gt;) –&amp;gt; IE&amp;lt;Supplier&amp;gt;. This is exactly the signature of Bind or SelectMany.&lt;/p&gt;

&lt;p&gt;How can we use this to create a filter like Where? The answer is pretty simple, by controlling the “selector” function passed to Bind and make it analyze each element that’s passed in, deciding whether or not to return it to Bind. The “whether or not” part can be realized using a conditional either returning Return(element) or Empty(). And there we got our filtering logic:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;pre class="code"&gt;&lt;span style="color:blue;"&gt;public static &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;Func&lt;/span&gt;&amp;lt;&lt;span style="color:#2b91af;"&gt;Func&lt;/span&gt;&amp;lt;&lt;span style="color:#2b91af;"&gt;Option&lt;/span&gt;&amp;lt;T&amp;gt;&amp;gt;&amp;gt; Where&amp;lt;T&amp;gt;(&lt;span style="color:blue;"&gt;this &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;Func&lt;/span&gt;&amp;lt;&lt;span style="color:#2b91af;"&gt;Func&lt;/span&gt;&amp;lt;&lt;span style="color:#2b91af;"&gt;Option&lt;/span&gt;&amp;lt;T&amp;gt;&amp;gt;&amp;gt; source, &lt;span style="color:#2b91af;"&gt;Func&lt;/span&gt;&amp;lt;T, &lt;span style="color:blue;"&gt;bool&lt;/span&gt;&amp;gt; filter)
{
    &lt;span style="color:blue;"&gt;return &lt;/span&gt;source.Bind(t =&amp;gt; filter(t) ? &lt;span style="color:#2b91af;"&gt;FEnumerable&lt;/span&gt;.Return(t) : &lt;span style="color:#2b91af;"&gt;FEnumerable&lt;/span&gt;.Empty&amp;lt;T&amp;gt;());
}&lt;/pre&gt;
&lt;/blockquote&gt;

&lt;p&gt;A picture is worth a thousand words, so let’s have a look at the Where operator realization in terms of Bind:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;&lt;a href="http://bartdesmet.net/images_wlw/TheEssenceofLINQMinLINQ_13EBD/image_10.png"&gt;&lt;img style="border-bottom:0px;border-left:0px;display:inline;border-top:0px;border-right:0px;" title="image" border="0" alt="image" src="http://bartdesmet.net/images_wlw/TheEssenceofLINQMinLINQ_13EBD/image_thumb_10.png" width="640" height="343" /&gt;&lt;/a&gt; &lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;And guess what, the FObservable implementation can be derived by mechanical translation from the one for FEnumerable:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;pre class="code"&gt;&lt;span style="color:blue;"&gt;public static &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;Action&lt;/span&gt;&amp;lt;&lt;span style="color:#2b91af;"&gt;Action&lt;/span&gt;&amp;lt;&lt;span style="color:#2b91af;"&gt;Option&lt;/span&gt;&amp;lt;T&amp;gt;&amp;gt;&amp;gt; Where&amp;lt;T&amp;gt;(&lt;span style="color:blue;"&gt;this &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;Action&lt;/span&gt;&amp;lt;&lt;span style="color:#2b91af;"&gt;Action&lt;/span&gt;&amp;lt;&lt;span style="color:#2b91af;"&gt;Option&lt;/span&gt;&amp;lt;T&amp;gt;&amp;gt;&amp;gt; source, &lt;span style="color:#2b91af;"&gt;Func&lt;/span&gt;&amp;lt;T, &lt;span style="color:blue;"&gt;bool&lt;/span&gt;&amp;gt; filter)
{
    &lt;span style="color:blue;"&gt;return &lt;/span&gt;source.Bind(t =&amp;gt; filter(t) ? &lt;span style="color:#2b91af;"&gt;FObservable&lt;/span&gt;.Return(t) : &lt;span style="color:#2b91af;"&gt;FObservable&lt;/span&gt;.Empty&amp;lt;T&amp;gt;());
}&lt;/pre&gt;
&lt;/blockquote&gt;

&lt;p&gt;&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;In fact, the code is exactly the same with FEnumerable replaced by FObservable. If we’d have typedefs for the function signatures or static extension methods on a delegate type, we’d actually see both pieces of code being the same of the following “template”:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;pre class="code"&gt;&lt;span style="color:blue;"&gt;public static &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;M&lt;/span&gt;&amp;lt;T&amp;gt; Where&amp;lt;T&amp;gt;(&lt;span style="color:blue;"&gt;this &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;M&lt;/span&gt;&amp;lt;T&amp;gt; source, &lt;span style="color:#2b91af;"&gt;Func&lt;/span&gt;&amp;lt;T, &lt;span style="color:blue;"&gt;bool&lt;/span&gt;&amp;gt; filter)
{
    &lt;span style="color:blue;"&gt;return &lt;/span&gt;source.Bind(t =&amp;gt; filter(t) ? &lt;span style="color:#2b91af;"&gt;M&lt;/span&gt;&amp;lt;T&amp;gt;.Return(t) : &lt;span style="color:#2b91af;"&gt;M&lt;/span&gt;&amp;lt;T&amp;gt;.Empty());
}&lt;/pre&gt;
  &lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;&lt;/blockquote&gt;

&lt;p&gt;Such an M&amp;lt;T&amp;gt; abstraction would be realized as a &lt;em&gt;type constructor&lt;/em&gt; in Haskell and the packaging of both Return and Bind on M&amp;lt;T&amp;gt; would be realized by means of a &lt;em&gt;type class&lt;/em&gt; that looks as follows:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;&lt;font face="Courier New"&gt;class Monad m where
      &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; return :: a –&amp;gt; m a

      &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; (&amp;gt;&amp;gt;=)&amp;#160; :: m a –&amp;gt; (a –&amp;gt; m b) –&amp;gt; m b&lt;/font&gt;&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;The second function is Haskell’s infix operator for bind. More information ca be found at the following locations:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;a title="http://www.haskell.org/haskellwiki/Monad" href="http://www.haskell.org/haskellwiki/Monad"&gt;http://www.haskell.org/haskellwiki/Monad&lt;/a&gt;&lt;/li&gt;

  &lt;li&gt;&lt;a title="http://www.haskell.org/tutorial/monads.html" href="http://www.haskell.org/tutorial/monads.html"&gt;http://www.haskell.org/tutorial/monads.html&lt;/a&gt;&lt;/li&gt;

  &lt;li&gt;&lt;a title="http://en.wikibooks.org/wiki/Haskell/Understanding_monads" href="http://en.wikibooks.org/wiki/Haskell/Understanding_monads"&gt;http://en.wikibooks.org/wiki/Haskell/Understanding_monads&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;How can we realize Select using Bind and Return as well? The answer is again very straightforward: this time we simply apply the projection function to the object passed to the bind selector function and wrap the result using Return. Here’s the code for both worlds, again ready to be abstracted to M&amp;lt;T&amp;gt;:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;pre class="code"&gt;&lt;span style="color:blue;"&gt;public static &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;Func&lt;/span&gt;&amp;lt;&lt;span style="color:#2b91af;"&gt;Func&lt;/span&gt;&amp;lt;&lt;span style="color:#2b91af;"&gt;Option&lt;/span&gt;&amp;lt;R&amp;gt;&amp;gt;&amp;gt; Select&amp;lt;T, R&amp;gt;(&lt;span style="color:blue;"&gt;this &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;Func&lt;/span&gt;&amp;lt;&lt;span style="color:#2b91af;"&gt;Func&lt;/span&gt;&amp;lt;&lt;span style="color:#2b91af;"&gt;Option&lt;/span&gt;&amp;lt;T&amp;gt;&amp;gt;&amp;gt; source, &lt;span style="color:#2b91af;"&gt;Func&lt;/span&gt;&amp;lt;T, R&amp;gt; selector)
{
    &lt;span style="color:blue;"&gt;return &lt;/span&gt;source.Bind(t =&amp;gt; &lt;span style="color:#2b91af;"&gt;FEnumerable&lt;/span&gt;.Return(selector(t)));
}&lt;/pre&gt;

  &lt;pre class="code"&gt;&lt;span style="color:blue;"&gt;public static &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;Action&lt;/span&gt;&amp;lt;&lt;span style="color:#2b91af;"&gt;Action&lt;/span&gt;&amp;lt;&lt;span style="color:#2b91af;"&gt;Option&lt;/span&gt;&amp;lt;R&amp;gt;&amp;gt;&amp;gt; Select&amp;lt;T, R&amp;gt;(&lt;span style="color:blue;"&gt;this &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;Action&lt;/span&gt;&amp;lt;&lt;span style="color:#2b91af;"&gt;Action&lt;/span&gt;&amp;lt;&lt;span style="color:#2b91af;"&gt;Option&lt;/span&gt;&amp;lt;T&amp;gt;&amp;gt;&amp;gt; source, &lt;span style="color:#2b91af;"&gt;Func&lt;/span&gt;&amp;lt;T, R&amp;gt; selector)
{
    &lt;span style="color:blue;"&gt;return &lt;/span&gt;source.Bind(t =&amp;gt; &lt;span style="color:#2b91af;"&gt;FObservable&lt;/span&gt;.Return(selector(t)));
}&lt;/pre&gt;
  &lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;&lt;/blockquote&gt;

&lt;p&gt;Again a picture will make the above more clear:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;&lt;a href="http://bartdesmet.net/images_wlw/TheEssenceofLINQMinLINQ_13EBD/image_11.png"&gt;&lt;img style="border-bottom:0px;border-left:0px;display:inline;border-top:0px;border-right:0px;" title="image" border="0" alt="image" src="http://bartdesmet.net/images_wlw/TheEssenceofLINQMinLINQ_13EBD/image_thumb_11.png" width="506" height="349" /&gt;&lt;/a&gt; &lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;With those extension methods in place, we can actually start writing LINQ expressions against FEnumerable and FObservable (function!) objects. That’s right: now you got a delegate you can dot into, thanks to the magic of extension methods. But using convenient LINQ syntax, we don’t even have to see any of that:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;pre class="code"&gt;&lt;span style="color:blue;"&gt;var &lt;/span&gt;res = (&lt;span style="color:blue;"&gt;from &lt;/span&gt;x &lt;span style="color:blue;"&gt;in &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;Enumerable&lt;/span&gt;.Range(0, 10).AsFEnumerable()
           &lt;span style="color:blue;"&gt;where &lt;/span&gt;x % 2 == 0
           &lt;span style="color:blue;"&gt;select &lt;/span&gt;x + 1).AsEnumerable();

&lt;span style="color:blue;"&gt;foreach &lt;/span&gt;(&lt;span style="color:blue;"&gt;var &lt;/span&gt;x &lt;span style="color:blue;"&gt;in &lt;/span&gt;res)
    &lt;span style="color:#2b91af;"&gt;Console&lt;/span&gt;.WriteLine(x);&lt;/pre&gt;
  &lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;&lt;/blockquote&gt;

&lt;p&gt;Notice how we go back and forth between classic IEnumerable&amp;lt;T&amp;gt; and our FEnumerable implementation? But the key to see here is that our Where and Select operators are getting called. The result obviously prints 1, 3, 5, 7, 9 and to convince ourselves or calls happening to our methods, we’ll have a look in the debugger:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;&lt;a href="http://bartdesmet.net/images_wlw/TheEssenceofLINQMinLINQ_13EBD/image_12.png"&gt;&lt;img style="border-bottom:0px;border-left:0px;display:inline;border-top:0px;border-right:0px;" title="image" border="0" alt="image" src="http://bartdesmet.net/images_wlw/TheEssenceofLINQMinLINQ_13EBD/image_thumb_12.png" width="992" height="364" /&gt;&lt;/a&gt; &lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;I hope this suffices to convince the reader we got query expression syntax working around our MinLINQ implementation. It’s left to the reader to decipher the exact call stack we’re observing above. The same exercise can be repeated for the FObservable case, using the following equivalent code:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;pre class="code"&gt;&lt;span style="color:blue;"&gt;var &lt;/span&gt;res = (&lt;span style="color:blue;"&gt;from &lt;/span&gt;x &lt;span style="color:blue;"&gt;in &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;Observable&lt;/span&gt;.Range(0, 10).AsFObservable()
           &lt;span style="color:blue;"&gt;where &lt;/span&gt;x % 2 == 0
           &lt;span style="color:blue;"&gt;select &lt;/span&gt;x + 1).AsObservable();

res.Subscribe(&lt;span style="color:#2b91af;"&gt;Console&lt;/span&gt;.WriteLine);
&lt;span style="color:#2b91af;"&gt;Console&lt;/span&gt;.ReadLine(); &lt;span style="color:green;"&gt;// Stuff happening on the background; don&amp;#39;t exit yet&lt;/span&gt;&lt;/pre&gt;
  &lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;&lt;/blockquote&gt;

&lt;p&gt;Since Bind is none other than SelectMany in disguise, we could rename it as such to enable it for use in LINQ as well, triggered by query expressions having multiple from clauses. In fact, to fully enable query expressions of that form, you’ll need a slight tweak to the SelectMany signature, as follows (same for the observable case of course):&lt;/p&gt;

&lt;blockquote&gt;
  &lt;pre class="code"&gt;&lt;span style="color:blue;"&gt;public static &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;Func&lt;/span&gt;&amp;lt;&lt;span style="color:#2b91af;"&gt;Func&lt;/span&gt;&amp;lt;&lt;span style="color:#2b91af;"&gt;Option&lt;/span&gt;&amp;lt;R&amp;gt;&amp;gt;&amp;gt; SelectMany&amp;lt;T, C, R&amp;gt;(&lt;span style="color:blue;"&gt;this &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;Func&lt;/span&gt;&amp;lt;&lt;span style="color:#2b91af;"&gt;Func&lt;/span&gt;&amp;lt;&lt;span style="color:#2b91af;"&gt;Option&lt;/span&gt;&amp;lt;T&amp;gt;&amp;gt;&amp;gt; source, &lt;span style="color:#2b91af;"&gt;Func&lt;/span&gt;&amp;lt;T, &lt;span style="color:#2b91af;"&gt;Func&lt;/span&gt;&amp;lt;&lt;span style="color:#2b91af;"&gt;Func&lt;/span&gt;&amp;lt;&lt;span style="color:#2b91af;"&gt;Option&lt;/span&gt;&amp;lt;C&amp;gt;&amp;gt;&amp;gt;&amp;gt; selector, &lt;span style="color:#2b91af;"&gt;Func&lt;/span&gt;&amp;lt;T, C, R&amp;gt; result)
{
    &lt;span style="color:green;"&gt;// Left as an exercise.
&lt;/span&gt;}&lt;/pre&gt;
&lt;/blockquote&gt;

&lt;p&gt;&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;If you implement this one correctly, you will be able to run a query of the following shape:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;pre class="code"&gt;&lt;span style="color:blue;"&gt;var &lt;/span&gt;res = (&lt;span style="color:blue;"&gt;from &lt;/span&gt;x &lt;span style="color:blue;"&gt;in &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;Enumerable&lt;/span&gt;.Range(1, 5).AsFEnumerable()
           &lt;span style="color:blue;"&gt;from &lt;/span&gt;y &lt;span style="color:blue;"&gt;in &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;Enumerable&lt;/span&gt;.Range(1, x).AsFEnumerable()
           &lt;span style="color:blue;"&gt;select new string&lt;/span&gt;((&lt;span style="color:blue;"&gt;char&lt;/span&gt;)(&lt;span style="color:#a31515;"&gt;&amp;#39;a&amp;#39; &lt;/span&gt;+ x - 1), y)).AsEnumerable();

&lt;span style="color:blue;"&gt;foreach &lt;/span&gt;(&lt;span style="color:blue;"&gt;var &lt;/span&gt;item &lt;span style="color:blue;"&gt;in &lt;/span&gt;res)
    &lt;span style="color:#2b91af;"&gt;Console&lt;/span&gt;.WriteLine(item);&lt;/pre&gt;
&lt;/blockquote&gt;

&lt;p&gt;&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;This will print the following output:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;a
    &lt;br /&gt;b

    &lt;br /&gt;bb

    &lt;br /&gt;c

    &lt;br /&gt;cc

    &lt;br /&gt;ccc

    &lt;br /&gt;d

    &lt;br /&gt;dd

    &lt;br /&gt;ddd

    &lt;br /&gt;dddd

    &lt;br /&gt;e

    &lt;br /&gt;ee

    &lt;br /&gt;eee

    &lt;br /&gt;eeee

    &lt;br /&gt;eeeee&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;Finally, just to go nuts with some back-and-forth transitioning between all worlds (as shown in our diagram before), an all-inclusive sample mixing all sorts of execution:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;pre class="code"&gt;&lt;span style="color:blue;"&gt;var &lt;/span&gt;res = (&lt;span style="color:blue;"&gt;from &lt;/span&gt;y &lt;span style="color:blue;"&gt;in
               &lt;/span&gt;(&lt;span style="color:blue;"&gt;from &lt;/span&gt;x &lt;span style="color:blue;"&gt;in &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;Enumerable&lt;/span&gt;.Range(0, 20).AsFEnumerable()
                &lt;span style="color:blue;"&gt;where &lt;/span&gt;x % 2 == 0
                &lt;span style="color:blue;"&gt;select &lt;/span&gt;x + 1).AsEnumerable()
               .ToObservable() &lt;span style="color:green;"&gt;// Rx
               &lt;/span&gt;.AsFObservable()
           &lt;span style="color:blue;"&gt;where &lt;/span&gt;y % 3 == 0
           &lt;span style="color:blue;"&gt;select &lt;/span&gt;y * 2)
          .AsObservable()
          .ToEnumerable(); &lt;span style="color:green;"&gt;// Rx

&lt;/span&gt;&lt;span style="color:blue;"&gt;foreach &lt;/span&gt;(&lt;span style="color:blue;"&gt;var &lt;/span&gt;item &lt;span style="color:blue;"&gt;in &lt;/span&gt;res)
    &lt;span style="color:#2b91af;"&gt;Console&lt;/span&gt;.WriteLine(item);&lt;/pre&gt;
  &lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;&lt;/blockquote&gt;

&lt;p&gt;The interested reader is invited to create short-circuiting operators to provide a direct path for .AsEnumerable().ToObservable().AsFObservable() and .AsObservable().ToEnumerable().AsFEnumerable(). Refer back to the diagram to see where those operators’ corresponding arrows occur.&lt;/p&gt;

&lt;p&gt;&amp;#160;&lt;/p&gt;

&lt;h1&gt;Fueling Range and Sum with Ana and Cata&lt;/h1&gt;

&lt;p&gt;To conclude this post, let’s also have a look at how to derive constructor and aggregator operators from our Ana and Cata primitives. As a sequence constructor we’ll consider Range and for the aggregator we’ll consider Sum. Let’s start with Range in terms if Ana:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;pre class="code"&gt;&lt;span style="color:blue;"&gt;public static &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;Func&lt;/span&gt;&amp;lt;&lt;span style="color:#2b91af;"&gt;Func&lt;/span&gt;&amp;lt;&lt;span style="color:#2b91af;"&gt;Option&lt;/span&gt;&amp;lt;&lt;span style="color:blue;"&gt;int&lt;/span&gt;&amp;gt;&amp;gt;&amp;gt; Range(&lt;span style="color:blue;"&gt;int &lt;/span&gt;from, &lt;span style="color:blue;"&gt;int &lt;/span&gt;length)
{
    &lt;span style="color:blue;"&gt;return &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;FEnumerable&lt;/span&gt;.Ana&amp;lt;&lt;span style="color:blue;"&gt;int&lt;/span&gt;&amp;gt;(from, x =&amp;gt; x &amp;lt; from + length, x =&amp;gt; x + 1);
}&lt;/pre&gt;
  &lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;&lt;/blockquote&gt;

&lt;p&gt;and (again exactly the same code thanks to the shared primitives)&lt;/p&gt;

&lt;blockquote&gt;
  &lt;pre class="code"&gt;&lt;span style="color:blue;"&gt;public static &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;Action&lt;/span&gt;&amp;lt;&lt;span style="color:#2b91af;"&gt;Action&lt;/span&gt;&amp;lt;&lt;span style="color:#2b91af;"&gt;Option&lt;/span&gt;&amp;lt;&lt;span style="color:blue;"&gt;int&lt;/span&gt;&amp;gt;&amp;gt;&amp;gt; Range(&lt;span style="color:blue;"&gt;int &lt;/span&gt;from, &lt;span style="color:blue;"&gt;int &lt;/span&gt;length)
{
    &lt;span style="color:blue;"&gt;return &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;FObservable&lt;/span&gt;.Ana&amp;lt;&lt;span style="color:blue;"&gt;int&lt;/span&gt;&amp;gt;(from, x =&amp;gt; x &amp;lt; from + length, x =&amp;gt; x + 1);
}&lt;/pre&gt;
&lt;/blockquote&gt;

&lt;p&gt;&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;Now we can get rid of the AsFEnumerable() use in our samples when creating a range and construct our range sequence immediately in our world (similar example for FObservable of course):&lt;/p&gt;

&lt;blockquote&gt;
  &lt;pre class="code"&gt;&lt;span style="color:blue;"&gt;var &lt;/span&gt;res = (&lt;span style="color:blue;"&gt;from &lt;/span&gt;x &lt;span style="color:blue;"&gt;in &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;FEnumerableEx&lt;/span&gt;.Range(0, 10)
           &lt;span style="color:blue;"&gt;where &lt;/span&gt;x % 2 == 0
           &lt;span style="color:blue;"&gt;select &lt;/span&gt;x + 1).AsEnumerable();

&lt;span style="color:blue;"&gt;foreach &lt;/span&gt;(&lt;span style="color:blue;"&gt;var &lt;/span&gt;x &lt;span style="color:blue;"&gt;in &lt;/span&gt;res)
    &lt;span style="color:#2b91af;"&gt;Console&lt;/span&gt;.WriteLine(x);&lt;/pre&gt;
  &lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;&lt;/blockquote&gt;

&lt;p&gt;As an exercise, also abstract the AsEnumerable call followed by foreach into a &lt;a href="http://blogs.bartdesmet.net/blogs/bart/archive/2009/12/26/more-linq-with-system-interactive-the-ultimate-imperative.aspx"&gt;Run method&lt;/a&gt;, as seen in System.Interactive, so that you can write the code below. Implement this operator in terms of Cata (!):&lt;/p&gt;

&lt;blockquote&gt;
  &lt;pre class="code"&gt;(&lt;span style="color:blue;"&gt;from &lt;/span&gt;x &lt;span style="color:blue;"&gt;in &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;FEnumerableEx&lt;/span&gt;.Range(0, 10)
 &lt;span style="color:blue;"&gt;where &lt;/span&gt;x % 2 == 0
 &lt;span style="color:blue;"&gt;select &lt;/span&gt;x + 1).Run(
     &lt;span style="color:#2b91af;"&gt;Console&lt;/span&gt;.WriteLine
);&lt;/pre&gt;
  &lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;&lt;/blockquote&gt;

&lt;p&gt;(Question: could you benefit from such an operator in FObservable as well?)&lt;/p&gt;

&lt;p&gt;For the Sum realization we can use Cata:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;pre class="code"&gt;&lt;span style="color:blue;"&gt;public static int &lt;/span&gt;Sum(&lt;span style="color:blue;"&gt;this &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;Func&lt;/span&gt;&amp;lt;&lt;span style="color:#2b91af;"&gt;Func&lt;/span&gt;&amp;lt;&lt;span style="color:#2b91af;"&gt;Option&lt;/span&gt;&amp;lt;&lt;span style="color:blue;"&gt;int&lt;/span&gt;&amp;gt;&amp;gt;&amp;gt; source)
{
    &lt;span style="color:blue;"&gt;return &lt;/span&gt;source.Cata(0, (sum, x) =&amp;gt; sum + x);
}&lt;/pre&gt;
  &lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;&lt;/blockquote&gt;

&lt;p&gt;and&lt;/p&gt;

&lt;blockquote&gt;
  &lt;pre class="code"&gt;&lt;span style="color:blue;"&gt;public static int &lt;/span&gt;Sum(&lt;span style="color:blue;"&gt;this &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;Action&lt;/span&gt;&amp;lt;&lt;span style="color:#2b91af;"&gt;Action&lt;/span&gt;&amp;lt;&lt;span style="color:#2b91af;"&gt;Option&lt;/span&gt;&amp;lt;&lt;span style="color:blue;"&gt;int&lt;/span&gt;&amp;gt;&amp;gt;&amp;gt; source)
{
    &lt;span style="color:blue;"&gt;return &lt;/span&gt;source.Cata(0, (sum, x) =&amp;gt; sum + x);
}&lt;/pre&gt;
  &lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;&lt;/blockquote&gt;

&lt;p&gt;The following example illustrates how to sum 1 to 10 using Range and Sum:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;pre class="code"&gt;&lt;span style="color:#2b91af;"&gt;Console&lt;/span&gt;.WriteLine(&lt;span style="color:#2b91af;"&gt;FEnumerableEx&lt;/span&gt;.Range(1, 10).Sum());
&lt;span style="color:#2b91af;"&gt;Console&lt;/span&gt;.WriteLine(&lt;span style="color:#2b91af;"&gt;FObservableEx&lt;/span&gt;.Range(1, 10).Sum());&lt;/pre&gt;
&lt;/blockquote&gt;

&lt;p&gt;&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;Both print 55 just fine.&lt;/p&gt;

&lt;p&gt;Implement more aggregation operators as found in the Standard Query Operators. Also think about how to implement those over nullable value types (e.g. Sum with int?). Could you reuse Option&amp;lt;T&amp;gt; as an alternative to nullables? Could you reuse monadic computation to carry out nullable arithmetic (tip: the &lt;a href="http://www.haskell.org/all_about_monads/html/maybemonad.html"&gt;Maybe monad&lt;/a&gt;)? A few aggregates that some people don’t see as aggregates include All, Any, First, Last, ElementAt, and more. Don’t forget to implement those either (most of them should be a one-liner making a single call to Cata). As an additional caveat, the following implementation of Average is inadequate (why?):&lt;/p&gt;

&lt;blockquote&gt;
  &lt;pre class="code"&gt;&lt;span style="color:blue;"&gt;public static double &lt;/span&gt;Average(&lt;span style="color:blue;"&gt;this &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;Func&lt;/span&gt;&amp;lt;&lt;span style="color:#2b91af;"&gt;Func&lt;/span&gt;&amp;lt;&lt;span style="color:#2b91af;"&gt;Option&lt;/span&gt;&amp;lt;&lt;span style="color:blue;"&gt;int&lt;/span&gt;&amp;gt;&amp;gt;&amp;gt; source)
{
    &lt;span style="color:blue;"&gt;return &lt;/span&gt;(&lt;span style="color:blue;"&gt;double&lt;/span&gt;)source.Sum() / source.Count();
}&lt;/pre&gt;
&lt;/blockquote&gt;

&lt;p&gt;&amp;#160;&lt;/p&gt;

&lt;h1&gt;Conclusion&lt;/h1&gt;

&lt;p&gt;Boiling down LINQ to its core essence can be fun and a great eye-opener to many users of the technology. While optimizations often mandate a lower degree of layering, it’s good to have an idea of the conceptual layering of various operators to see which ones are essential and which ones are not so much. If kids can build castles out of Lego blocks, sure every self-respecting developer should be able to exploit the expressive power a few primitive building blocks to create great libraries and applications. Choosing the right set of primitives can get you a long way in such a design, as illustrated in this post. Readers who can’t get enough of essential primitives and the composition thereof are cordially invited to have a go at another &lt;a href="http://blogs.bartdesmet.net/blogs/bart/archive/tags/Crazy+Sundays/default.aspx"&gt;Crazy Sunday&lt;/a&gt; post titled &lt;a href="http://blogs.bartdesmet.net/blogs/bart/archive/2009/04/27/unlambda-net-with-a-big-dose-of-c-3-0-lambdas.aspx"&gt;Unlambda .NET – With a Big Dose of C# 3.0 Lambdas&lt;/a&gt; (and many others in that category).&lt;/p&gt;

&lt;p&gt;In the continuation of my &lt;a href="http://blogs.bartdesmet.net/blogs/bart/archive/tags/Rx/default.aspx"&gt;“More LINQ with System.Interactive” series&lt;/a&gt; we’ll get back to less academic stuff with System.Interactive. And before I forget: a happy 2010!&lt;/p&gt;&lt;img src="http://blogs.bartdesmet.net/aggbug.aspx?PostID=14981" width="1" height="1"&gt;</description><category domain="http://blogs.bartdesmet.net/blogs/bart/archive/tags/LINQ/default.aspx">LINQ</category><category domain="http://blogs.bartdesmet.net/blogs/bart/archive/tags/Crazy+Sundays/default.aspx">Crazy Sundays</category><category domain="http://blogs.bartdesmet.net/blogs/bart/archive/tags/Rx/default.aspx">Rx</category></item><item><title>More LINQ with System.Interactive – More combinators for your Swiss Army Knife</title><link>http://blogs.bartdesmet.net/blogs/bart/archive/2009/12/30/more-linq-with-system-interactive-more-combinators-for-your-swiss-army-knife.aspx</link><pubDate>Wed, 30 Dec 2009 08:44:00 GMT</pubDate><guid isPermaLink="false">863c5522-913f-4a64-ac0a-bd5f05abad0f:14945</guid><dc:creator>bart</dc:creator><slash:comments>9</slash:comments><wfw:commentRss xmlns:wfw="http://wellformedweb.org/CommentAPI/">http://blogs.bartdesmet.net/blogs/bart/rsscomments.aspx?PostID=14945</wfw:commentRss><comments>http://blogs.bartdesmet.net/blogs/bart/archive/2009/12/30/more-linq-with-system-interactive-more-combinators-for-your-swiss-army-knife.aspx#comments</comments><description>&lt;p&gt;With the recent release of the &lt;a href="http://msdn.microsoft.com/en-us/devlabs/ee794896.aspx"&gt;Reactive Extensions for .NET (Rx)&lt;/a&gt; on &lt;a href="http://msdn.microsoft.com/en-us/devlabs/default.aspx"&gt;DevLabs&lt;/a&gt;, you’ll hear quite a bit about reactive programming, based on the IObservable&amp;lt;T&amp;gt; and IObserver&amp;lt;T&amp;gt; interfaces. A great amount of resources is available &lt;a href="http://channel9.msdn.com/tags/Rx/"&gt;on Channel 9&lt;/a&gt;. In this series, I’ll focus on the &lt;a href="http://channel9.msdn.com/shows/Going+Deep/Expert-to-Expert-Brian-Beckman-and-Erik-Meijer-Inside-the-NET-Reactive-Framework-Rx/"&gt;dual&lt;/a&gt; of the System.Reactive assembly, which is System.Interactive, providing a bunch of extensions to the &lt;a href="http://www.codeplex.com/LINQSQO"&gt;LINQ Standard Query Operators&lt;/a&gt; for IEnumerable&amp;lt;T&amp;gt;. In today’s installment we’ll talk about new combinator operators provided by EnumerableEx:&lt;/p&gt;  &lt;p&gt;&lt;a href="http://bartdesmet.net/images_wlw/Mor.InteractiveMorecombinatorsforyourSwi_1178/image.png"&gt;&lt;img style="border-bottom:0px;border-left:0px;display:inline;border-top:0px;border-right:0px;" title="image" border="0" alt="image" src="http://bartdesmet.net/images_wlw/Mor.InteractiveMorecombinatorsforyourSwi_1178/image_thumb.png" width="526" height="480" /&gt;&lt;/a&gt; &lt;/p&gt;  &lt;p&gt;&amp;#160;&lt;/p&gt;  &lt;h1&gt;Combine and conquer?&lt;/h1&gt;  &lt;p&gt;Combinators are at the heart of LINQ’s expressive power, allowing sequences to be combined into new ones. In earlier posts, I’ve shown the essence of monadic computation through the following illustration:&lt;/p&gt;  &lt;blockquote&gt;   &lt;p&gt;&lt;a href="http://bartdesmet.net/images_wlw/Mor.InteractiveMorecombinatorsforyourSwi_1178/image_3.png"&gt;&lt;img style="border-bottom:0px;border-left:0px;display:inline;border-top:0px;border-right:0px;" title="image" border="0" alt="image" src="http://bartdesmet.net/images_wlw/Mor.InteractiveMorecombinatorsforyourSwi_1178/image_thumb_3.png" width="640" height="236" /&gt;&lt;/a&gt; &lt;/p&gt; &lt;/blockquote&gt;  &lt;p&gt;It’s fair to say that SelectMany (or Bind) is the mother of all combinators, as many others can be derived from it (Exercise: implement Where and Select using SelectMany and a limited number of auxiliary operators like Return). In today’s post we’ll look at various new combinators added to the IEnumerable&amp;lt;T&amp;gt; set of operators.&lt;/p&gt;  &lt;p&gt;So, what’s a combinator? In one world view (the one we’re using), it’s an operator that combines one or more instances of a given entity into a new such entity. For example, in functional programming we got S, K and I combinators that act on functions:&lt;/p&gt;  &lt;blockquote&gt;   &lt;p&gt;S x y z = (x z) y z     &lt;br /&gt;K x y = x      &lt;br /&gt;I x = x&lt;/p&gt; &lt;/blockquote&gt;  &lt;p&gt;A more precise definition can be found on &lt;a title="http://en.wikipedia.org/wiki/Combinator" href="http://en.wikipedia.org/wiki/Combinator"&gt;http://en.wikipedia.org/wiki/Combinator&lt;/a&gt;, for those interested in more foundational stuff. In our case, we’ll combine one or more IEnumerable&amp;lt;T&amp;gt; instances into a new IEnumerable&amp;lt;R&amp;gt; (where R &lt;em&gt;can&lt;/em&gt; be different from T).&lt;/p&gt;  &lt;p&gt;&amp;#160;&lt;/p&gt;  &lt;h1&gt;Concat, now with more arguments&lt;/h1&gt;  &lt;p&gt;LINQ to Objects has always had a Concat operator, with the following signature:&lt;/p&gt;  &lt;blockquote&gt;   &lt;pre class="code"&gt;&lt;span style="color:blue;"&gt;public static &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;IEnumerable&lt;/span&gt;&amp;lt;TSource&amp;gt; Concat&amp;lt;TSource&amp;gt;(&lt;span style="color:blue;"&gt;this &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;IEnumerable&lt;/span&gt;&amp;lt;TSource&amp;gt; first, &lt;span style="color:#2b91af;"&gt;IEnumerable&lt;/span&gt;&amp;lt;TSource&amp;gt; second);&lt;/pre&gt;
  &lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;&lt;/blockquote&gt;

&lt;p&gt;However, this is merely a special case of a more general version of Concat, introduced in EnumerableEx:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;pre class="code"&gt;&lt;span style="color:blue;"&gt;public static &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;IEnumerable&lt;/span&gt;&amp;lt;TSource&amp;gt; Concat&amp;lt;TSource&amp;gt;(&lt;span style="color:blue;"&gt;params &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;IEnumerable&lt;/span&gt;&amp;lt;TSource&amp;gt;[] sources);
&lt;span style="color:blue;"&gt;public static &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;IEnumerable&lt;/span&gt;&amp;lt;TSource&amp;gt; Concat&amp;lt;TSource&amp;gt;(&lt;span style="color:blue;"&gt;this &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;IEnumerable&lt;/span&gt;&amp;lt;&lt;span style="color:#2b91af;"&gt;IEnumerable&lt;/span&gt;&amp;lt;TSource&amp;gt;&amp;gt; sources);&lt;/pre&gt;
  &lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;&lt;/blockquote&gt;

&lt;p&gt;The second one is the core operator we’re talking about here, with the first overload providing convenience due to the lack of a “params enumerable” feature in the language. The Concat operator is simple to understand, simply yielding all TSource objects from all sequences in the sources parameter. If an error occurs during enumeration any of the sequences, the resulting concatenated sequence is also terminated for yielding. In fact, this operator is very similar to OnErrorResumeNext where the error condition is ignored.&lt;/p&gt;

&lt;p&gt;Below is a sample illustrating the main scenarios:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;pre class="code"&gt;&lt;span style="color:blue;"&gt;new&lt;/span&gt;[] {
    &lt;span style="color:blue;"&gt;new&lt;/span&gt;[] { 1, 2 },
    &lt;span style="color:blue;"&gt;new&lt;/span&gt;[] { 3, 4 },
    &lt;span style="color:blue;"&gt;new&lt;/span&gt;[] { 5, 6 }
}
.Concat()
.Materialize(&lt;span style="color:green;"&gt;/* for pretty printing */&lt;/span&gt;)
.Run(&lt;span style="color:#2b91af;"&gt;Console&lt;/span&gt;.WriteLine);

&lt;span style="color:blue;"&gt;new&lt;/span&gt;[] {
    &lt;span style="color:blue;"&gt;new&lt;/span&gt;[] { 1, 2 },
    &lt;span style="color:blue;"&gt;new&lt;/span&gt;[] { 3, 4 }.Concat(&lt;span style="color:#2b91af;"&gt;EnumerableEx&lt;/span&gt;.Throw&amp;lt;&lt;span style="color:blue;"&gt;int&lt;/span&gt;&amp;gt;(&lt;span style="color:blue;"&gt;new &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;Exception&lt;/span&gt;())),
    &lt;span style="color:blue;"&gt;new&lt;/span&gt;[] { 5, 6 }
}
.Concat()
.Materialize(&lt;span style="color:green;"&gt;/* for pretty printing */&lt;/span&gt;)
.Run(&lt;span style="color:#2b91af;"&gt;Console&lt;/span&gt;.WriteLine);&lt;/pre&gt;
&lt;/blockquote&gt;

&lt;p&gt;&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;The first sample will print numbers 1 through 6, while the second one will print 1 through 4 and an error notification.&lt;/p&gt;

&lt;p&gt;&lt;a href="http://bartdesmet.net/images_wlw/Mor.InteractiveMorecombinatorsforyourSwi_1178/image_4.png"&gt;&lt;img style="border-bottom:0px;border-left:0px;display:inline;border-top:0px;border-right:0px;" title="image" border="0" alt="image" src="http://bartdesmet.net/images_wlw/Mor.InteractiveMorecombinatorsforyourSwi_1178/image_thumb_4.png" width="500" height="380" /&gt;&lt;/a&gt; &lt;/p&gt;

&lt;p&gt;&amp;#160;&lt;/p&gt;

&lt;p&gt;&lt;/p&gt;

&lt;h1&gt;Merge, a parallel Concat&lt;/h1&gt;

&lt;p&gt;Where Concat will proceed through the sources collection sequentially, guaranteeing in-order retrieval of data, one could get all the data from the sources in a parallel manner as well. To do so, Merge spawns workers that drain all of the sources in parallel, flattening or “sinking” all the results to the caller:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;pre class="code"&gt;&lt;span style="color:blue;"&gt;public static &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;IEnumerable&lt;/span&gt;&amp;lt;TSource&amp;gt; Merge&amp;lt;TSource&amp;gt;(&lt;span style="color:blue;"&gt;params &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;IEnumerable&lt;/span&gt;&amp;lt;TSource&amp;gt;[] sources);
&lt;span style="color:blue;"&gt;public static &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;IEnumerable&lt;/span&gt;&amp;lt;TSource&amp;gt; Merge&amp;lt;TSource&amp;gt;(&lt;span style="color:blue;"&gt;this &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;IEnumerable&lt;/span&gt;&amp;lt;&lt;span style="color:#2b91af;"&gt;IEnumerable&lt;/span&gt;&amp;lt;TSource&amp;gt;&amp;gt; sources);
&lt;span style="color:blue;"&gt;public static &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;IEnumerable&lt;/span&gt;&amp;lt;TSource&amp;gt; Merge&amp;lt;TSource&amp;gt;(&lt;span style="color:blue;"&gt;this &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;IEnumerable&lt;/span&gt;&amp;lt;TSource&amp;gt; leftSource, &lt;span style="color:#2b91af;"&gt;IEnumerable&lt;/span&gt;&amp;lt;TSource&amp;gt; rightSource);&lt;/pre&gt;
  &lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;&lt;/blockquote&gt;

&lt;p&gt;The three overloads share the same signatures as the Concat equivalents, with the second one being the most general overload again. The same sample as for Concat can be used to illustrate the working:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;pre class="code"&gt;&lt;span style="color:blue;"&gt;new&lt;/span&gt;[] {
    &lt;span style="color:blue;"&gt;new&lt;/span&gt;[] { 1, 2 },
    &lt;span style="color:blue;"&gt;new&lt;/span&gt;[] { 3, 4 },
    &lt;span style="color:blue;"&gt;new&lt;/span&gt;[] { 5, 6 }
}
.Merge()
.Materialize(&lt;span style="color:green;"&gt;/* for pretty printing */&lt;/span&gt;)
.Run(&lt;span style="color:#2b91af;"&gt;Console&lt;/span&gt;.WriteLine);

&lt;span style="color:blue;"&gt;new&lt;/span&gt;[] {
    &lt;span style="color:blue;"&gt;new&lt;/span&gt;[] { 1, 2 },
    &lt;span style="color:blue;"&gt;new&lt;/span&gt;[] { 3, 4 }.Concat(&lt;span style="color:#2b91af;"&gt;EnumerableEx&lt;/span&gt;.Throw&amp;lt;&lt;span style="color:blue;"&gt;int&lt;/span&gt;&amp;gt;(&lt;span style="color:blue;"&gt;new &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;Exception&lt;/span&gt;())),
    &lt;span style="color:blue;"&gt;new&lt;/span&gt;[] { 5, 6 }
}
.Merge()
.Materialize(&lt;span style="color:green;"&gt;/* for pretty printing */&lt;/span&gt;)
.Run(&lt;span style="color:#2b91af;"&gt;Console&lt;/span&gt;.WriteLine);&lt;/pre&gt;
&lt;/blockquote&gt;

&lt;p&gt;&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;What the results are will depend on the mood of your task scheduler. Either way, for the first sample you should get to see all of the numbers from 1 through 6 getting printed, in any order (though 1 will come before 2, 3 before 4 and 5 before 6). On my machine I got 1, 3, 5, 4, 2, 6 in my first run. For the second sample, it’s entirely possible to see 5 and 6 getting printed before the exception for the second source is reached. But then that’s what you expect from parallel computation, don’t you?&lt;/p&gt;

&lt;p&gt;Merge can speed up your data retrieval operations significantly, if you don’t care about the order in which results are returned. For example, you could cause two LINQ to SQL queries that provide stock quotes to run in parallel by using Merge, followed by a client-side duplicate entry elimination technique:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;pre class="code"&gt;&lt;span style="color:blue;"&gt;var &lt;/span&gt;stocks =
    &lt;span style="color:blue;"&gt;from &lt;/span&gt;quote &lt;span style="color:blue;"&gt;in
        &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;EnumerableEx&lt;/span&gt;.Merge(
            (&lt;span style="color:blue;"&gt;from &lt;/span&gt;quote &lt;span style="color:blue;"&gt;in &lt;/span&gt;t1 &lt;span style="color:blue;"&gt;select &lt;/span&gt;quote).Do(q =&amp;gt; &lt;span style="color:#2b91af;"&gt;Console&lt;/span&gt;.WriteLine(&lt;span style="color:#a31515;"&gt;&amp;quot;t1: &amp;quot; &lt;/span&gt;+ q)),
            (&lt;span style="color:blue;"&gt;from &lt;/span&gt;quote &lt;span style="color:blue;"&gt;in &lt;/span&gt;t2 &lt;span style="color:blue;"&gt;select &lt;/span&gt;quote).Do(q =&amp;gt; &lt;span style="color:#2b91af;"&gt;Console&lt;/span&gt;.WriteLine(&lt;span style="color:#a31515;"&gt;&amp;quot;t2: &amp;quot; &lt;/span&gt;+ q))
        )
    &lt;span style="color:blue;"&gt;group &lt;/span&gt;quote &lt;span style="color:blue;"&gt;by &lt;/span&gt;quote.Symbol &lt;span style="color:blue;"&gt;into &lt;/span&gt;g
    &lt;span style="color:blue;"&gt;select new &lt;/span&gt;{ g.Key, Price = g.Average(p =&amp;gt; p.Price) };

stocks.Run(&lt;span style="color:#2b91af;"&gt;Console&lt;/span&gt;.WriteLine);&lt;/pre&gt;
  &lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;&lt;/blockquote&gt;

&lt;p&gt;Results could look as follows, with the main idea being the parallel retrieval of both query results:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;Query: SELECT Symbol, Price FROM Trader1
    &lt;br /&gt;Query: SELECT Symbol, Price FROM Trader2

    &lt;br /&gt;t2: { Symbol = MSFT, Price = 30.94 }

    &lt;br /&gt;t1: { Symbol = MSFT, Price = 30.99 }

    &lt;br /&gt;t1: { Symbol = ORCL, Price = 24.92 }

    &lt;br /&gt;t1: { Symbol = GOOG, Price = 618.35 }

    &lt;br /&gt;t1: { Symbol = AAPL, Price = 209.10 }

    &lt;br /&gt;t2: { Symbol = ORCL, Price = 25.06 }

    &lt;br /&gt;t2: { Symbol = GOOG, Price = 610.25 }

    &lt;br /&gt;t2: { Symbol = AAPL, Price = 204.99 }

    &lt;br /&gt;{ Key = MSFT, Price = 30.965 }

    &lt;br /&gt;{ Key = ORCL, Price = 24.99 }

    &lt;br /&gt;{ Key = GOOG, Price = 614.30 }

    &lt;br /&gt;{ Key = AAPL, Price = 207.045 }&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;&lt;a href="http://bartdesmet.net/images_wlw/Mor.InteractiveMorecombinatorsforyourSwi_1178/image_5.png"&gt;&lt;img style="border-bottom:0px;border-left:0px;display:inline;border-top:0px;border-right:0px;" title="image" border="0" alt="image" src="http://bartdesmet.net/images_wlw/Mor.InteractiveMorecombinatorsforyourSwi_1178/image_thumb_5.png" width="500" height="380" /&gt;&lt;/a&gt; &lt;/p&gt;

&lt;p&gt;(Note: behavior in face of an exception will depend on timing and is not included in the diagram.)&lt;/p&gt;

&lt;p&gt;&amp;#160;&lt;/p&gt;

&lt;h1&gt;Amb, a racing game&lt;/h1&gt;

&lt;p&gt;Amb is the &lt;em&gt;ambiguous&lt;/em&gt; operator as &lt;a href="http://citeseerx.ist.psu.edu/viewdoc/summary?doi=10.1.1.55.8479"&gt;introduced by McCarthy in 1963&lt;/a&gt;. Because of its nostalgic background, it’s been chosen to preserve the name as-is instead of expanding it. What’s so ambiguous about this operator? Well, the idea is that Amb allows two sequences to race to provide the first result causing the winning sequence to be elected as the one providing the resulting sequence from the operator call. The operator’s signatures make this clear:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;pre class="code"&gt;&lt;span style="color:blue;"&gt;public static &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;IEnumerable&lt;/span&gt;&amp;lt;TSource&amp;gt; Amb&amp;lt;TSource&amp;gt;(&lt;span style="color:blue;"&gt;params &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;IEnumerable&lt;/span&gt;&amp;lt;TSource&amp;gt;[] sources);
&lt;span style="color:blue;"&gt;public static &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;IEnumerable&lt;/span&gt;&amp;lt;TSource&amp;gt; Amb&amp;lt;TSource&amp;gt;(&lt;span style="color:blue;"&gt;this &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;IEnumerable&lt;/span&gt;&amp;lt;&lt;span style="color:#2b91af;"&gt;IEnumerable&lt;/span&gt;&amp;lt;TSource&amp;gt;&amp;gt; sources);
&lt;span style="color:blue;"&gt;public static &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;IEnumerable&lt;/span&gt;&amp;lt;TSource&amp;gt; Amb&amp;lt;TSource&amp;gt;(&lt;span style="color:blue;"&gt;this &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;IEnumerable&lt;/span&gt;&amp;lt;TSource&amp;gt; leftSource, &lt;span style="color:#2b91af;"&gt;IEnumerable&lt;/span&gt;&amp;lt;TSource&amp;gt; rightSource);&lt;/pre&gt;
  &lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;&lt;/blockquote&gt;

&lt;p&gt;Again, the overloads are threesome, just like Concat and Merge. To provide a sample of the operator’s behavior, use the following simple implementation of a Delay operator:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;pre class="code"&gt;&lt;span style="color:blue;"&gt;public static &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;IEnumerable&lt;/span&gt;&amp;lt;TSource&amp;gt; Delay&amp;lt;TSource&amp;gt;(&lt;span style="color:blue;"&gt;this &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;IEnumerable&lt;/span&gt;&amp;lt;TSource&amp;gt; source, &lt;span style="color:blue;"&gt;int &lt;/span&gt;delay)
{
    &lt;span style="color:blue;"&gt;return &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;EnumerableEx&lt;/span&gt;.Defer(() =&amp;gt; { &lt;span style="color:#2b91af;"&gt;Thread&lt;/span&gt;.Sleep(delay); &lt;span style="color:blue;"&gt;return &lt;/span&gt;source; });
}&lt;/pre&gt;
&lt;/blockquote&gt;

&lt;p&gt;&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;Now we can write the following two test cases:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;pre class="code"&gt;&lt;span style="color:blue;"&gt;var &lt;/span&gt;src1 = &lt;span style="color:blue;"&gt;new&lt;/span&gt;[] { 1, 2 }.Delay(300);
&lt;span style="color:blue;"&gt;var &lt;/span&gt;src2 = &lt;span style="color:blue;"&gt;new&lt;/span&gt;[] { 3, 4 }.Delay(400);
src1.Amb(src2).Run(&lt;span style="color:#2b91af;"&gt;Console&lt;/span&gt;.WriteLine);

&lt;span style="color:blue;"&gt;var &lt;/span&gt;src3 = &lt;span style="color:blue;"&gt;new&lt;/span&gt;[] { 5, 6 }.Delay(400);
&lt;span style="color:blue;"&gt;var &lt;/span&gt;src4 = &lt;span style="color:blue;"&gt;new&lt;/span&gt;[] { 7, 8 }.Delay(300);
src3.Amb(src4).Run(&lt;span style="color:#2b91af;"&gt;Console&lt;/span&gt;.WriteLine);&lt;/pre&gt;
&lt;/blockquote&gt;

&lt;p&gt;&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;The expected result will be that src1 and src4 win their Amb battles against src2 and src3, respectively. One practical use for this operator is to have two or more redundant data sources, all containing the same data, fight to provide the quickest answer to a query. Here’s a sample illustrating this:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;pre class="code"&gt;&lt;span style="color:blue;"&gt;var &lt;/span&gt;stocks =
&lt;span style="color:#2b91af;"&gt;    EnumerableEx&lt;/span&gt;.Amb(
        (&lt;span style="color:blue;"&gt;from &lt;/span&gt;quote &lt;span style="color:blue;"&gt;in &lt;/span&gt;t1 &lt;span style="color:blue;"&gt;select &lt;/span&gt;quote).Do(q =&amp;gt; &lt;span style="color:#2b91af;"&gt;Console&lt;/span&gt;.WriteLine(&lt;span style="color:#a31515;"&gt;&amp;quot;t1: &amp;quot; &lt;/span&gt;+ q)),
        (&lt;span style="color:blue;"&gt;from &lt;/span&gt;quote &lt;span style="color:blue;"&gt;in &lt;/span&gt;t2 &lt;span style="color:blue;"&gt;select &lt;/span&gt;quote).Do(q =&amp;gt; &lt;span style="color:#2b91af;"&gt;Console&lt;/span&gt;.WriteLine(&lt;span style="color:#a31515;"&gt;&amp;quot;t2: &amp;quot; &lt;/span&gt;+ q))
    );

stocks.Run(&lt;span style="color:#2b91af;"&gt;Console&lt;/span&gt;.WriteLine);&lt;/pre&gt;
  &lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;&lt;/blockquote&gt;

&lt;p&gt;Results could look as follows, assuming t2 was the quickest to provide an answer:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;Query: SELECT Symbol, Price FROM Trader1
    &lt;br /&gt;Query: SELECT Symbol, Price FROM Trader2

    &lt;br /&gt;t2: { Symbol = MSFT, Price = 30.94 }

    &lt;br /&gt;t2: { Symbol = ORCL, Price = 25.06 }

    &lt;br /&gt;t2: { Symbol = GOOG, Price = 610.25 }

    &lt;br /&gt;t2: { Symbol = AAPL, Price = 204.99 }

    &lt;br /&gt;{ Key = MSFT, Price = 30.94 }

    &lt;br /&gt;{ Key = ORCL, Price = 25.06 }

    &lt;br /&gt;{ Key = GOOG, Price = 610.25 }

    &lt;br /&gt;{ Key = AAPL, Price = 204.99 }&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;&lt;a href="http://bartdesmet.net/images_wlw/Mor.InteractiveMorecombinatorsforyourSwi_1178/image_6.png"&gt;&lt;img style="border-bottom:0px;border-left:0px;display:inline;border-top:0px;border-right:0px;" title="image" border="0" alt="image" src="http://bartdesmet.net/images_wlw/Mor.InteractiveMorecombinatorsforyourSwi_1178/image_thumb_6.png" width="500" height="380" /&gt;&lt;/a&gt; &lt;/p&gt;

&lt;p&gt;&lt;/p&gt;

&lt;p&gt;&lt;/p&gt;

&lt;p&gt;&amp;#160;&lt;/p&gt;

&lt;h1&gt;Repeat, again and (maybe) again&lt;/h1&gt;

&lt;p&gt;The purpose of Repeat is self-explanatory and could be seen as a constructor function as well. Two categories of overloads exists: one that takes a single element and an optional repeat count (unspecified = infinite) and another that takes a sequence and an optional repeat count. While the former is more of a constructor, the latter is more of a combinator over a single input sequence:&lt;/p&gt;

&lt;pre class="code"&gt;&lt;span style="color:green;"&gt;        &lt;/span&gt;&lt;span style="color:blue;"&gt;public static &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;IEnumerable&lt;/span&gt;&amp;lt;TSource&amp;gt; Repeat&amp;lt;TSource&amp;gt;(&lt;span style="color:blue;"&gt;this &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;IEnumerable&lt;/span&gt;&amp;lt;TSource&amp;gt; source);
&lt;span style="color:green;"&gt;        &lt;/span&gt;&lt;span style="color:blue;"&gt;public static &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;IEnumerable&lt;/span&gt;&amp;lt;TSource&amp;gt; Repeat&amp;lt;TSource&amp;gt;(TSource value);
&lt;span style="color:green;"&gt;        &lt;/span&gt;&lt;span style="color:blue;"&gt;public static &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;IEnumerable&lt;/span&gt;&amp;lt;TSource&amp;gt; Repeat&amp;lt;TSource&amp;gt;(&lt;span style="color:blue;"&gt;this &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;IEnumerable&lt;/span&gt;&amp;lt;TSource&amp;gt; source, &lt;span style="color:blue;"&gt;int &lt;/span&gt;repeatCount);
&lt;span style="color:green;"&gt;        &lt;/span&gt;&lt;span style="color:blue;"&gt;public static &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;IEnumerable&lt;/span&gt;&amp;lt;TSource&amp;gt; Repeat&amp;lt;TSource&amp;gt;(TSource value, &lt;span style="color:blue;"&gt;int &lt;/span&gt;repeatCount);&lt;/pre&gt;
&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;

&lt;p&gt;Samples don’t need much further explanation either:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;pre class="code"&gt;&lt;span style="color:#2b91af;"&gt;EnumerableEx&lt;/span&gt;.Repeat(1).Take(5).Run(&lt;span style="color:#2b91af;"&gt;Console&lt;/span&gt;.WriteLine);
&lt;span style="color:#2b91af;"&gt;EnumerableEx&lt;/span&gt;.Repeat(2, 5).Run(&lt;span style="color:#2b91af;"&gt;Console&lt;/span&gt;.WriteLine);

&lt;span style="color:blue;"&gt;new&lt;/span&gt;[] { 3, 4 }.Repeat().Take(4).Run(&lt;span style="color:#2b91af;"&gt;Console&lt;/span&gt;.WriteLine);
&lt;span style="color:blue;"&gt;new&lt;/span&gt;[] { 5, 6 }.Repeat(2).Run(&lt;span style="color:#2b91af;"&gt;Console&lt;/span&gt;.WriteLine);&lt;/pre&gt;
&lt;/blockquote&gt;

&lt;p&gt;It goes almost without saying that an input sequence causing an exception will also terminate the enumeration of a repeated form of the same sequence:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;pre class="code"&gt;&lt;span style="color:blue;"&gt;new&lt;/span&gt;[] { 5, 6 }.Concat(&lt;span style="color:#2b91af;"&gt;EnumerableEx&lt;/span&gt;.Throw&amp;lt;&lt;span style="color:blue;"&gt;int&lt;/span&gt;&amp;gt;(&lt;span style="color:blue;"&gt;new &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;Exception&lt;/span&gt;())).Repeat(2).Run(&lt;span style="color:#2b91af;"&gt;Console&lt;/span&gt;.WriteLine);&lt;/pre&gt;
  &lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;&lt;/blockquote&gt;

&lt;p&gt;&lt;a href="http://bartdesmet.net/images_wlw/Mor.InteractiveMorecombinatorsforyourSwi_1178/image_7.png"&gt;&lt;img style="border-bottom:0px;border-left:0px;display:inline;border-top:0px;border-right:0px;" title="image" border="0" alt="image" src="http://bartdesmet.net/images_wlw/Mor.InteractiveMorecombinatorsforyourSwi_1178/image_thumb_7.png" width="500" height="380" /&gt;&lt;/a&gt; &lt;/p&gt;

&lt;p&gt;&amp;#160;&lt;/p&gt;

&lt;h1&gt;Zip ‘em together&lt;/h1&gt;

&lt;p&gt;Introduced in .NET 4.0, I’ve covered the new Zip operator already in my earlier post on &lt;a href="http://community.bartdesmet.net/blogs/bart/archive/2008/11/03/c-4-0-feature-focus-part-3-intermezzo-linq-s-new-zip-operator.aspx"&gt;C# 4.0 Feature Focus - Part 3 - Intermezzo: LINQ&amp;#39;s new Zip operator&lt;/a&gt;. Rx ports back this operator to the .NET 3.5 System.Interactive library for consistency. In summary, Zip walks two sequences hand-in-hand, combing their respective yielded elements using a given function to produce a result. The signature is as follows:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;pre class="code"&gt;&lt;span style="color:blue;"&gt;public static &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;IEnumerable&lt;/span&gt;&amp;lt;TResult&amp;gt; Zip&amp;lt;TFirst, TSecond, TResult&amp;gt;(&lt;span style="color:blue;"&gt;this &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;IEnumerable&lt;/span&gt;&amp;lt;TFirst&amp;gt; first, &lt;span style="color:#2b91af;"&gt;IEnumerable&lt;/span&gt;&amp;lt;TSecond&amp;gt; second, &lt;span style="color:#2b91af;"&gt;Func&lt;/span&gt;&amp;lt;TFirst, TSecond, TResult&amp;gt; resultSelector);&lt;/pre&gt;
  &lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;&lt;/blockquote&gt;

&lt;p&gt;A simple example is shown below:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;pre class="code"&gt;&lt;span style="color:#2b91af;"&gt;Enumerable&lt;/span&gt;.Range(1, 26).Zip(
    &lt;span style="color:#a31515;"&gt;&amp;quot;abcdefghijklmnopqrstuvwxyz&amp;quot;&lt;/span&gt;,
    (i, c) =&amp;gt; &lt;span style="color:#a31515;"&gt;&amp;quot;alpha[&amp;quot; &lt;/span&gt;+ i + &lt;span style="color:#a31515;"&gt;&amp;quot;] = &amp;quot; &lt;/span&gt;+ c
).Run(&lt;span style="color:#2b91af;"&gt;Console&lt;/span&gt;.WriteLine);&lt;/pre&gt;
  &lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;&lt;/blockquote&gt;

&lt;p&gt;In here, the first sequence is an IEnumerable&amp;lt;int&amp;gt; and the second one is a string, hence an IEnumerable&amp;lt;char&amp;gt;. The result is a table of mappings between numbers and letters. As an exercise, implement the following overload of Select using Zip and Generate, in terms of the more commonly used overload of Select that doesn’t take a position in the selector function:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;pre class="code"&gt;&lt;span style="color:blue;"&gt;public static &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;IEnumerable&lt;/span&gt;&amp;lt;TResult&amp;gt; Select&amp;lt;TSource, TResult&amp;gt;(&lt;span style="color:blue;"&gt;this &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;IEnumerable&lt;/span&gt;&amp;lt;TSource&amp;gt; source, &lt;span style="color:#2b91af;"&gt;Func&lt;/span&gt;&amp;lt;TSource, &lt;span style="color:blue;"&gt;int&lt;/span&gt;, TResult&amp;gt; selector);&lt;/pre&gt;
  &lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;&lt;/blockquote&gt;

&lt;p&gt;One thing that’s interesting about the interactive version of Zip is its left-to-right characteristic with regards to enumeration of first and second. Internally, it does something along the following lines:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;&lt;font face="Courier New"&gt;&lt;font color="#0000ff"&gt;while&lt;/font&gt; (first.MoveNext() &amp;amp;&amp;amp; second.MoveNext())

      &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; …&lt;/font&gt;&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;In other words, “first” is dominant in that it can prevent a MoveNext call on second from happening, e.g. because of an exception getting thrown, non-termination (stuck forever) and termination (returning false). The following matrix shows the implications of this:&lt;/p&gt;

&lt;p&gt;&lt;a href="http://bartdesmet.net/images_wlw/Mor.InteractiveMorecombinatorsforyourSwi_1178/image_8.png"&gt;&lt;img style="border-bottom:0px;border-left:0px;display:inline;border-top:0px;border-right:0px;" title="image" border="0" alt="image" src="http://bartdesmet.net/images_wlw/Mor.InteractiveMorecombinatorsforyourSwi_1178/image_thumb_8.png" width="500" height="380" /&gt;&lt;/a&gt; &lt;/p&gt;

&lt;p&gt;It’s left as an exercise to the reader to implement the right-hand side behavior (notice the transposition symmetry!) for fun, where a Zip could fetch results from both sources simultaneously, combining their results or exceptions into produced results. What are advantages and disadvantages of such an approach? As an additional question, think about ways to detect and report an asymmetric zip, where one of both sides still has an element while the other side has signaled termination.&lt;/p&gt;

&lt;p&gt;Finally, the diagram illustrating some of the regular operations of Zip. Other combinations of behavior can be read from the matrix above.&lt;/p&gt;

&lt;p&gt;&lt;a href="http://bartdesmet.net/images_wlw/Mor.InteractiveMorecombinatorsforyourSwi_1178/image_9.png"&gt;&lt;img style="border-bottom:0px;border-left:0px;display:inline;border-top:0px;border-right:0px;" title="image" border="0" alt="image" src="http://bartdesmet.net/images_wlw/Mor.InteractiveMorecombinatorsforyourSwi_1178/image_thumb_9.png" width="500" height="380" /&gt;&lt;/a&gt; &lt;/p&gt;

&lt;p&gt;&amp;#160;&lt;/p&gt;

&lt;h1&gt;Scan, a running aggregation operator&lt;/h1&gt;

&lt;p&gt;Readers familiar with the LINQ to Objects APIs will know about the Aggregate operator, which we also mentioned before when talking about the new Generate operator (as the opposite of Aggregate). Aggregate “folds” or reduces a sequence of elements into a single value, eating the elements one by one using some specified function. However, sometimes you may not want to loose the intermediate results, e.g. if you want to compute a running sum or so. Scan allows you to do so:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;pre class="code"&gt;&lt;span style="color:blue;"&gt;public static &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;IEnumerable&lt;/span&gt;&amp;lt;TSource&amp;gt; Scan&amp;lt;TSource&amp;gt;(&lt;span style="color:blue;"&gt;this &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;IEnumerable&lt;/span&gt;&amp;lt;TSource&amp;gt; source, &lt;span style="color:#2b91af;"&gt;Func&lt;/span&gt;&amp;lt;TSource, TSource, TSource&amp;gt; accumulator);
&lt;span style="color:blue;"&gt;public static &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;IEnumerable&lt;/span&gt;&amp;lt;TAccumulate&amp;gt; Scan&amp;lt;TSource, TAccumulate&amp;gt;(&lt;span style="color:blue;"&gt;this &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;IEnumerable&lt;/span&gt;&amp;lt;TSource&amp;gt; source, TAccumulate seed, &lt;span style="color:#2b91af;"&gt;Func&lt;/span&gt;&amp;lt;TAccumulate, TSource, TAccumulate&amp;gt; accumulator);&lt;/pre&gt;
  &lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;&lt;/blockquote&gt;

&lt;p&gt;You’ll see big similarities with the existing Aggregate operator when looking at the signatures above, and use of the operator is straightforward as well:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;pre class="code"&gt;&lt;span style="color:#2b91af;"&gt;Enumerable&lt;/span&gt;.Range(1, 10)
.Scan((sum, i) =&amp;gt; sum + i)
.Run(&lt;span style="color:#2b91af;"&gt;Console&lt;/span&gt;.WriteLine);

&lt;span style="color:#2b91af;"&gt;Enumerable&lt;/span&gt;.Range(2, 9).Reverse()
.Scan(3628800, (prod, i) =&amp;gt; prod / i)
.Run(&lt;span style="color:#2b91af;"&gt;Console&lt;/span&gt;.WriteLine);&lt;/pre&gt;
  &lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;&lt;/blockquote&gt;

&lt;p&gt;The first sample will simply print 1, 1+2 = 3, 3+3 = 6, 6+4 = 10, … In the second sample, a seed value is used to illustrate an inverse factorial computation, dividing a given value by subsequent descending values (from 10 to 2).&lt;/p&gt;

&lt;p&gt;&lt;a href="http://bartdesmet.net/images_wlw/Mor.InteractiveMorecombinatorsforyourSwi_1178/image_10.png"&gt;&lt;img style="border-bottom:0px;border-left:0px;display:inline;border-top:0px;border-right:0px;" title="image" border="0" alt="image" src="http://bartdesmet.net/images_wlw/Mor.InteractiveMorecombinatorsforyourSwi_1178/image_thumb_10.png" width="500" height="380" /&gt;&lt;/a&gt; &lt;/p&gt;

&lt;p&gt;&amp;#160;&lt;/p&gt;

&lt;h1&gt;SelectMany&lt;/h1&gt;

&lt;p&gt;&lt;/p&gt;

&lt;p&gt;&lt;/p&gt;

&lt;p&gt;&lt;/p&gt;

&lt;p&gt;&lt;/p&gt;

&lt;p&gt;Finally, as a honor to the monadic bind operator, a new overload was added for SelectMany :-). Its signature is shown below, and it’s left to the reader to figure out what it does (simple):&lt;/p&gt;

&lt;blockquote&gt;
  &lt;pre class="code"&gt;&lt;span style="color:blue;"&gt;public static &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;IEnumerable&lt;/span&gt;&amp;lt;TOther&amp;gt; SelectMany&amp;lt;TSource, TOther&amp;gt;(&lt;span style="color:blue;"&gt;this &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;IEnumerable&lt;/span&gt;&amp;lt;TSource&amp;gt; source, &lt;span style="color:#2b91af;"&gt;IEnumerable&lt;/span&gt;&amp;lt;TOther&amp;gt; other);&lt;/pre&gt;
&lt;/blockquote&gt;

&lt;p&gt;&amp;#160;&lt;/p&gt;

&lt;h1&gt;Next on More LINQ&lt;/h1&gt;

&lt;p&gt;Functionally inspired constructs allowing to share enumerables and tame their side-effects.&lt;/p&gt;&lt;img src="http://blogs.bartdesmet.net/aggbug.aspx?PostID=14945" width="1" height="1"&gt;</description><category domain="http://blogs.bartdesmet.net/blogs/bart/archive/tags/LINQ/default.aspx">LINQ</category><category domain="http://blogs.bartdesmet.net/blogs/bart/archive/tags/Rx/default.aspx">Rx</category></item><item><title>More LINQ with System.Interactive – Exploiting the code = data relationship</title><link>http://blogs.bartdesmet.net/blogs/bart/archive/2009/12/29/more-linq-with-system-interactive-exploiting-the-code-data-relationship.aspx</link><pubDate>Tue, 29 Dec 2009 08:30:00 GMT</pubDate><guid isPermaLink="false">863c5522-913f-4a64-ac0a-bd5f05abad0f:14934</guid><dc:creator>bart</dc:creator><slash:comments>13</slash:comments><wfw:commentRss xmlns:wfw="http://wellformedweb.org/CommentAPI/">http://blogs.bartdesmet.net/blogs/bart/rsscomments.aspx?PostID=14934</wfw:commentRss><comments>http://blogs.bartdesmet.net/blogs/bart/archive/2009/12/29/more-linq-with-system-interactive-exploiting-the-code-data-relationship.aspx#comments</comments><description>&lt;p&gt;With the recent release of the &lt;a href="http://msdn.microsoft.com/en-us/devlabs/ee794896.aspx"&gt;Reactive Extensions for .NET (Rx)&lt;/a&gt; on &lt;a href="http://msdn.microsoft.com/en-us/devlabs/default.aspx"&gt;DevLabs&lt;/a&gt;, you’ll hear quite a bit about reactive programming, based on the IObservable&amp;lt;T&amp;gt; and IObserver&amp;lt;T&amp;gt; interfaces. A great amount of resources is available &lt;a href="http://channel9.msdn.com/tags/Rx/"&gt;on Channel 9&lt;/a&gt;. In this series, I’ll focus on the &lt;a href="http://channel9.msdn.com/shows/Going+Deep/Expert-to-Expert-Brian-Beckman-and-Erik-Meijer-Inside-the-NET-Reactive-Framework-Rx/"&gt;dual&lt;/a&gt; of the System.Reactive assembly, which is System.Interactive, providing a bunch of extensions to the &lt;a href="http://www.codeplex.com/LINQSQO"&gt;LINQ Standard Query Operators&lt;/a&gt; for IEnumerable&amp;lt;T&amp;gt;. In today’s installment we’ll talk about the materialization and dematerialization operators provided by EnumerableEx:&lt;/p&gt;  &lt;p&gt;&lt;a href="http://bartdesmet.net/images_wlw/Mor.InteractiveExploitingthecodedatarela_13ACD/image.png"&gt;&lt;img style="border-bottom:0px;border-left:0px;display:inline;border-top:0px;border-right:0px;" title="image" border="0" alt="image" src="http://bartdesmet.net/images_wlw/Mor.InteractiveExploitingthecodedatarela_13ACD/image_thumb.png" width="526" height="480" /&gt;&lt;/a&gt; &lt;/p&gt;  &lt;p&gt;&amp;#160;&lt;/p&gt;  &lt;h1&gt;von Neumann was right&lt;/h1&gt;  &lt;p&gt;Code and data are very similar animals, much more similar than you may expect them to be. We can approach this observation from two different angles, one being a machine-centric view. Today’s computers are realizations of von Neumann machines where instructions and data are treated on the same footage from a memory storage point of view. While this is very useful, it’s also the source of various security-related headaches such as script or SQL injection and data execution through e.g. stack overruns (Data Execution Prevention is one mitigation).&lt;/p&gt;  &lt;p&gt;Another point of view goes back to the foundational nature of programming, in particular the essentials of functional programming, where functions are used to represent data. An example are &lt;a href="http://community.bartdesmet.net/blogs/bart/archive/2009/08/17/mis-using-c-4-0-dynamic-type-free-lambda-calculus-church-numerals-and-more.aspx"&gt;Church numerals&lt;/a&gt;, which are functions that are behaviorally equivalent to natural numbers (realized by repeated application of a function, equal in number to the natural number being represented). This illustrates how something that seems exclusively code-driven can be used to represent or mimic data.&lt;/p&gt;  &lt;p&gt;If the above samples seem far-fetched or esoteric, there are a variety of more familiar grounds where the “code as data” paradigm is used or exploited. One such sample is LISP where code and data representation share the same syntactical form and where the technique of quotation can be used to represent a code snippet as data for runtime inspection and/or manipulation. This is nothing other than meta-programming in its earliest form. Today we find exactly the same principle back in C#, and other languages, through expression trees. The core property here is so-called &lt;em&gt;homo-iconicity&lt;/em&gt;, where code can be represented as data without having to resort to a different syntax (homo = same; iconic = appearance):&lt;/p&gt;  &lt;blockquote&gt;   &lt;p&gt;&lt;font face="Courier New"&gt;Func&amp;lt;int, int&amp;gt; twiceD = x =&amp;gt; x * 2;       &lt;br /&gt;Expression&amp;lt;Func&amp;lt;int, int&amp;gt;&amp;gt; twiceE = x =&amp;gt; x * 2;&lt;/font&gt;&lt;/p&gt; &lt;/blockquote&gt;  &lt;p&gt;What what does all of this have to do with enumerable sequences? Spot on! The matter is that sequences seem to be a very data-intensive concept, and sure they are. However, the behavior and realization of such sequences, e.g. through iterators, can be very code-intensive as well, to such an extent that we introduced means to deal with exceptions (Catch for instance) and termination (Repeat, restarting after completing). This reveals that it’s useful to deal with all possible &lt;em&gt;states&lt;/em&gt; a sequence can go through. Guess what, state is data.&lt;/p&gt;  &lt;p&gt;&amp;#160;&lt;/p&gt;  &lt;h1&gt;The holy trinity of IEnumerator&amp;lt;T&amp;gt; and IObserver&amp;lt;T&amp;gt; states&lt;/h1&gt;  &lt;p&gt;In all the marble diagrams I’ve shown before, there was a legend consisting of three potential states an enumerable sequence can go through as a result of iteration. Those three states reflect possible responses to a call to MoveNext caused by the consumer of the sequence:&lt;/p&gt;  &lt;blockquote&gt;   &lt;p&gt;&lt;a href="http://bartdesmet.net/images_wlw/Mor.InteractiveExploitingthecodedatarela_13ACD/image_3.png"&gt;&lt;img style="border-bottom:0px;border-left:0px;display:inline;border-top:0px;border-right:0px;" title="image" border="0" alt="image" src="http://bartdesmet.net/images_wlw/Mor.InteractiveExploitingthecodedatarela_13ACD/image_thumb_3.png" width="240" height="151" /&gt;&lt;/a&gt; &lt;/p&gt; &lt;/blockquote&gt;  &lt;p&gt;In the world of IObserver&amp;lt;T&amp;gt;, the dual to IEnumerator&amp;lt;T&amp;gt; as we saw in earlier episodes, those three states are reflected in the interface definition directly, with three methods:&lt;/p&gt;  &lt;blockquote&gt;   &lt;pre class="code"&gt;&lt;span style="color:green;"&gt;// Summary:
//     Supports push-style iteration over an observable sequence.
&lt;/span&gt;&lt;span style="color:blue;"&gt;public interface &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;IObserver&lt;/span&gt;&amp;lt;T&amp;gt;
{
    &lt;span style="color:green;"&gt;// Summary:
    //     Notifies the observer of the end of the sequence.
    &lt;/span&gt;&lt;span style="color:blue;"&gt;void &lt;/span&gt;OnCompleted();
    &lt;span style="color:green;"&gt;//
    // Summary:
    //     Notifies the observer that an exception has occurred.
    &lt;/span&gt;&lt;span style="color:blue;"&gt;void &lt;/span&gt;OnError(&lt;span style="color:#2b91af;"&gt;Exception &lt;/span&gt;exception);
    &lt;span style="color:green;"&gt;//
    // Summary:
    //     Notifies the observer of a new value in the sequence.
    &lt;/span&gt;&lt;span style="color:blue;"&gt;void &lt;/span&gt;OnNext(T value);
}&lt;/pre&gt;
&lt;/blockquote&gt;

&lt;p&gt;Instead of having an observer getting called on any of those three methods, we could equally well &lt;em&gt;record&lt;/em&gt; the states “raised” by the observable, which turns calls (code) into object instances (data) of type Notification&amp;lt;T&amp;gt;. This operation is called &lt;em&gt;materialization&lt;/em&gt;. Thanks to dualization, the use of Notification&amp;lt;T&amp;gt; can be extended to the world of enumerables as well.&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;&lt;a href="http://bartdesmet.net/images_wlw/Mor.InteractiveExploitingthecodedatarela_13ACD/image_4.png"&gt;&lt;img style="border-bottom:0px;border-left:0px;display:inline;border-top:0px;border-right:0px;" title="image" border="0" alt="image" src="http://bartdesmet.net/images_wlw/Mor.InteractiveExploitingthecodedatarela_13ACD/image_thumb_4.png" width="235" height="501" /&gt;&lt;/a&gt; &lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;Notification&amp;lt;T&amp;gt; is a discriminated union with three notification kinds, reflecting the three states we talked about earlier:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;pre class="code"&gt;&lt;span style="color:blue;"&gt;public enum &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;NotificationKind
&lt;/span&gt;{
    OnNext = 0,
    OnError = 1,
    OnCompleted = 2,
}&lt;/pre&gt;
&lt;/blockquote&gt;

&lt;p&gt;&amp;#160;&lt;/p&gt;

&lt;h1&gt;It’s a material dual world&lt;/h1&gt;

&lt;p&gt;Materialization is the act of taking a plain enumerable and turning it into a data-centric view based on Notification&amp;lt;T&amp;gt;. Dematerialization reverses this operation, going back to the code-centric world. Thanks to this back-and-forth ability between the two worlds of code and data, we get the ability to use LINQ over notification sequences and put the result back into the regular familiar IEnumerable&amp;lt;T&amp;gt; world. A figure makes this clear:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;&lt;a href="http://bartdesmet.net/images_wlw/Mor.InteractiveExploitingthecodedatarela_13ACD/image_5.png"&gt;&lt;img style="border-bottom:0px;border-left:0px;display:inline;border-top:0px;border-right:0px;" title="image" border="0" alt="image" src="http://bartdesmet.net/images_wlw/Mor.InteractiveExploitingthecodedatarela_13ACD/image_thumb_5.png" width="640" height="446" /&gt;&lt;/a&gt; &lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;The power of this lies in the ability to use whatever domain is more convenient to perform operations over a sequence. Maybe you want to do thorough analysis of error conditions, corresponding to the Error notification kind, or maybe it’s more convenient to create a stream of notification objects before turning them into a “regular” sequence of objects that could exhibit certain additional behavior (like error conditions). This is exactly the same as the tricks played in various other fields, like mathematics where one can do &lt;a href="http://en.wikibooks.org/wiki/Signals_and_Systems"&gt;Fourier analysis&lt;/a&gt; either in the time of frequency domain. Sometimes one is more convenient than the other; all that counts is to know there are reliable ways to go back and forth.&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;&lt;a href="http://bartdesmet.net/images_wlw/Mor.InteractiveExploitingthecodedatarela_13ACD/image_6.png"&gt;&lt;img style="border-bottom:0px;border-left:0px;display:inline;border-top:0px;border-right:0px;" title="image" border="0" alt="image" src="http://bartdesmet.net/images_wlw/Mor.InteractiveExploitingthecodedatarela_13ACD/image_thumb_6.png" width="654" height="500" /&gt;&lt;/a&gt; &lt;/p&gt;

  &lt;p&gt;(Note: For the Queryable sample, you may want to end up in the bottom-right corner, so the AsQueryable call is often omitted.)&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;&amp;#160;&lt;/p&gt;

&lt;h1&gt;Materialize and Dematerialize&lt;/h1&gt;

&lt;p&gt;What remains to be said in this post are the signatures of the operators and a few samples. First, the signatures:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;pre class="code"&gt;&lt;span style="color:blue;"&gt;public static &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;IEnumerable&lt;/span&gt;&amp;lt;&lt;span style="color:#2b91af;"&gt;Notification&lt;/span&gt;&amp;lt;TSource&amp;gt;&amp;gt; Materialize&amp;lt;TSource&amp;gt;(&lt;span style="color:blue;"&gt;this &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;IEnumerable&lt;/span&gt;&amp;lt;TSource&amp;gt; source);&lt;br /&gt;&lt;span style="color:blue;"&gt;public static &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;IEnumerable&lt;/span&gt;&amp;lt;TSource&amp;gt; Dematerialize&amp;lt;TSource&amp;gt;(&lt;span style="color:blue;"&gt;this &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;IEnumerable&lt;/span&gt;&amp;lt;&lt;span style="color:#2b91af;"&gt;Notification&lt;/span&gt;&amp;lt;TSource&amp;gt;&amp;gt; source);&lt;/pre&gt;
&lt;/blockquote&gt;

&lt;p&gt;An example of materialization is shown below, where we take a simple range generator to materialize. We expect to see OnNext notifications for all the numeric values emitted, terminated by a single OnCompleted call:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;pre class="code"&gt;&lt;span style="color:#2b91af;"&gt;Enumerable&lt;/span&gt;.Range(1, 10)&lt;br /&gt;.Materialize()&lt;br /&gt;.Run(&lt;span style="color:#2b91af;"&gt;Console&lt;/span&gt;.WriteLine);&lt;/pre&gt;
  &lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;&lt;/blockquote&gt;

&lt;p&gt;This prints:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;OnNext(1)
    &lt;br /&gt;OnNext(2)

    &lt;br /&gt;OnNext(3)

    &lt;br /&gt;OnNext(4)

    &lt;br /&gt;OnNext(5)

    &lt;br /&gt;OnNext(6)

    &lt;br /&gt;OnNext(7)

    &lt;br /&gt;OnNext(8)

    &lt;br /&gt;OnNext(9)

    &lt;br /&gt;OnNext(10)

    &lt;br /&gt;OnCompleted()&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;A sample where an exception is triggered by the enumerator is shown below. Notice the code won’t blow up when enumerating over the materialized sequence: the exception is materialized as a passive exception object instance in an error notification.&lt;/p&gt;

&lt;blockquote&gt;
  &lt;pre class="code"&gt;&lt;span style="color:#2b91af;"&gt;Enumerable&lt;/span&gt;.Range(1, 10).Concat(&lt;span style="color:#2b91af;"&gt;EnumerableEx&lt;/span&gt;.Throw&amp;lt;&lt;span style="color:blue;"&gt;int&lt;/span&gt;&amp;gt;(&lt;span style="color:blue;"&gt;new &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;Exception&lt;/span&gt;()))
.Materialize()
.Run(&lt;span style="color:#2b91af;"&gt;Console&lt;/span&gt;.WriteLine);&lt;/pre&gt;
  &lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;&lt;/blockquote&gt;

&lt;p&gt;The result is as follows:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;OnNext(1)
    &lt;br /&gt;OnNext(2)

    &lt;br /&gt;OnNext(3)

    &lt;br /&gt;OnNext(4)

    &lt;br /&gt;OnNext(5)

    &lt;br /&gt;OnNext(6)

    &lt;br /&gt;OnNext(7)

    &lt;br /&gt;OnNext(8)

    &lt;br /&gt;OnNext(9)

    &lt;br /&gt;OnNext(10)

    &lt;br /&gt;OnError(System.Exception)&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;Starting from a plain IEnumerable&amp;lt;T&amp;gt; the grammar of notifications to be expected is as follows:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;OnNext* ( OnCompleted | OnError )?&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;In the other direction, starting from the world of IEnumerable&amp;lt;Notification&amp;lt;T&amp;gt;&amp;gt; one can write a different richer set of sequence defined by the following grammar:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;( OnNext | OnCompleted | OnError )*&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;For example:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;pre class="code"&gt;&lt;span style="color:blue;"&gt;var &lt;/span&gt;ns = &lt;span style="color:blue;"&gt;new &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;Notification&lt;/span&gt;&amp;lt;&lt;span style="color:blue;"&gt;int&lt;/span&gt;&amp;gt;[] {
    &lt;span style="color:blue;"&gt;new &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;Notification&lt;/span&gt;&amp;lt;&lt;span style="color:blue;"&gt;int&lt;/span&gt;&amp;gt;.&lt;span style="color:#2b91af;"&gt;OnNext&lt;/span&gt;(1),
    &lt;span style="color:blue;"&gt;new &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;Notification&lt;/span&gt;&amp;lt;&lt;span style="color:blue;"&gt;int&lt;/span&gt;&amp;gt;.&lt;span style="color:#2b91af;"&gt;OnNext&lt;/span&gt;(2),
    &lt;span style="color:blue;"&gt;new &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;Notification&lt;/span&gt;&amp;lt;&lt;span style="color:blue;"&gt;int&lt;/span&gt;&amp;gt;.&lt;span style="color:#2b91af;"&gt;OnCompleted&lt;/span&gt;(),
    &lt;span style="color:blue;"&gt;new &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;Notification&lt;/span&gt;&amp;lt;&lt;span style="color:blue;"&gt;int&lt;/span&gt;&amp;gt;.&lt;span style="color:#2b91af;"&gt;OnNext&lt;/span&gt;(3),
    &lt;span style="color:blue;"&gt;new &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;Notification&lt;/span&gt;&amp;lt;&lt;span style="color:blue;"&gt;int&lt;/span&gt;&amp;gt;.&lt;span style="color:#2b91af;"&gt;OnNext&lt;/span&gt;(4),
    &lt;span style="color:blue;"&gt;new &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;Notification&lt;/span&gt;&amp;lt;&lt;span style="color:blue;"&gt;int&lt;/span&gt;&amp;gt;.&lt;span style="color:#2b91af;"&gt;OnError&lt;/span&gt;(&lt;span style="color:blue;"&gt;new &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;Exception&lt;/span&gt;()),
    &lt;span style="color:blue;"&gt;new &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;Notification&lt;/span&gt;&amp;lt;&lt;span style="color:blue;"&gt;int&lt;/span&gt;&amp;gt;.&lt;span style="color:#2b91af;"&gt;OnNext&lt;/span&gt;(5),
};&lt;/pre&gt;
  &lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;&lt;/blockquote&gt;

&lt;p&gt;Dematerializing this sequence of notifications will produce an enumerable sequence that will run no further than the first OnCompleted or OnError:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;pre class="code"&gt;ns&lt;br /&gt;.Dematerialize()&lt;br /&gt;.Run(&lt;span style="color:#2b91af;"&gt;Console&lt;/span&gt;.WriteLine);&lt;/pre&gt;
  &lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;&lt;/blockquote&gt;

&lt;p&gt;This prints 1 and 2 and then terminates. The reason this can still be useful is to create a stream of notifications that will be pre-filtered before doing any dematerialization operation on it. For example, a series of batches could be represented in the following grammar:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;( OnNext* OnCompleted )*&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;If the user requests to run n batches, the first n – 1 OnCompleted notifications can be filtered out using some LINQ query expression, before doing dematerialization.&lt;/p&gt;

&lt;p&gt;Finally, a sample of some error-filtering code going back and forth between IEnumerable&amp;lt;T&amp;gt; and IEnumerable&amp;lt;Notification&amp;lt;T&amp;gt;&amp;gt; showing practical use for those operators when doing sophisticated error handling:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;pre class="code"&gt;&lt;span style="color:blue;"&gt;var &lt;/span&gt;xs1 = &lt;span style="color:blue;"&gt;new&lt;/span&gt;[] { 1, 2 }.Concat(&lt;span style="color:#2b91af;"&gt;EnumerableEx&lt;/span&gt;.Throw&amp;lt;&lt;span style="color:blue;"&gt;int&lt;/span&gt;&amp;gt;(&lt;span style="color:blue;"&gt;new &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;InvalidOperationException&lt;/span&gt;()));
&lt;span style="color:blue;"&gt;var &lt;/span&gt;xs2 = &lt;span style="color:blue;"&gt;new&lt;/span&gt;[] { 3, 4 }.Concat(&lt;span style="color:#2b91af;"&gt;EnumerableEx&lt;/span&gt;.Throw&amp;lt;&lt;span style="color:blue;"&gt;int&lt;/span&gt;&amp;gt;(&lt;span style="color:blue;"&gt;new &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;ArgumentException&lt;/span&gt;()));
&lt;span style="color:blue;"&gt;var &lt;/span&gt;xs3 = &lt;span style="color:blue;"&gt;new&lt;/span&gt;[] { 5, 6 }.Concat(&lt;span style="color:#2b91af;"&gt;EnumerableEx&lt;/span&gt;.Throw&amp;lt;&lt;span style="color:blue;"&gt;int&lt;/span&gt;&amp;gt;(&lt;span style="color:blue;"&gt;new &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;OutOfMemoryException&lt;/span&gt;()));
&lt;span style="color:blue;"&gt;var &lt;/span&gt;xs4 = &lt;span style="color:blue;"&gt;new&lt;/span&gt;[] { 7, 8 }.Concat(&lt;span style="color:#2b91af;"&gt;EnumerableEx&lt;/span&gt;.Throw&amp;lt;&lt;span style="color:blue;"&gt;int&lt;/span&gt;&amp;gt;(&lt;span style="color:blue;"&gt;new &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;ArgumentException&lt;/span&gt;()));

&lt;span style="color:blue;"&gt;var &lt;/span&gt;xss = &lt;span style="color:blue;"&gt;new&lt;/span&gt;[] { xs1, xs2, xs3, xs4 };
&lt;span style="color:blue;"&gt;var &lt;/span&gt;xns = xss.Select(xs =&amp;gt; xs&lt;strong&gt;.Materialize()&lt;/strong&gt;).Concat();

&lt;span style="color:blue;"&gt;var &lt;/span&gt;res = &lt;span style="color:blue;"&gt;from &lt;/span&gt;xn &lt;span style="color:blue;"&gt;in &lt;/span&gt;xns
          &lt;span style="color:blue;"&gt;let &lt;/span&gt;isError = xn.Kind == &lt;span style="color:#2b91af;"&gt;NotificationKind&lt;/span&gt;.OnError
          &lt;span style="color:blue;"&gt;let &lt;/span&gt;exception = isError ? ((&lt;span style="color:#2b91af;"&gt;Notification&lt;/span&gt;&amp;lt;&lt;span style="color:blue;"&gt;int&lt;/span&gt;&amp;gt;.&lt;span style="color:#2b91af;"&gt;OnError&lt;/span&gt;)xn).Exception : &lt;span style="color:blue;"&gt;null
          where &lt;/span&gt;!isError || exception &lt;span style="color:blue;"&gt;is &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;OutOfMemoryException
          &lt;/span&gt;&lt;span style="color:blue;"&gt;select &lt;/span&gt;xn;

res&lt;strong&gt;.Dematerialize()&lt;/strong&gt;.Run(&lt;span style="color:#2b91af;"&gt;Console&lt;/span&gt;.WriteLine);&lt;/pre&gt;
&lt;/blockquote&gt;

&lt;p&gt;Given some input sequences, we materialize and concatenate all of them into sequence xns. Now we write a LINQ query over the notifications to filter out exceptions, unless the exception is a critical OOM one (you could add others to this list). The result is we see 1 through 6 being printed to the screen. (Question: What’s the relationship to OnErrorResumeNext that we saw in the previous post? What’s similar, what’s different?)&lt;/p&gt;

&lt;p&gt;&amp;#160;&lt;/p&gt;

&lt;h1&gt;Exercises&lt;/h1&gt;

&lt;p&gt;As an exercise, try to implement &lt;a href="http://community.bartdesmet.net/blogs/bart/archive/2009/12/27/more-linq-with-system-interactive-exceptional-exception-handling.aspx"&gt;the following operators&lt;/a&gt; in a notification-oriented manner:&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;Catch
    &lt;br /&gt;(tip: use SelectMany and lots of conditional BLOCKED EXPRESSION&lt;/li&gt;

  &lt;li&gt;Finally
    &lt;br /&gt;(tip: use SelectMany and Defer)&lt;/li&gt;

  &lt;li&gt;OnErrorResumeNext – overload taking two IEnumerable&amp;lt;TSource&amp;gt; sequences
    &lt;br /&gt;(tip: use TakeWhile)&lt;/li&gt;

  &lt;li&gt;Retry – overload with a retry count
    &lt;br /&gt;(tip: recursion, ignore stack overflow conditions)&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;The skeleton code for those operators is shown below:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;pre class="code"&gt;&lt;span style="color:blue;"&gt;return
    &lt;/span&gt;source&lt;br /&gt;    .Materialize()&lt;br /&gt;&lt;span style="color:green;"&gt;    // Your stuff here&lt;/span&gt;&lt;br /&gt;    .Dematerialize();&lt;/pre&gt;
  &lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;&lt;/blockquote&gt;

&lt;p&gt;All-inclusive unit test:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;pre class="code"&gt;    &lt;span style="color:blue;"&gt;new&lt;/span&gt;[] { 1, 2 }
        .Finally(() =&amp;gt; &lt;span style="color:#2b91af;"&gt;Console&lt;/span&gt;.WriteLine(&lt;span style="color:#a31515;"&gt;&amp;quot;Finally inner&amp;quot;&lt;/span&gt;))
    .Concat(&lt;span style="color:#2b91af;"&gt;EnumerableEx&lt;/span&gt;.Throw&amp;lt;&lt;span style="color:blue;"&gt;int&lt;/span&gt;&amp;gt;(&lt;span style="color:blue;"&gt;new &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;InvalidOperationException&lt;/span&gt;()))
.Catch((&lt;span style="color:#2b91af;"&gt;InvalidOperationException &lt;/span&gt;_) =&amp;gt; &lt;span style="color:blue;"&gt;new&lt;/span&gt;[] { 3, 4 }.Concat(&lt;span style="color:#2b91af;"&gt;EnumerableEx&lt;/span&gt;.Throw&amp;lt;&lt;span style="color:blue;"&gt;int&lt;/span&gt;&amp;gt;(&lt;span style="color:blue;"&gt;new &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;Exception&lt;/span&gt;())))
.Finally(() =&amp;gt; &lt;span style="color:#2b91af;"&gt;Console&lt;/span&gt;.WriteLine(&lt;span style="color:#a31515;"&gt;&amp;quot;Finally outer&amp;quot;&lt;/span&gt;))
.OnErrorResumeNext(&lt;span style="color:blue;"&gt;new&lt;/span&gt;[] { 5, 6 })
.Concat(&lt;span style="color:#2b91af;"&gt;EnumerableEx&lt;/span&gt;.Throw&amp;lt;&lt;span style="color:blue;"&gt;int&lt;/span&gt;&amp;gt;(&lt;span style="color:blue;"&gt;new &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;ArgumentException&lt;/span&gt;()))
.Retry(2)
.Run(&lt;span style="color:#2b91af;"&gt;Console&lt;/span&gt;.WriteLine);&lt;/pre&gt;
  &lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;&lt;/blockquote&gt;

&lt;p&gt;This should produce the same results with the built-in operators and with your implementation of those operators. More specifically, the result has to be:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;1
    &lt;br /&gt;2

    &lt;br /&gt;Finally inner

    &lt;br /&gt;3

    &lt;br /&gt;4

    &lt;br /&gt;Finally outer

    &lt;br /&gt;5

    &lt;br /&gt;6

    &lt;br /&gt;1

    &lt;br /&gt;2

    &lt;br /&gt;Finally inner

    &lt;br /&gt;3

    &lt;br /&gt;4

    &lt;br /&gt;Finally outer

    &lt;br /&gt;5

    &lt;br /&gt;6&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;with no exception leaking to the surface in the call site (behavior of Retry after the retry count has been exceeded).&lt;/p&gt;

&lt;p&gt;&amp;#160;&lt;/p&gt;

&lt;h1&gt;Next on More LINQ&lt;/h1&gt;

&lt;p&gt;Various combinators to combine or transform existing observable sources into others.&lt;/p&gt;&lt;img src="http://blogs.bartdesmet.net/aggbug.aspx?PostID=14934" width="1" height="1"&gt;</description><category domain="http://blogs.bartdesmet.net/blogs/bart/archive/tags/LINQ/default.aspx">LINQ</category><category domain="http://blogs.bartdesmet.net/blogs/bart/archive/tags/Rx/default.aspx">Rx</category></item><item><title>More LINQ with System.Interactive – Sequences under construction</title><link>http://blogs.bartdesmet.net/blogs/bart/archive/2009/12/28/more-linq-with-system-interactive-sequences-under-construction.aspx</link><pubDate>Mon, 28 Dec 2009 09:07:00 GMT</pubDate><guid isPermaLink="false">863c5522-913f-4a64-ac0a-bd5f05abad0f:14928</guid><dc:creator>bart</dc:creator><slash:comments>9</slash:comments><wfw:commentRss xmlns:wfw="http://wellformedweb.org/CommentAPI/">http://blogs.bartdesmet.net/blogs/bart/rsscomments.aspx?PostID=14928</wfw:commentRss><comments>http://blogs.bartdesmet.net/blogs/bart/archive/2009/12/28/more-linq-with-system-interactive-sequences-under-construction.aspx#comments</comments><description>&lt;p&gt;With the recent release of the &lt;a href="http://msdn.microsoft.com/en-us/devlabs/ee794896.aspx"&gt;Reactive Extensions for .NET (Rx)&lt;/a&gt; on &lt;a href="http://msdn.microsoft.com/en-us/devlabs/default.aspx"&gt;DevLabs&lt;/a&gt;, you’ll hear quite a bit about reactive programming, based on the IObservable&amp;lt;T&amp;gt; and IObserver&amp;lt;T&amp;gt; interfaces. A great amount of resources is available &lt;a href="http://channel9.msdn.com/tags/Rx/"&gt;on Channel 9&lt;/a&gt;. In this series, I’ll focus on the &lt;a href="http://channel9.msdn.com/shows/Going+Deep/Expert-to-Expert-Brian-Beckman-and-Erik-Meijer-Inside-the-NET-Reactive-Framework-Rx/"&gt;dual&lt;/a&gt; of the System.Reactive assembly, which is System.Interactive, providing a bunch of extensions to the &lt;a href="http://www.codeplex.com/LINQSQO"&gt;LINQ Standard Query Operators&lt;/a&gt; for IEnumerable&amp;lt;T&amp;gt;. In today’s installment we’ll talk about constructor operators provided by EnumerableEx:&lt;/p&gt;  &lt;p&gt;&lt;a href="http://bartdesmet.net/images_wlw/Mor.InteractiveSequencesunderconstructio_11DD/image.png"&gt;&lt;img style="border-right-width:0px;display:inline;border-top-width:0px;border-bottom-width:0px;border-left-width:0px;" title="image" border="0" alt="image" src="http://bartdesmet.net/images_wlw/Mor.InteractiveSequencesunderconstructio_11DD/image_thumb.png" width="526" height="480" /&gt;&lt;/a&gt; &lt;/p&gt;  &lt;p&gt;&amp;#160;&lt;/p&gt;  &lt;h1&gt;Constructing sequences&lt;/h1&gt;  &lt;p&gt;In order to perform operations over sequences using various combinators and operators, it’s obviously a prerequisite to have such sequences available. While collection types in the .NET Framework implement IEnumerable&amp;lt;T&amp;gt; (or the non-generic counterpart, bridgeable to LINQ using the Cast&amp;lt;T&amp;gt; Standard Query Operator), one often wants to construct sequences on the spot. Moreover, sequences often should have a lazy nature as their persistence in memory may be problematic or infeasible (infinite sequences). For all those reasons, constructor operators come in handy.&lt;/p&gt;  &lt;p&gt;LINQ to Objects already has a constructor function called Enumerable.Range to produce a sequence with a integral numbers starting from a certain value, returning the asked amount of numbers lazily:&lt;/p&gt;  &lt;blockquote&gt;   &lt;pre class="code"&gt;&lt;span style="color:green;"&gt;// Imperative
&lt;/span&gt;&lt;span style="color:blue;"&gt;for &lt;/span&gt;(&lt;span style="color:blue;"&gt;int &lt;/span&gt;i = 0; i &amp;lt; 10; i++)
{
    &lt;span style="color:#2b91af;"&gt;Console&lt;/span&gt;.WriteLine(i);
}

&lt;span style="color:green;"&gt;// LINQish
&lt;/span&gt;&lt;span style="color:#2b91af;"&gt;Enumerable&lt;/span&gt;.Range(start: 0, count: 10).Run
(
    &lt;span style="color:#2b91af;"&gt;Console&lt;/span&gt;.WriteLine
);&lt;/pre&gt;
&lt;/blockquote&gt;

&lt;p&gt;&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;The lazy nature should not be underestimated, as one could create infinite sequences representing the &lt;em&gt;potential&lt;/em&gt; to &lt;em&gt;produce&lt;/em&gt; a certain (ordered) set of objects. When combined with other restriction operators it becomes possible to use composition to limit the produced results in a manner very close to the domain we’re talking about. For example, positive natural numbers are integer numbers larger or equal to zero. Numbers starting with 5 are the numbers, capped by means of a Skip operation or something similar. Taking a number of elements can be done using Take. Without deviating too much from our today’s blogging mission, here’s what I’m alluding to:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;pre class="code"&gt;&lt;span style="color:blue;"&gt;static &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;IEnumerable&lt;/span&gt;&amp;lt;&lt;span style="color:blue;"&gt;int&lt;/span&gt;&amp;gt; Integer()
{
    &lt;span style="color:blue;"&gt;for &lt;/span&gt;(&lt;span style="color:blue;"&gt;int &lt;/span&gt;i = &lt;span style="color:blue;"&gt;int&lt;/span&gt;.MinValue; i &amp;lt; &lt;span style="color:blue;"&gt;int&lt;/span&gt;.MaxValue; i++)
        &lt;span style="color:blue;"&gt;yield return &lt;/span&gt;i;

    &lt;span style="color:blue;"&gt;yield return int&lt;/span&gt;.MaxValue;
}&lt;/pre&gt;
  &lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;&lt;/blockquote&gt;

&lt;blockquote&gt;
  &lt;pre class="code"&gt;&lt;span style="color:blue;"&gt;var &lt;/span&gt;ints = Integer();
&lt;span style="color:blue;"&gt;var &lt;/span&gt;nats = &lt;span style="color:blue;"&gt;from &lt;/span&gt;i &lt;span style="color:blue;"&gt;in &lt;/span&gt;ints &lt;span style="color:blue;"&gt;where &lt;/span&gt;i &amp;gt;= 0 &lt;span style="color:blue;"&gt;select &lt;/span&gt;i;
&lt;span style="color:blue;"&gt;var &lt;/span&gt;some = nats.Skip(5).Take(5); &lt;span style="color:green;"&gt;// Good luck :-)
&lt;/span&gt;some.Run(&lt;span style="color:#2b91af;"&gt;Console&lt;/span&gt;.WriteLine);&lt;/pre&gt;
&lt;/blockquote&gt;
&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;

&lt;p&gt;I’ll leave it to the reader as a challenge to come up with ways to optimize this in a variety of ways whilst preserving the declarative nature on the use site (i.e. make the sarcastic “Good luck” go away).&lt;/p&gt;

&lt;p&gt;Back to Rx: in today’s installment we’ll look at various constructor functions in EnumerableEx.&lt;/p&gt;

&lt;p&gt;&amp;#160;&lt;/p&gt;

&lt;h1&gt;Return and the cruel return of the monad&lt;/h1&gt;

&lt;p&gt;The simplest constructor function is Return, simply yielding the single value specified on demand. It’s similar to a one-element array and that’s about it from a practical point of view:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;pre class="code"&gt;&lt;span style="color:blue;"&gt;public static &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;IEnumerable&lt;/span&gt;&amp;lt;TSource&amp;gt; Return&amp;lt;TSource&amp;gt;(TSource value);&lt;/pre&gt;
&lt;/blockquote&gt;

&lt;p&gt;&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;You should be able to guess the implementation of the operator for yourself. Use is straightforward as shown below:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;pre class="code"&gt;&lt;span style="color:#2b91af;"&gt;EnumerableEx&lt;/span&gt;.Return(42).Run(&lt;span style="color:#2b91af;"&gt;Console&lt;/span&gt;.WriteLine);&lt;/pre&gt;
  &lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;&lt;/blockquote&gt;

&lt;p&gt;One interesting thing about this constructor function is its signature, going from TSource to IEnumerable&amp;lt;TSource&amp;gt;. This is nothing but the return function (sometimes referred to as &lt;em&gt;unit&lt;/em&gt;) used on a &lt;em&gt;monad&lt;/em&gt;, with a more general signature of T to M&amp;lt;T&amp;gt;, the little brother to the bind function which has signature M&amp;lt;T&amp;gt; –&amp;gt; (T –&amp;gt; M&amp;lt;R&amp;gt;) –&amp;gt; M&amp;lt;R&amp;gt;, also known as SelectMany in LINQ. The triplet (known as a Kleisli triple) of the type constructor M (in LINQ the particular cases of IEnumerable&amp;lt;T&amp;gt; and IQueryable&amp;lt;T&amp;gt; are used, i.e. not a general type constructor), the unit and bind function form a monad.&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;&lt;a href="http://bartdesmet.net/images_wlw/Mor.InteractiveSequencesunderconstructio_11DD/image_3.png"&gt;&lt;img style="border-right-width:0px;display:inline;border-top-width:0px;border-bottom-width:0px;border-left-width:0px;" title="image" border="0" alt="image" src="http://bartdesmet.net/images_wlw/Mor.InteractiveSequencesunderconstructio_11DD/image_thumb_3.png" width="640" height="236" /&gt;&lt;/a&gt; &lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;For a great overview of Language Integrated Monads, have a look at &lt;a href="http://blogs.msdn.com/wesdyer/archive/2008/01/11/the-marvels-of-monads.aspx"&gt;Wes Dyer’s The Marvels of Monads post&lt;/a&gt;. For a more foundational paper (with lots of applications though), have a look at &lt;a href="http://homepages.inf.ed.ac.uk/wadler/papers/marktoberdorf/baastad.pdf"&gt;Philip Wadler’s Monads for Functional Programming&lt;/a&gt;&amp;#160;&lt;a href="http://homepages.inf.ed.ac.uk/wadler/papers/marktoberdorf/baastad.pdf"&gt;paper&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;&amp;#160;&lt;/p&gt;

&lt;h1&gt;Throw me an exception please&lt;/h1&gt;

&lt;p&gt;Another singleton constructor is the Throw function that we’ve seen repeatedly in the previous post on exception handling over sequences. Its role is to provide an enumerable that will throw an exception upon the first MoveNext call during enumeration:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;pre class="code"&gt;&lt;span style="color:blue;"&gt;public static &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;IEnumerable&lt;/span&gt;&amp;lt;TSource&amp;gt; Throw&amp;lt;TSource&amp;gt;(&lt;span style="color:#2b91af;"&gt;Exception &lt;/span&gt;exception);&lt;/pre&gt;
&lt;/blockquote&gt;

&lt;p&gt;In fact, this is a lazily thrown exception constructor. Use is simple again:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;pre class="code"&gt;&lt;span style="color:#2b91af;"&gt;EnumerableEx&lt;/span&gt;.Throw&amp;lt;&lt;span style="color:blue;"&gt;int&lt;/span&gt;&amp;gt;(&lt;span style="color:blue;"&gt;new &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;Exception&lt;/span&gt;()).Run();&lt;/pre&gt;
&lt;/blockquote&gt;

&lt;p&gt;&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;Notice you got to specify the element type for the returned (never-yielding) sequence as we’re constructing an IEnumerable&amp;lt;T&amp;gt; and there’s no information to infer T from. Obviously, the resulting sequence can be combined with other sequences of the same type in various places, e.g. using Concat. Below is a sample of how to use the Throw constructor with SelectMany to forcefully reject even numbers in a sequence (rather than filtering them out):&lt;/p&gt;

&lt;blockquote&gt;
  &lt;pre class="code"&gt;&lt;span style="color:blue;"&gt;var &lt;/span&gt;src = &lt;span style="color:#2b91af;"&gt;Enumerable&lt;/span&gt;.Range(1, 10);&lt;span style="color:green;"&gt;//.Where(i =&amp;gt; i % 2 != 0);
&lt;/span&gt;&lt;span style="color:blue;"&gt;var &lt;/span&gt;res = src.SelectMany(i =&amp;gt;
    i % 2 == 0
    ? &lt;span style="color:#2b91af;"&gt;EnumerableEx&lt;/span&gt;.Throw&amp;lt;&lt;span style="color:blue;"&gt;int&lt;/span&gt;&amp;gt;(&lt;span style="color:blue;"&gt;new &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;Exception&lt;/span&gt;(&lt;span style="color:#a31515;"&gt;&amp;quot;No evens please!&amp;quot;&lt;/span&gt;))
    : &lt;span style="color:#2b91af;"&gt;EnumerableEx&lt;/span&gt;.Return(i)
);
res.Run(&lt;span style="color:#2b91af;"&gt;Console&lt;/span&gt;.WriteLine);&lt;/pre&gt;
&lt;/blockquote&gt;

&lt;p&gt;Here we use the conditional operator to decide between an exception throwing sequence or a singleton element sequence (in this case, “Many” in “SelectMany” has “Single” semantics).&lt;/p&gt;

&lt;p&gt;&amp;#160;&lt;/p&gt;

&lt;h1&gt;Empty completing the triad&lt;/h1&gt;

&lt;p&gt;Since the introduction of LINQ in .NET 3.5 (thanks to reader Keith for reminding me about my heritage), there’s been an Empty constructor as well, with the following signature and implementation:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;pre class="code"&gt;&lt;span style="color:blue;"&gt;public static &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;IEnumerable&lt;/span&gt;&amp;lt;TSource&amp;gt; Empty&amp;lt;TSource&amp;gt;()
{
    &lt;span style="color:blue;"&gt;yield break&lt;/span&gt;;
}&lt;/pre&gt;
&lt;/blockquote&gt;

&lt;p&gt;&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;There seems little use for this though I challenge the reader to use this one to build the Where operator using SelectMany. In fact, the reason I say “for completeness” is illustrated below:&lt;/p&gt;

&lt;p&gt;&lt;a href="http://bartdesmet.net/images_wlw/Mor.InteractiveSequencesunderconstructio_11DD/image_4.png"&gt;&lt;img style="border-right-width:0px;display:inline;border-top-width:0px;border-bottom-width:0px;border-left-width:0px;" title="image" border="0" alt="image" src="http://bartdesmet.net/images_wlw/Mor.InteractiveSequencesunderconstructio_11DD/image_thumb_4.png" width="500" height="380" /&gt;&lt;/a&gt; &lt;/p&gt;

&lt;p&gt;&amp;#160;&lt;/p&gt;

&lt;h1&gt;StartWith = Snoc (or Cons in disguise)&lt;/h1&gt;

&lt;p&gt;People familiar with LISP, ML, Scala, and many other functional languages, will know the concept of cons by heart. Cons is nothing but the abbreviation for “construct” used to create a bigger list (in LISP lingo) out of an existing list and an element to be prepended:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;(cons 1 (cons 2 nil))&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;The above creates a list with 1 as the head and (cons 2 nil) as the tail, which by itself expands into a cell containing 2 and a tail with the nil (null) value. The underlying pair of the head value and tail “reference” to the tail list is known as a cons cell. Decomposition operators exist, known as car and cdr (from old IBM machine terminology where cons cells were realized in machine words consisting of a so called “address” and “decrement” register, explaining the a and d in car and cdr – c and r stand for content and register respectively):&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;(car (cons 1 2)) == 1 
    &lt;br /&gt;(cdr (cons 1 2)) == 2&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;The StartWith operator is none other than Cons in reverse (sometimes jokingly referred to as “Snoc” by functional programmers):&lt;/p&gt;

&lt;blockquote&gt;
  &lt;pre class="code"&gt;&lt;span style="color:blue;"&gt;public static &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;IEnumerable&lt;/span&gt;&amp;lt;TSource&amp;gt; StartWith&amp;lt;TSource&amp;gt;(&lt;span style="color:blue;"&gt;this &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;IEnumerable&lt;/span&gt;&amp;lt;TSource&amp;gt; source, &lt;span style="color:blue;"&gt;params &lt;/span&gt;TSource[] first);&lt;br /&gt;&lt;span style="color:blue;"&gt;public static &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;IEnumerable&lt;/span&gt;&amp;lt;TSource&amp;gt; StartWith&amp;lt;TSource&amp;gt;(&lt;span style="color:blue;"&gt;this &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;IEnumerable&lt;/span&gt;&amp;lt;TSource&amp;gt; source, TSource first);&lt;/pre&gt;
  &lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;&lt;/blockquote&gt;

&lt;p&gt;Focus on the second one first. See how the “first” parameter is taken in as the second argument to StartWith. The reason is it’d be very invasive to put the extension method this parameter on the “first” parameter, as it would pollute all types in the framework with a “Cons” method:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;pre class="code"&gt;&lt;span style="color:blue;"&gt;public static &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;IEnumerable&lt;/span&gt;&amp;lt;TSource&amp;gt; Cons&amp;lt;TSource&amp;gt;(&lt;span style="color:blue;"&gt;this &lt;/span&gt;TSource head, &lt;span style="color:#2b91af;"&gt;IEnumerable&lt;/span&gt;&amp;lt;TSource&amp;gt; tail);&lt;/pre&gt;
  &lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;&lt;/blockquote&gt;

&lt;p&gt;So, StartWith has to be read in reverse as illustrated below:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;pre class="code"&gt;&lt;span style="color:#2b91af;"&gt;EnumerableEx&lt;/span&gt;.StartWith(
    &lt;span style="color:#2b91af;"&gt;EnumerableEx&lt;/span&gt;.StartWith(
        &lt;span style="color:#2b91af;"&gt;EnumerableEx&lt;/span&gt;.Return(3),
        2
    ),
    1
).Run(&lt;span style="color:#2b91af;"&gt;Console&lt;/span&gt;.WriteLine);&lt;/pre&gt;
  &lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;&lt;/blockquote&gt;

&lt;p&gt;This prints 1, 2, 3 since 2 is put in front of 3 and 1 in front of that { 2, 3 } result. An overload exists to start a sequence with multiple elements in front of it:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;pre class="code"&gt;&lt;span style="color:#2b91af;"&gt;EnumerableEx&lt;/span&gt;.StartWith(
    &lt;span style="color:#2b91af;"&gt;EnumerableEx&lt;/span&gt;.Return(3),
    1, 2
).Run(&lt;span style="color:#2b91af;"&gt;Console&lt;/span&gt;.WriteLine);&lt;/pre&gt;
&lt;/blockquote&gt;

&lt;p&gt;&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;&lt;a href="http://bartdesmet.net/images_wlw/Mor.InteractiveSequencesunderconstructio_11DD/image_5.png"&gt;&lt;img style="border-right-width:0px;display:inline;border-top-width:0px;border-bottom-width:0px;border-left-width:0px;" title="image" border="0" alt="image" src="http://bartdesmet.net/images_wlw/Mor.InteractiveSequencesunderconstructio_11DD/image_thumb_5.png" width="500" height="380" /&gt;&lt;/a&gt; &lt;/p&gt;

&lt;p&gt;&amp;#160;&lt;/p&gt;

&lt;h1&gt;Generate is your new anamorphism&lt;/h1&gt;

&lt;p&gt;Generate is the most general constructor function for sequences you can imagine. It’s the dual of Aggregate in various ways. Where Aggregate folds a sequence into a single object by combining elements in the input sequence onto a final value in a step-by-step way, the Generate function unfolds a sequence out of a generator function also in a step-by-step way. To set the scene, let’s show the power of Aggregate by refreshing its signature and showing how to implement a bunch of other LINQ combinators in terms of it:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;pre class="code"&gt;&lt;span style="color:blue;"&gt;public static &lt;/span&gt;TResult Aggregate&amp;lt;TSource, TAccumulate, TResult&amp;gt;(&lt;span style="color:blue;"&gt;this &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;IEnumerable&lt;/span&gt;&amp;lt;TSource&amp;gt; source, TAccumulate seed, &lt;span style="color:#2b91af;"&gt;Func&lt;/span&gt;&amp;lt;TAccumulate, TSource, TAccumulate&amp;gt; func, &lt;span style="color:#2b91af;"&gt;Func&lt;/span&gt;&amp;lt;TAccumulate, TResult&amp;gt; resultSelector);&lt;/pre&gt;
  &lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;&lt;/blockquote&gt;

&lt;p&gt;Given a seed value and a function to combine an element of the input sequence with the current accumulator value into a new accumulator value, the Aggregate function can produce a result that’s the result of (left-)folding all elements in the sequence one-by-one. For example, a sum is nothing but a left-fold thanks to left associativity of the numerical addition operation:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;1 + 2 + 3 + 4 + 5 = ((((1 + 2) + 3) + 4) + 5)&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;The accumulated value is the running sum of everything to the left of the current element. Seeing the elements of a sequence being eaten one-by-one is quite a shocking catastrophic event for the sequence, hence the name &lt;a href="http://en.wikipedia.org/wiki/Catamorphism"&gt;catamorphism&lt;/a&gt;. Below are implementations of Sum, Product, Min, Max, FirstOrDefault, LastOrDefault, Any and All:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;pre class="code"&gt;&lt;span style="color:blue;"&gt;var &lt;/span&gt;src = &lt;span style="color:#2b91af;"&gt;Enumerable&lt;/span&gt;.Range(1, 10);

&lt;span style="color:#2b91af;"&gt;Console&lt;/span&gt;.WriteLine(&lt;span style="color:#a31515;"&gt;&amp;quot;Sum = &amp;quot; &lt;/span&gt;+ src.Aggregate(0, (sum, i) =&amp;gt; sum + i));
&lt;span style="color:#2b91af;"&gt;Console&lt;/span&gt;.WriteLine(&lt;span style="color:#a31515;"&gt;&amp;quot;Prd = &amp;quot; &lt;/span&gt;+ src.Aggregate(1, (prd, i) =&amp;gt; prd * i));
&lt;span style="color:#2b91af;"&gt;Console&lt;/span&gt;.WriteLine(&lt;span style="color:#a31515;"&gt;&amp;quot;Min = &amp;quot; &lt;/span&gt;+ src.Aggregate(&lt;span style="color:blue;"&gt;int&lt;/span&gt;.MaxValue, (min, i) =&amp;gt; i &amp;lt; min ? i : min));
&lt;span style="color:#2b91af;"&gt;Console&lt;/span&gt;.WriteLine(&lt;span style="color:#a31515;"&gt;&amp;quot;Max = &amp;quot; &lt;/span&gt;+ src.Aggregate(&lt;span style="color:blue;"&gt;int&lt;/span&gt;.MinValue, (max, i) =&amp;gt; i &amp;gt; max ? i : max));
&lt;span style="color:#2b91af;"&gt;Console&lt;/span&gt;.WriteLine(&lt;span style="color:#a31515;"&gt;&amp;quot;Fst = &amp;quot; &lt;/span&gt;+ src.Aggregate((&lt;span style="color:blue;"&gt;int&lt;/span&gt;?)&lt;span style="color:blue;"&gt;null&lt;/span&gt;, (fst, i) =&amp;gt; fst == &lt;span style="color:blue;"&gt;null &lt;/span&gt;? i : fst));
&lt;span style="color:#2b91af;"&gt;Console&lt;/span&gt;.WriteLine(&lt;span style="color:#a31515;"&gt;&amp;quot;Lst = &amp;quot; &lt;/span&gt;+ src.Aggregate((&lt;span style="color:blue;"&gt;int&lt;/span&gt;?)&lt;span style="color:blue;"&gt;null&lt;/span&gt;, (lst, i) =&amp;gt; i));
&lt;span style="color:#2b91af;"&gt;Console&lt;/span&gt;.WriteLine(&lt;span style="color:#a31515;"&gt;&amp;quot;AlE = &amp;quot; &lt;/span&gt;+ src.Aggregate(&lt;span style="color:blue;"&gt;true&lt;/span&gt;, (all, i) =&amp;gt; all &amp;amp;&amp;amp; i % 2 == 0));
&lt;span style="color:#2b91af;"&gt;Console&lt;/span&gt;.WriteLine(&lt;span style="color:#a31515;"&gt;&amp;quot;AnE = &amp;quot; &lt;/span&gt;+ src.Aggregate(&lt;span style="color:blue;"&gt;false&lt;/span&gt;, (any, i) =&amp;gt; any || i % 2 == 0));&lt;/pre&gt;
  &lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;&lt;/blockquote&gt;

&lt;p&gt;As the dual to catamorphisms we find &lt;a href="http://en.wikipedia.org/wiki/Anamorphism"&gt;anamorphisms&lt;/a&gt;, where one starts from an initial state and generates elements for the resulting sequence. I leave it to the reader to draw parallels with others words starting with ana- (from the Greek “up”). The most elaborate signature of Generate is shown below:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;pre class="code"&gt;&lt;span style="color:blue;"&gt;public static &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;IEnumerable&lt;/span&gt;&amp;lt;TResult&amp;gt; Generate&amp;lt;TState, TResult&amp;gt;(TState initial, &lt;span style="color:#2b91af;"&gt;Func&lt;/span&gt;&amp;lt;TState, &lt;span style="color:blue;"&gt;bool&lt;/span&gt;&amp;gt; condition, &lt;span style="color:#2b91af;"&gt;Func&lt;/span&gt;&amp;lt;TState, &lt;span style="color:#2b91af;"&gt;IEnumerable&lt;/span&gt;&amp;lt;TResult&amp;gt;&amp;gt; resultSelector, &lt;span style="color:#2b91af;"&gt;Func&lt;/span&gt;&amp;lt;TState, TState&amp;gt; iterate);&lt;/pre&gt;
  &lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;&lt;/blockquote&gt;

&lt;p&gt;To see this is the dual to Aggregate, you got to use a bit of fantasy, but you can see the parallels. Where Aggregate takes in an IEnumerable&amp;lt;TSource&amp;gt; and produces a TResult, the Generate function produces an IEnumerable&amp;lt;TResult&amp;gt; from a given TState (and a bunch of other things). On both sides, there’s room for an initial state and a way to make progress (“func” versus “iterate”) both staying in their respective domains for the accumulation type (TAccumulate and TState). To select the result (that will end up in the output sequence), the overload above allows to produce multiple TResult values to be returned per TState. And finally, there’s a stop condition which is implicit in the case of a catamorphism as the “remaining tail of sequence is empty” condition can be used for it (i.e. MoveNext returns false).&lt;/p&gt;

&lt;p&gt;Another way to look at Generate is to draw the parallel with a for loop’s three parts: initialization, termination condition, update. In fact, Generate is implemented as some for-loops. More signatures exist:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;pre class="code"&gt;&lt;span style="color:blue;"&gt;public static &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;IEnumerable&lt;/span&gt;&amp;lt;TValue&amp;gt; Generate&amp;lt;TValue&amp;gt;(&lt;span style="color:blue;"&gt;this &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;Func&lt;/span&gt;&amp;lt;&lt;span style="color:#2b91af;"&gt;Notification&lt;/span&gt;&amp;lt;TValue&amp;gt;&amp;gt; function);
&lt;span style="color:blue;"&gt;public static &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;IEnumerable&lt;/span&gt;&amp;lt;TResult&amp;gt; Generate&amp;lt;TState, TResult&amp;gt;(TState initial, &lt;span style="color:#2b91af;"&gt;Func&lt;/span&gt;&amp;lt;TState, &lt;span style="color:#2b91af;"&gt;IEnumerable&lt;/span&gt;&amp;lt;TResult&amp;gt;&amp;gt; resultSelector, &lt;span style="color:#2b91af;"&gt;Func&lt;/span&gt;&amp;lt;TState, TState&amp;gt; iterate);
&lt;span style="color:blue;"&gt;public static &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;IEnumerable&lt;/span&gt;&amp;lt;TResult&amp;gt; Generate&amp;lt;TState, TResult&amp;gt;(TState initial, &lt;span style="color:#2b91af;"&gt;Func&lt;/span&gt;&amp;lt;TState, &lt;span style="color:#2b91af;"&gt;Notification&lt;/span&gt;&amp;lt;TResult&amp;gt;&amp;gt; resultSelector, &lt;span style="color:#2b91af;"&gt;Func&lt;/span&gt;&amp;lt;TState, TState&amp;gt; iterate);
&lt;span style="color:blue;"&gt;public static &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;IEnumerable&lt;/span&gt;&amp;lt;TResult&amp;gt; Generate&amp;lt;TState, TResult&amp;gt;(TState initial, &lt;span style="color:#2b91af;"&gt;Func&lt;/span&gt;&amp;lt;TState, &lt;span style="color:blue;"&gt;bool&lt;/span&gt;&amp;gt; condition, &lt;span style="color:#2b91af;"&gt;Func&lt;/span&gt;&amp;lt;TState, &lt;span style="color:#2b91af;"&gt;IEnumerable&lt;/span&gt;&amp;lt;TResult&amp;gt;&amp;gt; resultSelector, &lt;span style="color:#2b91af;"&gt;Func&lt;/span&gt;&amp;lt;TState, TState&amp;gt; iterate);
&lt;span style="color:blue;"&gt;public static &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;IEnumerable&lt;/span&gt;&amp;lt;TResult&amp;gt; Generate&amp;lt;TState, TResult&amp;gt;(TState initial, &lt;span style="color:#2b91af;"&gt;Func&lt;/span&gt;&amp;lt;TState, &lt;span style="color:blue;"&gt;bool&lt;/span&gt;&amp;gt; condition, &lt;span style="color:#2b91af;"&gt;Func&lt;/span&gt;&amp;lt;TState, TResult&amp;gt; resultSelector, &lt;span style="color:#2b91af;"&gt;Func&lt;/span&gt;&amp;lt;TState, TState&amp;gt; iterate);&lt;/pre&gt;
  &lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;&lt;/blockquote&gt;

&lt;p&gt;We’ll discuss the ones with Notification&amp;lt;T&amp;gt; types in the next episode titled “Code = Data”, but the remaining three others are all straightforward to understand. Some lack a terminating condition while others lack the ability to yield multiple results per intermediate state. Below is a sample of Generate to produce the same results as Enumerable.Range:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;pre class="code"&gt;&lt;span style="color:#2b91af;"&gt;Func&lt;/span&gt;&amp;lt;&lt;span style="color:blue;"&gt;int&lt;/span&gt;, &lt;span style="color:blue;"&gt;int&lt;/span&gt;, &lt;span style="color:#2b91af;"&gt;IEnumerable&lt;/span&gt;&amp;lt;&lt;span style="color:blue;"&gt;int&lt;/span&gt;&amp;gt;&amp;gt; range = (start, count) =&amp;gt; &lt;span style="color:#2b91af;"&gt;EnumerableEx&lt;/span&gt;.Generate(0, i =&amp;gt; i &amp;lt; count, i =&amp;gt; i + start, i =&amp;gt; i + 1);&lt;/pre&gt;
  &lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;&lt;/blockquote&gt;

&lt;p&gt;The other constructors we’ve seen can be written in terms of Generate as well:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;pre class="code"&gt;&lt;span style="color:#2b91af;"&gt;Func&lt;/span&gt;&amp;lt;&lt;span style="color:#2b91af;"&gt;IEnumerable&lt;/span&gt;&amp;lt;&lt;span style="color:blue;"&gt;int&lt;/span&gt;&amp;gt;&amp;gt; empty = () =&amp;gt; &lt;span style="color:#2b91af;"&gt;EnumerableEx&lt;/span&gt;.Generate&amp;lt;&lt;span style="color:blue;"&gt;object&lt;/span&gt;, &lt;span style="color:blue;"&gt;int&lt;/span&gt;&amp;gt;(&lt;span style="color:blue;"&gt;null&lt;/span&gt;, o =&amp;gt; &lt;span style="color:blue;"&gt;false&lt;/span&gt;, o =&amp;gt; &lt;span style="color:blue;"&gt;null&lt;/span&gt;, o =&amp;gt; o);
&lt;span style="color:#2b91af;"&gt;Func&lt;/span&gt;&amp;lt;&lt;span style="color:blue;"&gt;int&lt;/span&gt;, &lt;span style="color:#2b91af;"&gt;IEnumerable&lt;/span&gt;&amp;lt;&lt;span style="color:blue;"&gt;int&lt;/span&gt;&amp;gt;&amp;gt; @return = i =&amp;gt; &lt;span style="color:#2b91af;"&gt;EnumerableEx&lt;/span&gt;.Generate&amp;lt;&lt;span style="color:blue;"&gt;int&lt;/span&gt;, &lt;span style="color:blue;"&gt;int&lt;/span&gt;&amp;gt;(0, n =&amp;gt; n &amp;lt; 1, o =&amp;gt; &lt;span style="color:blue;"&gt;new &lt;/span&gt;[] { i }, n =&amp;gt; n + 1);
&lt;span style="color:#2b91af;"&gt;Func&lt;/span&gt;&amp;lt;&lt;span style="color:#2b91af;"&gt;Exception&lt;/span&gt;, &lt;span style="color:#2b91af;"&gt;IEnumerable&lt;/span&gt;&amp;lt;&lt;span style="color:blue;"&gt;int&lt;/span&gt;&amp;gt;&amp;gt; @throw = ex =&amp;gt; &lt;span style="color:#2b91af;"&gt;EnumerableEx&lt;/span&gt;.Generate&amp;lt;&lt;span style="color:blue;"&gt;object&lt;/span&gt;, &lt;span style="color:blue;"&gt;int&lt;/span&gt;&amp;gt;(&lt;span style="color:blue;"&gt;null&lt;/span&gt;, o =&amp;gt; &lt;span style="color:blue;"&gt;true&lt;/span&gt;, o =&amp;gt; { &lt;span style="color:blue;"&gt;throw &lt;/span&gt;ex; &lt;span style="color:blue;"&gt;return null&lt;/span&gt;; }, o =&amp;gt; o);
&lt;span style="color:#2b91af;"&gt;Func&lt;/span&gt;&amp;lt;&lt;span style="color:blue;"&gt;int&lt;/span&gt;, &lt;span style="color:#2b91af;"&gt;IEnumerable&lt;/span&gt;&amp;lt;&lt;span style="color:blue;"&gt;int&lt;/span&gt;&amp;gt;, &lt;span style="color:#2b91af;"&gt;IEnumerable&lt;/span&gt;&amp;lt;&lt;span style="color:blue;"&gt;int&lt;/span&gt;&amp;gt;&amp;gt; cons = (a, d) =&amp;gt; &lt;span style="color:#2b91af;"&gt;EnumerableEx&lt;/span&gt;.Generate&amp;lt;&lt;span style="color:blue;"&gt;int&lt;/span&gt;, &lt;span style="color:blue;"&gt;int&lt;/span&gt;&amp;gt;(0, n =&amp;gt; n &amp;lt; 2, o =&amp;gt; o == 0 ? &lt;span style="color:blue;"&gt;new &lt;/span&gt;[] { a } : d, n =&amp;gt; n + 1);

@return(1).Run(&lt;span style="color:#2b91af;"&gt;Console&lt;/span&gt;.WriteLine);
@throw(&lt;span style="color:blue;"&gt;new &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;Exception&lt;/span&gt;()).Catch((&lt;span style="color:#2b91af;"&gt;Exception &lt;/span&gt;ex) =&amp;gt; @return(22)).Run(&lt;span style="color:#2b91af;"&gt;Console&lt;/span&gt;.WriteLine);
cons(1, cons(2, cons(3, empty()))).Run(&lt;span style="color:#2b91af;"&gt;Console&lt;/span&gt;.WriteLine);&lt;/pre&gt;
&lt;/blockquote&gt;

&lt;p&gt;&amp;#160;&lt;/p&gt;

&lt;h1&gt;Defer what you can do now till later&lt;/h1&gt;

&lt;p&gt;The intrinsic lazy nature of sequences with regards to enumeration allows us to push more delayed effects into the sequence’s iteration code. In particular, the construction of a sequence can be hidden behind a sequence of the same type. Let’s show a signature to make this more clear:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;pre class="code"&gt;&lt;span style="color:blue;"&gt;public static &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;IEnumerable&lt;/span&gt;&amp;lt;TSource&amp;gt; Defer&amp;lt;TSource&amp;gt;(&lt;span style="color:#2b91af;"&gt;Func&lt;/span&gt;&amp;lt;&lt;span style="color:#2b91af;"&gt;IEnumerable&lt;/span&gt;&amp;lt;TSource&amp;gt;&amp;gt; enumerableFactory);&lt;/pre&gt;
&lt;/blockquote&gt;

&lt;p&gt;&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;In here, an IEnumerable&amp;lt;TSource&amp;gt; is created out of a factory function. What’s handed back from the call to Defer is a stub IEnumerable&amp;lt;TSource&amp;gt; that will only call its factory function (getting the real intended result sequence) upon a triggered enumeration. An example is shown below:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;pre class="code"&gt;&lt;span style="color:blue;"&gt;var &lt;/span&gt;xs = &lt;span style="color:#2b91af;"&gt;EnumerableEx&lt;/span&gt;.Defer(() =&amp;gt;
{
    &lt;span style="color:#2b91af;"&gt;Console&lt;/span&gt;.WriteLine(&lt;span style="color:#a31515;"&gt;&amp;quot;Factory!&amp;quot;&lt;/span&gt;);
    &lt;span style="color:blue;"&gt;return &lt;/span&gt;&lt;span style="color:#2b91af;"&gt;EnumerableEx&lt;/span&gt;.Return(1);
});

&lt;span style="color:#2b91af;"&gt;Console&lt;/span&gt;.ReadLine();

xs.Run(&lt;span style="color:#2b91af;"&gt;Console&lt;/span&gt;.WriteLine);
xs.Run(&lt;span style="color:#2b91af;"&gt;Console&lt;/span&gt;.WriteLine);&lt;/pre&gt;
&lt;/blockquote&gt;

&lt;p&gt;&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;In here, the Factory message won’t be printed till something starts enumerating the xs sequence. Both calls to Run do so, meaning the factory will be called twice (and could in fact return a different sequence each time).&lt;/p&gt;

&lt;p&gt;&lt;a href="http://bartdesmet.net/images_wlw/Mor.InteractiveSequencesunderconstructio_11DD/image_6.png"&gt;&lt;img style="border-right-width:0px;display:inline;border-top-width:0px;border-bottom-width:0px;border-left-width:0px;" title="image" border="0" alt="image" src="http://bartdesmet.net/images_wlw/Mor.InteractiveSequencesunderconstructio_11DD/image_thumb_6.png" width="500" height="380" /&gt;&lt;/a&gt; &lt;/p&gt;

&lt;p&gt;&amp;#160;&lt;/p&gt;

&lt;h1&gt;Next on More LINQ&lt;/h1&gt;

&lt;p&gt;More duality, this time between “code and data” views on sequences, introducing Notification&amp;lt;T&amp;gt;.&lt;/p&gt;&lt;img src="http://blogs.bartdesmet.net/aggbug.aspx?PostID=14928" width="1" height="1"&gt;</description><category domain="http://blogs.bartdesmet.net/blogs/bart/archive/tags/LINQ/default.aspx">LINQ</category><category domain="http://blogs.bartdesmet.net/blogs/bart/archive/tags/Rx/default.aspx">Rx</category></item></channel></rss>