<?xml version="1.0" encoding="utf-8"?><rss version="2.0"><channel><title>(w)asp.net - extending the world</title><link>http://www.robychechi.it:80/roby/Tags/extending%20the%20world</link><description>(w)asp.net - extending the world</description><item><title>The resultor pattern</title><link>http://www.robychechi.it:80/roby/the-resultor-pattern</link><description>&lt;p&gt;
	In this short post belonging to &lt;a href="http://www.robychechi.it/roby/Tags/extending%20the%20world" target="_blank"&gt;the series about extending the world of Linq&lt;/a&gt;, I&amp;#39;ll talk about an interesting way to leverage anonymous types through a pattern we use at work. We all know what they are, and we all know their most important limitation: once defined, an anonymous type cannot be passed to other functions or returned to the caller of the function which defined it (we are talking about language features, and we don&amp;#39;t consider any technique based on reflection or other knowledge about the runtime internal structure of such types). It is quite common to write functions which return complex values, and if we want to make them reusable we need at some point to define some structure representing the result of the computation. We could use tuples, but they are not that good at communicating information, so we must surrender and define small DTOs just to represent those answers, just because anonymous type cannot cross the boundaries of a function. But is that completely true?&lt;/p&gt;
&lt;p&gt;
	Let&amp;#39;s suppose we need a function which parses string, and for each one we want to return a set of values. We could write something like this:&lt;/p&gt;
&lt;pre class="brush:csharp"&gt;
public static IEnumerable&amp;lt;DTO&amp;gt; Parse(
    this IEnumerable&amp;lt;string&amp;gt; source, 
    int someParam, string someOtherParam)
{
    return from item in source
           select new DTO
           {
               First  = item,
	       Second = item.Length,
	       Third  = new DateTime(2012, 1, 1),
	       Fourth = 42
           };
}

public class DTO
{
    public string   First   { get; set; }    
    public int      Second  { get; set; }    
    public DateTime Third   { get; set; }    
    public decimal  Fourth  { get; set; }    
}
&lt;/pre&gt;
&lt;p&gt;
	The body of the &lt;span style="font-family:courier new,courier,monospace;"&gt;Parse&lt;/span&gt; function is doing some stupid calculations, but that&amp;#39;s not the point, what I want to show here is that for even for simple cases like this one we need to define a special class (&lt;span style="font-family:courier new,courier,monospace;"&gt;DTO&lt;/span&gt;) just for the sake of returning four values for each parsed string. It feels like a &amp;quot;waste&amp;quot; of power. We need to define some static type to return our answers. And even more disturbing, it often happens that the caller does not really need all the values that we are returning, but just some of them.&amp;nbsp;&lt;/p&gt;
&lt;p&gt;
	But there is a way out. Type inference helps us to put a &amp;#39;trick&amp;#39; in place and make anonymous types cross the function boundary. Let&amp;#39;s look at our &lt;span style="font-family:courier new,courier,monospace;"&gt;Parse&lt;/span&gt; function: each time it parses a string it &amp;#39;calculates&amp;#39; 4 values and it packs them in our &lt;span style="font-family:courier new,courier,monospace;"&gt;DTO&lt;/span&gt; to return them to the caller, but we could slightly change the point of view and say that the &lt;span style="font-family:courier new,courier,monospace;"&gt;Parse&lt;/span&gt; function calculates those values and &amp;#39;passes&amp;#39; them to the caller. This subtle change makes us think that we could do what we always do in such cases: call a function.&lt;/p&gt;
&lt;p&gt;
	Let&amp;#39;s change our &lt;span style="font-family:courier new,courier,monospace;"&gt;Parse&lt;/span&gt; function signature like this:&lt;/p&gt;
&lt;pre class="brush:csharp"&gt;
public static IEnumerable&amp;lt;T&amp;gt; Parse&amp;lt;T&amp;gt;(
    this IEnumerable&amp;lt;string&amp;gt; source, 
    int someParam, string someOtherParam, 
    Func&amp;lt;string, int, DateTime, decimal, T&amp;gt; resultor)&lt;/pre&gt;
&lt;p&gt;
	In this new version we changed 2 things:&lt;/p&gt;
&lt;ul&gt;
	&lt;li&gt;
		the return values is not an enumeration of &lt;span style="font-family:courier new,courier,monospace;"&gt;DTO&lt;/span&gt;s (or whatever well-defined type), but &lt;span style="font-family:courier new,courier,monospace;"&gt;IEnumerable&amp;lt;T&amp;gt;&lt;/span&gt;&lt;/li&gt;
	&lt;li&gt;
		the same &lt;span style="font-family:courier new,courier,monospace;"&gt;T&lt;/span&gt; appears as part of the type of a new parameter we added to the already existing ones: this new parameter (a callback) is declared as a &lt;span style="font-family:courier new,courier,monospace;"&gt;Func&amp;lt;...&amp;gt;&lt;/span&gt; with N+1 type parameters, where the first N types are the same types of the properties in the original &lt;span style="font-family:courier new,courier,monospace;"&gt;DTO&lt;/span&gt;, and the last type parameter is &lt;span style="font-family:courier new,courier,monospace;"&gt;T&lt;/span&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;
	This &amp;#39;strange&amp;#39; signature is in fact very handy, and thanks to type inference we can modify our test call like this:&lt;/p&gt;
&lt;pre class="brush:csharp"&gt;
var parsed = from p in items.Parse(0, &amp;quot;wasp&amp;quot;, 
                 (first, second, third, fourth) =&amp;gt; new
                 {
                     First  = first,
                     Second = second,
                     Third  = third,
                     Fourth = fourth
                 })
             where p.First
                    .Equals(&amp;quot;a&amp;quot;, 
                            StringComparison.OrdinalIgnoreCase)
             select p;
&lt;/pre&gt;
&lt;p&gt;
	The lambda expression we pass as the last parameter in the call defines an anonymous type, which thanks to type inference becomes the &lt;span style="font-family:courier new,courier,monospace;"&gt;T&lt;/span&gt; of the generic &lt;span style="font-family:courier new,courier,monospace;"&gt;Parse&lt;/span&gt; function. The complete body of &lt;span style="font-family:courier new,courier,monospace;"&gt;Parse&lt;/span&gt; function could therefore be something like this:&lt;/p&gt;
&lt;pre class="brush:csharp"&gt;
public static IEnumerable&amp;lt;T&amp;gt; Parse&amp;lt;T&amp;gt;(
    this IEnumerable&amp;lt;string&amp;gt; source, 
    int someParam, string someOtherParam, 
    Func&amp;lt;string, int, DateTime, decimal, T&amp;gt; resultor)
{
    return from item in source 
	   select resultor 
           ( 
               item, 
               item.Length,
               new DateTime(2012, 1, 1), 
               42 
           ); 
}&lt;/pre&gt;
&lt;p&gt;
	It&amp;#39;s very similar to the original version, but the &lt;span style="font-family:courier new,courier,monospace;"&gt;new DTO()&lt;/span&gt;&amp;nbsp;part has been replaced to a function call to the supplied &lt;span style="font-family:courier new,courier,monospace;"&gt;Func&amp;lt;...&amp;gt;&lt;/span&gt; delegate, which is called &lt;span style="font-family:courier new,courier,monospace;"&gt;resultor&lt;/span&gt;. So we now have moved the responsibility of creating a representation of our &amp;#39;answer&amp;#39; outside of the &lt;span style="font-family:courier new,courier,monospace;"&gt;Parse&lt;/span&gt; function, which now just calls someone capable of building such a representation. Thanks to type inference we can define the builder on the fly through a lambda, and use an anonymous type to contain the representation. We don&amp;#39;t need the &lt;span style="font-family:courier new,courier,monospace;"&gt;DTO&lt;/span&gt; class anymore, and one more advantage that we gain now is that we can easily handle cases where we are not interested in all the components of an answer. If for instance we just want to deal with the first and the fourth value, we can call &lt;span style="font-family:courier new,courier,monospace;"&gt;Parse&lt;/span&gt; like this:&lt;/p&gt;
&lt;pre class="brush:csharp"&gt;
var parsed = from p in items.Parse(0, &amp;quot;wasp&amp;quot;, 
                 (p1, _, ___, p2) =&amp;gt; new
                 {
                     This  = p1,
                     That = p2
                 })
             where p.This
                    .Equals(&amp;quot;a&amp;quot;,
                            StringComparison.OrdinalIgnoreCase)
             select p;
&lt;/pre&gt;
&lt;p&gt;
	I learned about this &lt;a href="http://www.raboof.com" target="_blank"&gt;at work&lt;/a&gt;, and there we name it the &lt;strong&gt;resultor pattern&lt;/strong&gt;. So far I did not find anything around describing this technique explicily, Bill Wagner in one of his books talks about something similar but in a more basic way. It adds one more piece to our toolbox which helps us move our coding more &amp;#39;into Linq&amp;#39;. It could be used in other contexts too, but it really shines inside Linq queries.&lt;/p&gt;
</description><pubDate>Thu, 21 Mar 2013 05:00:24 GMT</pubDate><guid isPermaLink="true">http://www.robychechi.it:80/roby/the-resultor-pattern</guid></item><item><title>Extending the world, related material</title><link>http://www.robychechi.it:80/roby/extending-the-world-related-material</link><description>&lt;p&gt;
	As promised, here you can find the source code relative to &lt;a href="http://www.robychechi.it/roby/tech-blog/extending-the-world"&gt;the discussions we made so far&lt;/a&gt;:&lt;/p&gt;
&lt;p&gt;
	&lt;a href="http://www.robychechi.it/roby/Media/Default/code/ExtendingTheWorld.zip" target="_blank"&gt;Source code&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;
	Please remember that this is not production code at all, it has the only purpose to give you the chance to easily try what I&amp;#39;ve been trying myself so far while writing this series.&lt;/p&gt;
&lt;p&gt;
	I can also give you a few links where you can fine more formal and deeper material about the topics I&amp;#39;m blogging about in this series. I read a lot of stuff around functional programming and its influence over imperative ones, and especially over C#, and I think that &lt;a href="http://community.bartdesmet.net/blogs/bart/archive/tags/LINQ/default.aspx" target="_blank"&gt;Bart De Smet&lt;/a&gt; and &lt;a href="http://blogs.msdn.com/b/wesdyer/" target="_blank"&gt;Wes Dyer&lt;/a&gt; wrote some of the most interesting pieces I had the chance to find. It&amp;#39;s a pity that both have not been blogging about such topics in the last years, but their writings are still actual and very interesting. From there it is easy to naviggate and find more stuff, but here you have a couple of links more which I think deserve some consideration in our context: functional programming for &lt;strike&gt;dummies&lt;/strike&gt; imperative programmers :)&lt;/p&gt;
&lt;ul&gt;
	&lt;li&gt;
		&lt;a href="http://tomasp.net/blog/idioms-in-linq.aspx" target="_blank"&gt;http://tomasp.net/blog/idioms-in-linq.aspx&lt;/a&gt;&lt;/li&gt;
	&lt;li&gt;
		&lt;a href="http://weblogs.asp.net/podwysocki/archive/2008/10/13/functional-net-linq-or-language-integrated-monads.aspx" target="_blank"&gt;http://weblogs.asp.net/podwysocki/archive/2008/10/13/functional-net-linq-or-language-integrated-monads.aspx&lt;/a&gt;&lt;/li&gt;
	&lt;li&gt;
		&lt;a href="http://mikehadlow.blogspot.com/2011/01/monads-in-c1-introduction.html" target="_blank"&gt;http://mikehadlow.blogspot.com/2011/01/monads-in-c1-introduction.html&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;
	Enjoy :)&lt;/p&gt;
</description><pubDate>Thu, 01 Mar 2012 13:25:01 GMT</pubDate><guid isPermaLink="true">http://www.robychechi.it:80/roby/extending-the-world-related-material</guid></item><item><title>Extending the world, step 4</title><link>http://www.robychechi.it:80/roby/extending-the-world-step-4</link><description>&lt;p&gt;
	&lt;a href="http://www.robychechi.it/roby/tech-blog/extending-the-world-step-3"&gt;Last time&lt;/a&gt; we introduced a new simple exercise, where we have a computation which might fails and we want to to try to remove all the noise that the error handling introduces all around the algorithm. We talked about &lt;strong&gt;Monads&lt;/strong&gt; (in a very simplified way) and we defined a way we could write our computation inside a Linq expression, using a Monad to isolate the unwanted error handling code. What we still have to do is actually implement this new Monad and see how we can leverage this concepts and strategies to reach our goal.&lt;/p&gt;
&lt;p&gt;
	Following a few simple steps, we had arrived to this way to express our computation:&lt;/p&gt;
&lt;pre class="brush: csharp"&gt;
var r = from x in M.Unit(fi)
        from y in M.Unit(fj)
        from x in M.Unit(fk)
        select x + y + k;&lt;/pre&gt;
&lt;p&gt;
	We already said that this &amp;quot;would&amp;quot; compile as long as we provide the right methods to enable Linq to host and execute our code on our Monad. Let&amp;#39;s first give a better definition about our Monad, so that we will be able to figure out how we should implement all the details. Basically our Monad will have to isolate the error handling code from the actual computation, which we should be able to express in a compositional way. The idea is that the Monad will be the only actor aware of the error handling, and it will be in charge of keeping track of computation executions and of their actual success or failure. We already said that a Monad by definition has to supply &lt;strong&gt;unit &lt;/strong&gt;and &lt;strong&gt;bind&lt;/strong&gt;, and it is actually bind that will takes care of the specific behavior of our Monad.&lt;/p&gt;
&lt;p&gt;
	We still have to give this Monad a name, and given its description I think that &lt;span style="font-family:courier new,courier,monospace;"&gt;ValueOrError&lt;/span&gt; is a good one. Let&amp;#39;s write a (very) basic implementation of a class that is able to hold a value or an error condition:&lt;/p&gt;
&lt;pre class="brush: csharp"&gt;
public class ValueOrError&amp;lt;T&amp;gt;
{
	private readonly Exception error;
	private readonly T value;
	private readonly Func&amp;lt;T&amp;gt; eval;
	internal ValueOrError(Func&amp;lt;T&amp;gt; eval)
	{
		this.eval = eval;
	}
	internal ValueOrError(T value)
	{
		this.value = value;
	}
	internal ValueOrError(Exception error)
	{
		this.error = error;
	}
	public T Value
	{
		get { return eval != null ? eval() : value; }
	}
	public Exception Error
	{
		get { return error; }
	}
	public bool HasError
	{
		get { return error != null; }
	}
	public bool HasValue
	{
		get { return !HasError; }
	}
}&lt;/pre&gt;
&lt;p&gt;
	We wrote a generic type, and we specified a costructor to hold an error, and 2 constructor to store respectively a value of type &lt;span style="font-family:courier new,courier,monospace;"&gt;T&lt;/span&gt;, or a function which is able to produce a value of type &lt;span style="font-family:courier new,courier,monospace;"&gt;T&lt;/span&gt;. We could make this code more interesting, but it is enough for our exercise. We also did not manage any specific execution behavior yet, we will do that later. We already know that, to be a Monad, a type must supply 2 special functions, &lt;strong&gt;unit&lt;/strong&gt; and &lt;strong&gt;bind&lt;/strong&gt;. Let&amp;#39;s write those as extension methods of &lt;span style="font-family:courier new,courier,monospace;"&gt;ValueOrError&amp;lt;T&amp;gt;&lt;/span&gt; inside some static class (&lt;span style="font-family:courier new,courier,monospace;"&gt;ValueOrErrorExtensions&lt;/span&gt; for example), and let&amp;#39;s start with &lt;span style="font-family:courier new,courier,monospace;"&gt;Unit&lt;/span&gt;:&lt;/p&gt;
&lt;pre class="brush: csharp"&gt;
public static ValueOrError&amp;lt;T&amp;gt; Unit&amp;lt;T&amp;gt;(this T source)
{
	return new ValueOrError&amp;lt;T&amp;gt;(source);
}
public static ValueOrError&amp;lt;T&amp;gt; Unit&amp;lt;T&amp;gt;(this Func&amp;lt;T&amp;gt; source)
{
	return new ValueOrError&amp;lt;T&amp;gt;(source);
}&lt;/pre&gt;
&lt;p&gt;
	For &lt;span style="font-family:courier new,courier,monospace;"&gt;Unit&lt;/span&gt; we have 2 overloads which are mapping the 2 constructors dealing with &amp;quot;values&amp;quot; we have in &lt;span style="font-family:courier new,courier,monospace;"&gt;ValueOrError&amp;lt;T&amp;gt;&lt;/span&gt;, and these overloads fulfill the &lt;strong&gt;unit&lt;/strong&gt; mission: put a value inside the Monad.&lt;/p&gt;
&lt;p&gt;
	Let&amp;#39;s move on to &lt;strong&gt;bind&lt;/strong&gt;, here we need an implementation which has to have the signature we described in the previous episode:&lt;/p&gt;
&lt;pre class="brush: csharp"&gt;
M&amp;lt;TR&amp;gt; Bind&amp;lt;TS, TR&amp;gt;(this M&amp;lt;TS&amp;gt; source, Func&amp;lt;TS, M&amp;lt;TR&amp;gt;&amp;gt; selector)&lt;/pre&gt;
&lt;p&gt;
	A &lt;strong&gt;bind&lt;/strong&gt; is supposed to accomplish these steps:&lt;/p&gt;
&lt;ol&gt;
	&lt;li&gt;
		extract the value(s) of type &lt;span style="font-family:courier new,courier,monospace;"&gt;TS&lt;/span&gt; from the input &lt;span style="font-family:courier new,courier,monospace;"&gt;ValueOrError&amp;lt;TS&amp;gt;&lt;/span&gt;&lt;/li&gt;
	&lt;li&gt;
		apply the supplied function, which transforms the value(s) of type &lt;span style="font-family:courier new,courier,monospace;"&gt;TS &lt;/span&gt;in value(s) of type &lt;span style="font-family:courier new,courier,monospace;"&gt;TR&lt;/span&gt; and then puts it (or them) in &lt;span style="font-family:courier new,courier,monospace;"&gt;ValueOrError&amp;lt;TR&amp;gt;&lt;/span&gt;&lt;/li&gt;
	&lt;li&gt;
		return the just created instance of &lt;span style="font-family:courier new,courier,monospace;"&gt;ValueOrError&amp;lt;TR&amp;gt;&lt;/span&gt;&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;
	This is what we expect from a &lt;strong&gt;bind&lt;/strong&gt;, but while doing this job this method can actually do more things, and in our scenario we know that we need someone who handles errors in a proper way. Let&amp;#39;s define what &amp;quot;proper&amp;quot; is:&lt;/p&gt;
&lt;ul&gt;
	&lt;li&gt;
		&lt;span style="font-family:courier new,courier,monospace;"&gt;Bind&lt;/span&gt; should check if the source &lt;span style="font-family:courier new,courier,monospace;"&gt;ValueOrError&amp;lt;TS&amp;gt;&lt;/span&gt; already contains an error, if yes we know that we should not go on with further processing, so we just create an instance of &lt;span style="font-family:courier new,courier,monospace;"&gt;ValueOrError&amp;lt;TR&amp;gt;&lt;/span&gt; (because we have to go from &lt;span style="font-family:courier new,courier,monospace;"&gt;TS &lt;/span&gt;to &lt;span style="font-family:courier new,courier,monospace;"&gt;TR&lt;/span&gt;), using the constructor which receives an &lt;span style="font-family:courier new,courier,monospace;"&gt;Exception&lt;/span&gt; and supplying the error condition of the source &lt;span style="font-family:courier new,courier,monospace;"&gt;ValueOrError&amp;lt;TR&amp;gt;&lt;/span&gt; as its input; this way we are stopping the execution chain and passing along the already generated error condition, although wrapped in a new Monad&lt;/li&gt;
	&lt;li&gt;
		on the other hand, if the source is a valid value, we can go on with the computation, so we just need to extract the source value and pass it to the &lt;span style="font-family:courier new,courier,monospace;"&gt;selector&lt;/span&gt; function which puts the value inside a Monad of type &lt;span style="font-family:courier new,courier,monospace;"&gt;ValueOrError&amp;lt;TR&amp;gt;&lt;/span&gt;; if we are in a case where the Monad has been supplied a &lt;span style="font-family:courier new,courier,monospace;"&gt;Func&amp;lt;T&amp;gt;&lt;/span&gt; as a constructor parameter, reading its value will actually execute the supplied function, so it is enough to do that inside a &lt;span style="font-family:courier new,courier,monospace;"&gt;try...catch&lt;/span&gt; block and, in case of error, return an instance of &lt;span style="font-family:courier new,courier,monospace;"&gt;ValueOrError&amp;lt;TR&amp;gt;&lt;/span&gt; containing the thrown exception as the error condition&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;
	This is definitely easier to read in code:&lt;/p&gt;
&lt;pre class="brush: csharp"&gt;
public static ValueOrError&amp;lt;TR&amp;gt; Bind&amp;lt;TS, TR&amp;gt;(
        this ValueOrError&amp;lt;TS&amp;gt; source, 
        Func&amp;lt;TS, ValueOrError&amp;lt;TR&amp;gt;&amp;gt; selector)
{
	if (source.HasError)
		return new ValueOrError&amp;lt;TR&amp;gt;(source.Error);
	try
	{
		return selector(source.Value);
	}
	catch (Exception ex)
	{
		return new ValueOrError&amp;lt;TR&amp;gt;(ex);
	}
}&lt;/pre&gt;
&lt;p&gt;
	It&amp;#39;s very simple, but it&amp;#39;s clean and isolated in one point. We could have also moved the &lt;span style="font-family:courier new,courier,monospace;"&gt;try...catch&lt;/span&gt; block directly inside the &lt;span style="font-family:courier new,courier,monospace;"&gt;ValueOrError&amp;lt;T&amp;gt;&lt;/span&gt; class, but this is a detail and it is not so relevant for our discussion. What&amp;#39;s relevant is how to trigger this mechanism, and we already saw that we are going to have this code run inside Linq expressions. Let&amp;#39;s write the simplest Linq expression we can, as we did the last time:&lt;/p&gt;
&lt;pre class="brush: csharp"&gt;
var r = from i in ValueOrError.Unit(fi) select i;&lt;/pre&gt;
&lt;p&gt;
	which is equivalent to this:&lt;/p&gt;
&lt;pre class="brush: csharp"&gt;
var r = ValueOrError.Unit(fi).Select(i =&amp;gt; i);&lt;/pre&gt;
&lt;p&gt;
	We need to implement &lt;span style="font-family:courier new,courier,monospace;"&gt;Select&lt;/span&gt;, and we can take advantage of &lt;span style="font-family:courier new,courier,monospace;"&gt;Bind &lt;/span&gt;and &lt;span style="font-family:courier new,courier,monospace;"&gt;Unit &lt;/span&gt;to do it in a simple way:&lt;/p&gt;
&lt;pre class="brush: csharp"&gt;
public static ValueOrError&amp;lt;TR&amp;gt; Select&amp;lt;TS, TR&amp;gt;(
        this ValueOrError&amp;lt;TS&amp;gt; source, 
        Func&amp;lt;TS, TR&amp;gt; selector)
{
	return source.Bind(s =&amp;gt; selector(s).Unit());
}&lt;/pre&gt;
&lt;p&gt;
	Again very simple, and our knowledge about how to go from &lt;span style="font-family:courier new,courier,monospace;"&gt;T&lt;/span&gt; to &lt;span style="font-family:courier new,courier,monospace;"&gt;ValueOrError&amp;lt;T&amp;gt;&lt;/span&gt;, about how to go from &lt;span style="font-family:courier new,courier,monospace;"&gt;ValueOrError&amp;lt;TS&amp;gt;&lt;/span&gt; to &lt;span style="font-family:courier new,courier,monospace;"&gt;ValueOrError&amp;lt;TR&amp;gt;&lt;/span&gt;, and most important about how to deal with errors, is hidden inside &lt;span style="font-family:courier new,courier,monospace;"&gt;Unit &lt;/span&gt;and &lt;span style="font-family:courier new,courier,monospace;"&gt;Bind&lt;/span&gt;. The result of our computation will be an instance of &lt;span style="font-family:courier new,courier,monospace;"&gt;ValueOrError&amp;lt;T&amp;gt;&lt;/span&gt; containing either the computed value &lt;span style="font-family:courier new,courier,monospace;"&gt;fi()&lt;/span&gt;, or the error condition encountered during the execution. This was very trivial and we might have done it without all the Monad theory and the Linq support, but as soon as we try to implement more complex computations we start appreciating the added value of these mechanisms. Let&amp;#39;s go back to our &amp;quot;complex&amp;quot; algorithm:&lt;/p&gt;
&lt;pre class="brush: csharp"&gt;
var r = from x in ValueOrError.Unit(fi)
        from y in ValueOrError.Unit(fj)
        from x in ValueOrError.Unit(fk)
        select x + y + k;&lt;/pre&gt;
&lt;p&gt;
	If we&amp;#39;d try to write the expression as a composition of method calls, we should come up with something like this:&lt;/p&gt;
&lt;pre class="brush: csharp"&gt;
var q = ValueOrError.Unit(fi)
                    .SelectMany( i      =&amp;gt; ValueOrError.Unit(fj), 
                                (i,  j) =&amp;gt; new {i, j})
                    .SelectMany( @t     =&amp;gt; ValueOrError.Unit(fk), 
                                (@t, k) =&amp;gt; @t.i + @t.j + k);&lt;/pre&gt;
&lt;p&gt;
	Now it is clear that we need to implement &lt;span style="font-family:courier new,courier,monospace;"&gt;SelectMany &lt;/span&gt;for our Monad, and at the same time we can appreciate that the query syntax is much more readable than the methods chain, which by the way makes explicit a temporary range variable &lt;span style="font-family:courier new,courier,monospace;"&gt;@t&lt;/span&gt; that the query syntax manages to keep hidden. Let&amp;#39;s implement &lt;span style="font-family:courier new,courier,monospace;"&gt;SelectMany&lt;/span&gt;, in terms of &lt;span style="font-family:courier new,courier,monospace;"&gt;Unit &lt;/span&gt;and &lt;span style="font-family:courier new,courier,monospace;"&gt;Select &lt;/span&gt;(which is based on &lt;span style="font-family:courier new,courier,monospace;"&gt;Unit &lt;/span&gt;and &lt;span style="font-family:courier new,courier,monospace;"&gt;Bind&lt;/span&gt;):&lt;/p&gt;
&lt;pre class="brush: csharp"&gt;
public static ValueOrError&amp;lt;TR&amp;gt; SelectMany&amp;lt;TS, TC, TR&amp;gt;(
        this ValueOrError&amp;lt;TS&amp;gt; source, 
        Func&amp;lt;TS, ValueOrError&amp;lt;TC&amp;gt;&amp;gt; matcher, 
        Func&amp;lt;TS, TC, TR&amp;gt; selector)
{
	return source.Bind(s =&amp;gt; matcher(s).Select(t =&amp;gt; selector(s, t)));
}&lt;/pre&gt;
&lt;p&gt;
	If we analyze its signature and we forget for a moment about the last parameter, we can see that it matches the &lt;span style="font-family:courier new,courier,monospace;"&gt;Bind &lt;/span&gt;signature, and the last parameter just adds an additional level of indirection, which brings us some more flexibility and actually enables the nice query syntax we are trying to use. &lt;span style="font-family:courier new,courier,monospace;"&gt;SelectMany &lt;/span&gt;itself is just using &lt;span style="font-family:courier new,courier,monospace;"&gt;Bind &lt;/span&gt;and &lt;span style="font-family:courier new,courier,monospace;"&gt;Select&lt;/span&gt;, and there are several amazing things around its implementation:&lt;/p&gt;
&lt;ul&gt;
	&lt;li&gt;
		these very short and neat lines of codes inside our extension methods enable such a clear and coincise Linq expression describing our computation&lt;/li&gt;
	&lt;li&gt;
		if you try to follow every single method call to get to the final result, you will immediately notice how complex the call sequence can get, and all this complexity is handled by 4 method, where 3 of them are just one line of code, and the more complex one is just an if statement followed by a function call inside a &lt;span style="font-family:courier new,courier,monospace;"&gt;try...catch&lt;/span&gt; block&lt;/li&gt;
	&lt;li&gt;
		we already said that we wrote &lt;span style="font-family:courier new,courier,monospace;"&gt;Select &lt;/span&gt;and &lt;span style="font-family:courier new,courier,monospace;"&gt;SelectMany &lt;/span&gt;in terms of &lt;span style="font-family:courier new,courier,monospace;"&gt;Bind &lt;/span&gt;and &lt;span style="font-family:courier new,courier,monospace;"&gt;Unit&lt;/span&gt;, but what we did not said is that, following this pattern, whatever Monad you will be writing you will just need to reimplement &lt;span style="font-family:courier new,courier,monospace;"&gt;Bind &lt;/span&gt;and &lt;span style="font-family:courier new,courier,monospace;"&gt;Unit&lt;/span&gt;, whereas &lt;span style="font-family:courier new,courier,monospace;"&gt;Select &lt;/span&gt;and &lt;span style="font-family:courier new,courier,monospace;"&gt;SelectMany &lt;/span&gt;will stay exactly the same!&lt;/li&gt;
	&lt;li&gt;
		if you think that methods like &lt;span style="font-family:courier new,courier,monospace;"&gt;SelectMany &lt;/span&gt;are hard to understand, you should just use the trick to &amp;quot;follow the types&amp;quot; and you will be able to write that line of code by yourself; let&amp;#39;s try together:
		&lt;ul&gt;
			&lt;li&gt;
				&lt;span style="font-family:courier new,courier,monospace;"&gt;SelectMany &lt;/span&gt;and &lt;span style="font-family:courier new,courier,monospace;"&gt;Bind &lt;/span&gt;have the same first argument and the first return type, so we can start writing this: &lt;span style="font-family:courier new,courier,monospace;"&gt;return source.Bind(...); &lt;/span&gt;&lt;/li&gt;
			&lt;li&gt;
				&lt;span style="font-family:courier new,courier,monospace;"&gt;Bind &lt;/span&gt;expects a second argument of type &lt;span style="font-family:courier new,courier,monospace;"&gt;Func&amp;lt;TS, ValueOrError&amp;lt;TR&amp;gt;&amp;gt;&lt;/span&gt;, and we have &lt;span style="font-family:courier new,courier,monospace;"&gt;matcher &lt;/span&gt;and &lt;span style="font-family:courier new,courier,monospace;"&gt;selector &lt;/span&gt;with signatures which do not help, but we also have &lt;span style="font-family:courier new,courier,monospace;"&gt;Select &lt;/span&gt;available, which goes from &lt;span style="font-family: courier new,courier,monospace;"&gt;ValueOrError&amp;lt;T1&amp;gt;&lt;/span&gt; to &lt;span style="font-family: courier new,courier,monospace;"&gt;ValueOrError&amp;lt;T2&amp;gt;&lt;/span&gt;, so we can call &lt;span style="font-family:courier new,courier,monospace;"&gt;matcher &lt;/span&gt;on &lt;span style="font-family:courier new,courier,monospace;"&gt;TS&lt;/span&gt;, obtaining a &lt;span style="font-family: courier new,courier,monospace;"&gt;ValueOrError&amp;lt;TC&amp;gt;&lt;/span&gt;, and then call &lt;span style="font-family:courier new,courier,monospace;"&gt;Select &lt;/span&gt;on it to go to &lt;span style="font-family: courier new,courier,monospace;"&gt;ValueOrError&amp;lt;TR&amp;gt;&lt;/span&gt; thanks to &lt;span style="font-family:courier new,courier,monospace;"&gt;selector&lt;/span&gt;, which can be called from &amp;quot;inside&amp;quot; &lt;span style="font-family:courier new,courier,monospace;"&gt;Select &lt;/span&gt;supplying it the instances of &lt;span style="font-family:courier new,courier,monospace;"&gt;TS &lt;/span&gt;and &lt;span style="font-family:courier new,courier,monospace;"&gt;TC &lt;/span&gt;that at that point would be available&lt;/li&gt;
		&lt;/ul&gt;
	&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;
	So far we wrote nice and clean code, but we didn&amp;#39;t really analyze what this code does when dealing with real scenarios. Let&amp;#39;s try to follow a chain of computations considering a case where our 3 functions succeed:&lt;/p&gt;
&lt;ol&gt;
	&lt;li&gt;
		&lt;span style="font-family:courier new,courier,monospace;"&gt;fi&lt;/span&gt; is put inside a &lt;span style="font-family:courier new,courier,monospace;"&gt;ValueOrError&amp;lt;...&amp;gt;&lt;/span&gt; (let&amp;#39;s call it &lt;span style="font-family:courier new,courier,monospace;"&gt;VOE^fi&lt;/span&gt;, and we&amp;#39;ll implicitly use this notation for similar actions in further steps)&lt;/li&gt;
	&lt;li&gt;
		&lt;span style="font-family:courier new,courier,monospace;"&gt;SelectMany &lt;/span&gt;is called over &lt;span style="font-family:courier new,courier,monospace;"&gt;VOE^fi &lt;/span&gt;&lt;/li&gt;
	&lt;li&gt;
		inside &lt;span style="font-family:courier new,courier,monospace;"&gt;SelectMany&lt;/span&gt;, &lt;span style="font-family:courier new,courier,monospace;"&gt;Bind &lt;/span&gt;is called over &lt;span style="font-family:courier new,courier,monospace;"&gt;VOE^fi&lt;/span&gt;&lt;/li&gt;
	&lt;li&gt;
		&lt;span style="font-family:courier new,courier,monospace;"&gt;VOE^fi&lt;/span&gt; is checked for errors, it does not have any therefore we go on&lt;/li&gt;
	&lt;li&gt;
		&lt;span style="font-family:courier new,courier,monospace;"&gt;Value &lt;/span&gt;is extracted from&lt;span style="font-family:courier new,courier,monospace;"&gt; VOE^fi&lt;/span&gt; =&amp;gt; &lt;span style="font-family:courier new,courier,monospace;"&gt;fi()&lt;/span&gt; is called, let&amp;#39;s call its return value &lt;span style="font-family:courier new,courier,monospace;"&gt;fi!&lt;/span&gt; (we&amp;#39;ll implicitly use this notation for similar actions)&lt;/li&gt;
	&lt;li&gt;
		&lt;span style="font-family:courier new,courier,monospace;"&gt;fi!&lt;/span&gt; is passed to &lt;span style="font-family:courier new,courier,monospace;"&gt;Bind&lt;/span&gt;&amp;#39;s selector, which at this point was &lt;span style="font-family:courier new,courier,monospace;"&gt;matcher(s).Select(t =&amp;gt; selector(s, t))&lt;/span&gt;, which via substitution becomes &lt;span style="font-family:courier new,courier,monospace;"&gt;ValueOrError.Unit(fj).Select(t =&amp;gt; selector(s, t))&lt;/span&gt;, which eventually becomes &lt;span style="font-family:courier new,courier,monospace;"&gt;(VOE^fj).Select(t =&amp;gt; selector(s, t))&lt;/span&gt;&lt;/li&gt;
	&lt;li&gt;
		&lt;span style="font-family:courier new,courier,monospace;"&gt;Select &lt;/span&gt;is called over &lt;span style="font-family:courier new,courier,monospace;"&gt;VOE^fj&lt;/span&gt;, which means &lt;span style="font-family:courier new,courier,monospace;"&gt;(VOE^fj).Bind(s =&amp;gt; selector(s).Unit())&lt;/span&gt;&lt;/li&gt;
	&lt;li&gt;
		&lt;span style="font-family:courier new,courier,monospace;"&gt;Bind &lt;/span&gt;is called over &lt;span style="font-family:courier new,courier,monospace;"&gt;VOE^fj&lt;/span&gt;, we do not detect error conditions so we call &lt;span style="font-family:courier new,courier,monospace;"&gt;fj()&lt;/span&gt;, obtaining &lt;span style="font-family:courier new,courier,monospace;"&gt;fj!&lt;/span&gt;, and we pass it to &lt;span style="font-family:courier new,courier,monospace;"&gt;s =&amp;gt; selector(s).Unit()&lt;/span&gt;, which by substitution is &lt;span style="font-family:courier new,courier,monospace;"&gt;((i, j) =&amp;gt; new {i, j}).Unit()&lt;/span&gt;, where &lt;span style="font-family:courier new,courier,monospace;"&gt;i = fi!&lt;/span&gt; and &lt;span style="font-family:courier new,courier,monospace;"&gt;j = fj!&lt;/span&gt;; the anonymous type contains the first 2 results and it is put back in the &lt;span style="font-family:courier new,courier,monospace;"&gt;ValueOrError&amp;lt;...&amp;gt;&lt;/span&gt; via &lt;span style="font-family:courier new,courier,monospace;"&gt;Unit()&lt;/span&gt;&lt;/li&gt;
	&lt;li&gt;
		we repeat the same steps with the second &lt;span style="font-family:courier new,courier,monospace;"&gt;SelectMany&lt;/span&gt;, this will let our anonymous type pass through, &lt;span style="font-family:courier new,courier,monospace;"&gt;fk()&lt;/span&gt; will be called, and at the end of the same chain we just described we will get to &lt;span style="font-family:courier new,courier,monospace;"&gt;(@t, k) =&amp;gt; @t.i + @t.j + k&lt;/span&gt;, where &lt;span style="font-family:courier new,courier,monospace;"&gt;@t&lt;/span&gt; is our previous anonymous type and &lt;span style="font-family:courier new,courier,monospace;"&gt;k = fk!&lt;/span&gt;: the actual sum will be performed&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;
	It is not exactly easy to explain, I hope I did not loose you here, if you try to follow such a code with a debugger you will be able to track down what&amp;#39;s happening. But we built all this infrastructure to deal with errors, so we should show an example of such a case, and let&amp;#39;s suppose the very first computation fails:&lt;/p&gt;
&lt;ol&gt;
	&lt;li&gt;
		&lt;span style="font-family:courier new,courier,monospace;"&gt;fi&lt;/span&gt; is put inside a &lt;span style="font-family:courier new,courier,monospace;"&gt;ValueOrError&amp;lt;...&amp;gt;&lt;/span&gt;&lt;/li&gt;
	&lt;li&gt;
		&lt;span style="font-family:courier new,courier,monospace;"&gt;SelectMany &lt;/span&gt;is called over &lt;span style="font-family:courier new,courier,monospace;"&gt;VOE^fi&lt;/span&gt;&lt;/li&gt;
	&lt;li&gt;
		inside &lt;span style="font-family:courier new,courier,monospace;"&gt;SelectMany&lt;/span&gt;, &lt;span style="font-family:courier new,courier,monospace;"&gt;Bind &lt;/span&gt;is called over &lt;span style="font-family:courier new,courier,monospace;"&gt;VOE^fi&lt;/span&gt;&lt;/li&gt;
	&lt;li&gt;
		&lt;span style="font-family:courier new,courier,monospace;"&gt;VOE^fi&lt;/span&gt; is checked for errors, it does not have any so we go on (it&amp;#39;s not been computed yet)&lt;/li&gt;
	&lt;li&gt;
		&lt;span style="font-family:courier new,courier,monospace;"&gt;Value &lt;/span&gt;is extracted from &lt;span style="font-family:courier new,courier,monospace;"&gt;VOE^fi&lt;/span&gt; =&amp;gt; &lt;span style="font-family:courier new,courier,monospace;"&gt;fi()&lt;/span&gt; is called and this time it fails, so an exception is raised and trapped, and a &lt;span style="font-family:courier new,courier,monospace;"&gt;VOE^ERROR&lt;/span&gt; is returned&lt;/li&gt;
	&lt;li&gt;
		because &lt;span style="font-family:courier new,courier,monospace;"&gt;fi()&lt;/span&gt; failed, &lt;span style="font-family:courier new,courier,monospace;"&gt;selector &lt;/span&gt;is never called, so &lt;span style="font-family:courier new,courier,monospace;"&gt;Bind &lt;/span&gt;returns &lt;span style="font-family:courier new,courier,monospace;"&gt;VOE^ERROR&lt;/span&gt; to &lt;span style="font-family:courier new,courier,monospace;"&gt;SelectMany&lt;/span&gt;, which returns it to its caller&lt;/li&gt;
	&lt;li&gt;
		the second &lt;span style="font-family:courier new,courier,monospace;"&gt;SelectMany &lt;/span&gt;is called, and we soon reach again a &lt;span style="font-family:courier new,courier,monospace;"&gt;Bind &lt;/span&gt;call, but this time we detect an error condition on the source (&lt;span style="font-family:courier new,courier,monospace;"&gt;VOE^ERROR&lt;/span&gt;) and therefore we immediately return a new &lt;span style="font-family:courier new,courier,monospace;"&gt;VOE^ERROR&lt;/span&gt; containing the same error as the source one, and we skip again the &lt;span style="font-family:courier new,courier,monospace;"&gt;selector &lt;/span&gt;call, so &lt;span style="font-family:courier new,courier,monospace;"&gt;SelectMany &lt;/span&gt;will return &lt;span style="font-family:courier new,courier,monospace;"&gt;VOE^ERR&lt;/span&gt; as a result of the whole computation&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;
	Easy, isn&amp;#39;t it? :) In both cases we will receive a &lt;span style="font-family:courier new,courier,monospace;"&gt;ValueOrError&amp;lt;T&amp;gt;&lt;/span&gt; instance, and we will just have to examine if we have met an error condition or not. What also interesting is the way we actually calculated our computation, we used the term &amp;quot;substitution&amp;quot; several times, and this is another clue that what we are doing is quite functional: our computations can be treated as mathematical expressions where you calculate intermediate results and then just use them to replace parts of expressions (lambda calculus, I guess...).&lt;/p&gt;
&lt;p&gt;
	If you are still with me, I am sure you would be curious to try something like this, and you might want to have some real code to test. Well, my next post will be dedicated to deliver you a sample project that I&amp;#39;m preparing, along with some reference material you can use to investigate more the topics of this series.&lt;/p&gt;
</description><pubDate>Tue, 17 Jan 2012 22:14:18 GMT</pubDate><guid isPermaLink="true">http://www.robychechi.it:80/roby/extending-the-world-step-4</guid></item><item><title>Extending the world, step 3</title><link>http://www.robychechi.it:80/roby/extending-the-world-step-3</link><description>&lt;p&gt;
	So far in &lt;a href="http://www.robychechi.it/roby/tech-blog/extending-the-world"&gt;our series&lt;/a&gt; we have seen how Linq is a world that can be extended if we craft our types the right way. We learned that Linq is definitely not just for &lt;span style="font-family:courier new,courier,monospace;"&gt;IEnumerable&lt;/span&gt;&lt;t&gt;&lt;span style="font-family:courier new,courier,monospace;"&gt; &lt;/span&gt;or &lt;span style="font-family:courier new,courier,monospace;"&gt;IQueryable&lt;/span&gt;&lt;t&gt;, and I&amp;#39;m more and more convinced that what&amp;#39;s most interesting about Linq is the way it guides you to write more functional code. I&amp;#39;m not a functional programmer (yet), so please do not expect too much knowledge about that from my posts, but I&amp;#39;m slowly gaining a more functional view on things, and I&amp;#39;m feeling that it&amp;#39;s a good thing to have. There are a few aspects of functional programming that Linq tries to enforce:&lt;/t&gt;&lt;/t&gt;&lt;/p&gt;
&lt;ul&gt;
	&lt;li&gt;
		&lt;em&gt;no side effects&lt;/em&gt;: the code we write should not deal with the production of anything which is not strictly related to our result, and which in some way modifies a &amp;quot;global state&amp;quot;&lt;/li&gt;
	&lt;li&gt;
		&lt;em&gt;immutability&lt;/em&gt;: what&amp;#39;s defined inside a Linq expression should be immutable, and this is a good thing because it helps avoiding side effects (see previous point)&lt;/li&gt;
	&lt;li&gt;
		&lt;em&gt;declarativity&lt;/em&gt;: inside Linq we do not think in terms of state and statements, but in terms of declarations: we tend to describe more &lt;em&gt;what &lt;/em&gt;we want from a computation, and less &lt;em&gt;how &lt;/em&gt;we want any result to be computed&lt;/li&gt;
	&lt;li&gt;
		&lt;em&gt;compositionality&lt;/em&gt;: within a Linq expression we can compose computations, chaining hen and mixing them thanks to the operators we have available (of course the types we are using in our expression must support them), resulting in better readability of the intents we have (see previous point)&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;
	There are more, of course, but let&amp;#39;s stay with these and let&amp;#39;s try to expand them. To me it is easier to do it with samples, so here we go.&lt;/p&gt;
&lt;p&gt;
	Let&amp;#39;s imagine that we have to compute 3 values and to sum them, but let&amp;#39;s say that our 3 inputs are calculated or retrieved by someone who may fail (a db connection? a web service? you name it). Those are precious resources, and we do not want to waste them, so in a sequential world (too early to talk about parallelism or async, sorry... :) ) we would prefer to avoid the subsequent calls if a previous one failed, invalidating the whole computation. At the same time, if something went wrong, we do not want the whole process to fail, but we want to collect information about the error that occurred. How would you write such a code? Maybe something like this:&lt;/p&gt;
&lt;pre class="brush: csharp"&gt;
int r = 0;
Exception error;
try
{
	r = fi();
}
catch(Exception ex)
{
	error = ex;
}
if (error == null)
{
	try
	{
		r = r + fj();
	}
	catch(Exception ex)
	{
		error = ex;
	}
}
if (error == null)
{
	try
	{
		r = r + fk();
	}
	catch(Exception ex)
	{
		error = ex;
	}
}
if (error == null)
{
	...
}
else
{
	...
}&lt;/pre&gt;
&lt;p&gt;
	Not so good looking... I will not explain the details, the code is trivial, and actually it could be improved a little, but still you would have something where you would not easily spot the true essence of the algorithm, which indeed is:&lt;/p&gt;
&lt;pre class="brush: csharp"&gt;
int r = fi() + fj() + fk();&lt;/pre&gt;
&lt;p&gt;
	What&amp;#39;s really noisy here is the error handling, which is distracting you from the heart of the computation, but you cannot avoid it and it makes your code less readable. You would like to clean it up, moving the error handling &amp;quot;somewhere else&amp;quot;. Something like the well known AOP approach, but you still want to check if something went wrong in the context of your code. And if you go back to our list of functional characteristics, you can also look at the errors as &amp;quot;side effects&amp;quot;, which should really be avoided, or at least isolated from our computation.&lt;/p&gt;
&lt;p&gt;
	A functional programmer at this point would say the magic world: you need a &lt;strong&gt;Monad&lt;/strong&gt;! He might also say that you need a Maybe Monad, or something similar. What a Monad really is, it is still not 100% clear to me, and not being a functional programmer (yet) I try to bring that idea in the space I know better and with the concept I&amp;#39;m used to deal with. So, to me a Monad is a &amp;quot;container&amp;quot;, or a &amp;quot;decorator&amp;quot;, which is able to &amp;quot;augment&amp;quot; some other instance, or set of instances, of some type T. Let&amp;#39;s call out Monad &lt;span style="font-family:courier new,courier,monospace;"&gt;M&amp;lt;T&amp;gt;&lt;/span&gt;. A Monad should also, in some way, supply 2 special &amp;quot;static&amp;quot; functions:&lt;/p&gt;
&lt;ul&gt;
	&lt;li&gt;
		&lt;strong&gt;return&lt;/strong&gt;, or&amp;nbsp;&lt;strong&gt;unit&lt;/strong&gt;: such a function, given a type T, returns an &lt;span style="font-family:courier new,courier,monospace;"&gt;M&amp;lt;T&amp;gt;&lt;/span&gt;; its job is to take something and &amp;quot;put it&amp;quot; into the Monad&lt;/li&gt;
	&lt;li&gt;
		&lt;strong&gt;bind&lt;/strong&gt;: such a function should receive an instance of &lt;span style="font-family:courier new,courier,monospace;"&gt;M&amp;lt;T&amp;gt;&lt;/span&gt;, and a function that goes from &lt;span style="font-family:courier new,courier,monospace;"&gt;T&lt;/span&gt; to &lt;span style="font-family:courier new,courier,monospace;"&gt;M&amp;lt;R&amp;gt;&lt;/span&gt;, and returns an instance of &lt;span style="font-family:courier new,courier,monospace;"&gt;M&amp;lt;R&amp;gt;&lt;/span&gt;; in other words, it&amp;#39;s job is to &amp;quot;extract&amp;quot; the value(s) of type &lt;span style="font-family:courier new,courier,monospace;"&gt;T&lt;/span&gt; from &lt;span style="font-family:courier new,courier,monospace;"&gt;M&amp;lt;T&amp;gt;&lt;/span&gt;, then to apply the function that transform the value(s) of type &lt;span style="font-family:courier new,courier,monospace;"&gt;T&lt;/span&gt; in value(s) of type &lt;span style="font-family:courier new,courier,monospace;"&gt;R&lt;/span&gt; and puts it (them) in &lt;span style="font-family:courier new,courier,monospace;"&gt;M&amp;lt;R&amp;gt;&lt;/span&gt;, finally returning the instance of &lt;span style="font-family:courier new,courier,monospace;"&gt;M&amp;lt;R&amp;gt;&lt;/span&gt; created&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;
	Let&amp;#39;s write the signatures:&lt;/p&gt;
&lt;ul&gt;
	&lt;li&gt;
		&lt;strong&gt;unit&lt;/strong&gt;: &lt;span style="font-family:courier new,courier,monospace;"&gt;Func&amp;lt;T, M&amp;lt;T&amp;gt;&amp;gt;&lt;/span&gt;&lt;/li&gt;
	&lt;li&gt;
		&lt;strong&gt;bind&lt;/strong&gt;: &lt;span style="font-family:courier new,courier,monospace;"&gt;Func&amp;lt;M&amp;lt;T&amp;gt;, Func&amp;lt;T, M&amp;lt;R&amp;gt;&amp;gt;, M&amp;lt;R&amp;gt;&amp;gt;&lt;/span&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;
	What&amp;#39;s important is that both know the internals and the mechanics of the Monad, and they should be the only ones to know such details. We&amp;#39;ll get back to them later, for now let&amp;#39;s supposed we have them, and let&amp;#39;s use &lt;strong&gt;unit&lt;/strong&gt; like this:&lt;/p&gt;
&lt;pre class="brush: csharp"&gt;
int r = M.Unit(fi) + M.Unit(fj) + M.Unit(fk);&lt;/pre&gt;
&lt;p&gt;
	What did we do here? We simply put each of our functions (in a Monad we can put everything, so functions are welcome to) inside an instance of our Monad, and then we sum those instances as if we were still dealing with functions return values. Lovely... but this does not work. It does not even compile, of course, we do not have the + operator defined on our Monad, and we cannot define one because &lt;span style="font-family:courier new,courier,monospace;"&gt;M&amp;lt;T&amp;gt;&lt;/span&gt; is generic, and we don&amp;#39;t know how to implement the sum. And then, what about implementing all the other operators (-, *, /, ...)? We do not want to do that, of course, the goal of our Monad is to deal with whatever is NOT the computation. So what?&lt;/p&gt;
&lt;p&gt;
	Enter Linq. As the title of this series says, let&amp;#39;s extend the world (Linq) to understand our Monad. We already learned how to extend Linq, we just have to supply the right functions to implement the right operators. But first, why do we need Linq? Because Linq has a nice syntax that let us declare computations in a clean way, and because incidentally (well, probably not so incidentally) the &lt;strong&gt;select &lt;/strong&gt;operator would help us a lot. Let&amp;#39;s see it&amp;#39;s signature:&lt;/p&gt;
&lt;pre class="brush: csharp"&gt;
Func&amp;lt;M&amp;lt;T&amp;gt;, Func&amp;lt;T, R&amp;gt;, M&amp;lt;R&amp;gt;&amp;gt; &lt;/pre&gt;
&lt;p&gt;
	It&amp;#39;s similar to &amp;quot;bind&amp;quot;, but it&amp;#39;s not the same: &lt;strong&gt;select&lt;/strong&gt; receives an &amp;quot;augmented&amp;quot; value (or values), extracts it (them) from the &amp;quot;augmenting&amp;quot; Monad, applies to the value(s) a function which transform it (them) to something of type &lt;span style="font-family:courier new,courier,monospace;"&gt;R&lt;/span&gt;, and finally puts it (them) in &lt;span style="font-family:courier new,courier,monospace;"&gt;M&lt;/span&gt; again, returning it to then following piece of computation. We have 3 interesting points here:&lt;/p&gt;
&lt;ul&gt;
	&lt;li&gt;
		the function that goes from &lt;span style="font-family:courier new,courier,monospace;"&gt;T&lt;/span&gt; to &lt;span style="font-family:courier new,courier,monospace;"&gt;R&lt;/span&gt; is supplied by us, we are the ones knowing how to do that&lt;/li&gt;
	&lt;li&gt;
		&lt;strong&gt;select&lt;/strong&gt; will just extract things from Monad, then will call us to transform them in something else, and finally will put the result back in the Monad&lt;/li&gt;
	&lt;li&gt;
		&lt;strong&gt;select&lt;/strong&gt; will use &lt;strong&gt;bind&lt;/strong&gt; to do part of its job, and this will keep the deep knowledge of the internals of the Monad inside &lt;strong&gt;bind&lt;/strong&gt; (and &lt;strong&gt;unit&lt;/strong&gt;): we will say that &lt;strong&gt;select&lt;/strong&gt; is written in terms of &lt;strong&gt;bind&lt;/strong&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;
	Let&amp;#39;s simplify for a moment our algorithm to this:&lt;/p&gt;
&lt;pre class="brush: csharp"&gt;
int r = fi();&lt;/pre&gt;
&lt;p&gt;
	This seems stupid, but later you will understand why I did it. To do this calculation &amp;quot;inside the Monad&amp;quot;, before we tried this:&lt;/p&gt;
&lt;pre class="brush: csharp"&gt;
int r = M.From(fi);&lt;/pre&gt;
&lt;p&gt;
	but this would not compile. Let&amp;#39;s suppose we have the right implementation of the extension method &lt;span style="font-family:courier new,courier,monospace;"&gt;Select &lt;/span&gt;for our &lt;span style="font-family:courier new,courier,monospace;"&gt;M&lt;/span&gt;&amp;lt;T&amp;gt;, then we can try this:&lt;/p&gt;
&lt;pre class="brush: csharp"&gt;
var r = from x in M.From(fi) select x;&lt;/pre&gt;
&lt;p&gt;
	and this works! Actually, this expression is equivalent to this:&lt;/p&gt;
&lt;ul&gt;
	&lt;li&gt;
		calling &lt;strong&gt;unit&lt;/strong&gt;: put &lt;span style="font-family:courier new,courier,monospace;"&gt;fi()&lt;/span&gt; inside &lt;span style="font-family:courier new,courier,monospace;"&gt;M&lt;/span&gt;&lt;/li&gt;
	&lt;li&gt;
		calling &lt;strong&gt;select&lt;/strong&gt;: extracting back &lt;span style="font-family:courier new,courier,monospace;"&gt;fi()&lt;/span&gt; from &lt;span style="font-family:courier new,courier,monospace;"&gt;M&lt;/span&gt;, &amp;quot;do something&amp;quot; with &lt;span style="font-family:courier new,courier,monospace;"&gt;fi()&lt;/span&gt;, give the result back to us to &amp;quot;transform it&amp;quot; in something else (the &lt;span style="font-family:courier new,courier,monospace;"&gt;select x&lt;/span&gt; part, which in this case is just leaving the value as it is), and putting back the result in the Monad, which is returned to the left&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;
	You will have also noticed that now the lefthand side of the computation is not &lt;span style="font-family:courier new,courier,monospace;"&gt;int r&lt;/span&gt; anymore, but &lt;span style="font-family:courier new,courier,monospace;"&gt;var r&lt;/span&gt;, where &lt;span style="font-family:courier new,courier,monospace;"&gt;var&lt;/span&gt; actually stands for &lt;span style="font-family:courier new,courier,monospace;"&gt;M&amp;lt;int&amp;gt;&lt;/span&gt;. So now we are holding an instance of a Monad over our original type int, and this instance of the Monad will contain the result of our computation... well, maybe :) We&amp;#39;ll dig more about this next time.&lt;/p&gt;
&lt;p&gt;
	The final piece to get to a meaningful computation is &lt;span style="font-family:courier new,courier,monospace;"&gt;SelectMany&lt;/span&gt;, whose signature is exactly what we need to join different pieces. As long as every part is contained in the same type of Monad&lt;span style="font-family:courier new,courier,monospace;"&gt; M&amp;lt;T&amp;gt;&lt;/span&gt;, &lt;span style="font-family:courier new,courier,monospace;"&gt;SelectMany &lt;/span&gt;enhances &lt;strong&gt;select&lt;/strong&gt; and enables us to write this:&lt;/p&gt;
&lt;pre class="brush: csharp"&gt;
var r = from x in M.From(fi) 
		from y in M.From(fj) 
		from x in M.From(fk) 
		select x + y + k;&lt;/pre&gt;
&lt;p&gt;
	I&amp;#39;m sure that you can see how readable this is, the algorithm (&lt;span style="font-family:courier new,courier,monospace;"&gt;x + y + z&lt;/span&gt;) is very clear and the noise introduced by &lt;span style="font-family:courier new,courier,monospace;"&gt;M.From&lt;/span&gt; and by the query syntax is not too bad, and actually gets almost invisible when the computations get more complex. Probably still too noisy for someone using F# or Haskell, but for us in C# it&amp;#39;s not bad at all.&lt;/p&gt;
&lt;p&gt;
	This episode it&amp;#39;s been more about the concepts, and actually I did not say anything concrete about how to solve the error handling problem, this will be the topic of the next episode, where we will implement a specific Monad to solve this issue. Its implementation will also allow us to appreciate how &lt;strong&gt;unit&lt;/strong&gt;, &lt;strong&gt;bind&lt;/strong&gt; and &lt;strong&gt;select&lt;/strong&gt; are implemented to accomplish our goals.&lt;/p&gt;
</description><pubDate>Tue, 17 Jan 2012 22:14:07 GMT</pubDate><guid isPermaLink="true">http://www.robychechi.it:80/roby/extending-the-world-step-3</guid></item><item><title>Extending the world, step 2</title><link>http://www.robychechi.it:80/roby/extending-the-world-step-2</link><description>&lt;p&gt;
	In the &lt;a href="http://www.robychechi.it/roby/tech-blog/extending-the-world-step-1" target="_blank"&gt;previous episode&lt;/a&gt; of this short series, I showed how you can define a type in a way that enables it to participate to Linq queries. Linq query syntax defines a set of operators, which are mapped to methods that types involved in a Linq query must provide. If they natively do not, we can still make them work because extension methods come to the rescue. How those methods should be named and shaped is clearly documented, and it would be too much to be explained here, so I will skip these details. I&amp;#39;ll go back to our exercise and I&amp;#39;ll use it to give you some more details about a couple of interesting points.&lt;/p&gt;
&lt;p&gt;
	So we have our Twitter client:&lt;/p&gt;
&lt;pre class="brush: csharp"&gt;
public static class NiceTwitterClient 
{ 
    public static Searcher Search(string from) 
    { 
        return new Searcher(from); 
    }
}     &lt;/pre&gt;
&lt;p&gt;
	returning an instance of a &lt;span style="font-weight:bold;font-family:courier new,courier,monospace"&gt;Searcher &lt;/span&gt;type, and then we have our query:&lt;/p&gt;
&lt;pre class="brush: csharp"&gt;
var twits =  from t in NiceTwitterClient.Search(&amp;quot;@wasp_twit&amp;quot;)
             where t.Contains(&amp;quot;#csharp&amp;quot;)
             where t.Contains(&amp;quot;cats&amp;quot;)
             orderby t.Date descending
             select t;&lt;/pre&gt;
&lt;p&gt;
	When we write:&lt;/p&gt;
&lt;pre class="brush: csharp"&gt;
var twits =  from t in NiceTwitterClient.Search(&amp;quot;@wasp_twit&amp;quot;) ...&lt;/pre&gt;
&lt;p&gt;
	we retrieve an instance of &lt;span style="font-weight:bold;font-family:courier new,courier,monospace;"&gt;Searcher &lt;/span&gt;through our call to &lt;span style="font-weight:bold;font-family:courier new,courier,monospace;"&gt;Search &lt;/span&gt;and we &amp;quot;put it into&amp;quot; Linq. With the first part of the expression &lt;span style="font-weight:bold;font-family:courier new,courier,monospace;"&gt;from t&lt;/span&gt; we also define a range variable &lt;span style="font-weight:bold;font-family:courier new,courier,monospace;"&gt;t&lt;/span&gt; which Linq will use when building the subsequent calls. Because we must be compliant to the query syntax, Linq will try to map its operators to corresponding &lt;span style="font-weight:bold;font-family:courier new,courier,monospace;"&gt;Searcher &lt;/span&gt;methods (or extension methods), therefore they must have appropriate definitions. In our sample query, we go on with:&lt;/p&gt;
&lt;pre class="brush: csharp"&gt;
... where t.Contains(&amp;quot;#csharp&amp;quot;) ...&lt;/pre&gt;
&lt;p&gt;
	which Linq translates into this:&lt;/p&gt;
&lt;pre class="brush: csharp"&gt;
... NiceTwitterClient.Search(&amp;quot;@wasp_twit&amp;quot;)
                     .Where(t =&amp;gt; t.Contains(&amp;quot;#csharp&amp;quot;)) ...&lt;/pre&gt;
&lt;p&gt;
	Here you can see how the range variable &lt;span style="font-weight:bold;font-family:courier new,courier,monospace;"&gt;t&lt;/span&gt; is used to build a lambda expression. So, when we compile our code, the compiler will look for an available method named &lt;span style="font-weight:bold;font-family:courier new,courier,monospace;"&gt;Where &lt;/span&gt;on type &lt;span style="font-weight:bold;font-family:courier new,courier,monospace;"&gt;Searcher&lt;/span&gt;. C# syntax allows us to use lambda expressions to represent both delegates of certain types and code expressions built on the same types, so thanks to C# type inference the code above would match both the following definitions (I wrapped in square brackets the code you would add in case of extension methods):&lt;/p&gt;
&lt;pre class="brush: csharp"&gt;
public [static] Searcher Where([this Searcher source, ] 
    Func&amp;lt;SearcherClause, bool&amp;gt; filterClause) 
    { ... }

public [static] Searcher Where([this Searcher source, ] 
    Expression&amp;lt;Func&amp;lt;SearcherClause, bool&amp;gt;&amp;gt; filterClause) 
    { ... }&lt;/pre&gt;
&lt;p&gt;
	Our &lt;span style="font-weight:bold;font-family:courier new,courier,monospace;"&gt;Searcher &lt;/span&gt;happens to be implementing the second version of the &lt;span style="font-weight:bold;font-family:courier new,courier,monospace;"&gt;Where &lt;/span&gt;method, so the compiler will happily match that one and we will get called there. Our method will return a (possibly new) instance of &lt;span style="font-weight:bold;font-family:courier new,courier,monospace;"&gt;Searcher&lt;/span&gt;, and we will be ready for a new pass, looking again for the right match. In our sample query we go on with another &lt;span style="font-weight:bold;font-family:courier new,courier,monospace;"&gt;where &lt;/span&gt;clause:&lt;/p&gt;
&lt;pre class="brush: csharp"&gt;
... where t.Contains(&amp;quot;cats&amp;quot;) ...&lt;/pre&gt;
&lt;p&gt;
	which will be resolved as before. You probably already noticed that I specified 2 consecutive &lt;span style="font-weight:bold;font-family:courier new,courier,monospace;"&gt;where &lt;/span&gt;clauses, instead of doing it just once and joining the 2 predicates in a logical &lt;em&gt;and&lt;/em&gt;, and you might be wondering why. Well, simply because I&amp;#39;m lazy :) Let&amp;#39;s see how our &lt;span style="font-weight:bold;font-family:courier new,courier,monospace;"&gt;Where &lt;/span&gt;method is implemented and everything will be clearer:&lt;/p&gt;
&lt;pre class="brush: csharp"&gt;
public Searcher Where(Expression&amp;lt;Func&amp;lt;SearcherClause, bool&amp;gt;&amp;gt; filterClause)
{
    var mce = filterClause.Body 
              as MethodCallExpression;
    if (mce != null)
    {
        var a = mce.Arguments[0];
        if (a is ConstantExpression)
            return new Searcher(((ConstantExpression)a).Value.ToString(), this);
        if (a is MemberExpression)
        {
            var me = a as MemberExpression;
            if (me.Expression is ConstantExpression)
            {
                var value = ((ConstantExpression)me.Expression).Value;
                if (value is string)
                    return new Searcher(value.ToString(), this);
                var type = value.GetType();
                var fi = type.GetFields()[0];
                return new Searcher(fi.GetValue(value).ToString(), this);
            }
        }
    }
    throw new NotSupportedException(
        &amp;quot;When doing Where I understand calls to Contains method of SearcherClause.&amp;quot;);
}&lt;/pre&gt;
&lt;p&gt;
	The implementation deals with &lt;em&gt;expression trees&lt;/em&gt;, and you already know that those can be arbitrarily complex, and they easily get very hard to analyze. I built a naive implementation which just handles a couple of simple cases, and operation like logical &lt;em&gt;and&lt;/em&gt;/&lt;em&gt;or &lt;/em&gt;are not managed at all, so I just added an implicit semantic to the &lt;span style="font-weight:bold;font-family:courier new,courier,monospace;"&gt;Where &lt;/span&gt;methods which states that composing &lt;span style="font-weight:bold;font-family:courier new,courier,monospace;"&gt;Where &lt;/span&gt;call has the same effect as building a logical &lt;em&gt;and &lt;/em&gt;on the involved expressions.&lt;/p&gt;
&lt;p&gt;
	There are a few more interesting things to say here. The first one is about the return value of the &lt;span style="font-weight:bold;font-family:courier new,courier,monospace;"&gt;Where &lt;/span&gt;method, which is an instance of the &lt;span style="font-weight:bold;font-family:courier new,courier,monospace;"&gt;Searcher &lt;/span&gt;type which receives a reference to the current &lt;span style="font-weight:bold;font-family:courier new,courier,monospace;"&gt;Searcher &lt;/span&gt;(the &lt;span style="font-weight:bold;font-family:courier new,courier,monospace;"&gt;this&lt;/span&gt; parameter), holding it along with the specified filter values extracted from the expression. This way we build a &amp;quot;chain&amp;quot; of &lt;span style="font-weight:bold;font-family:courier new,courier,monospace;"&gt;Searcher &lt;/span&gt;instances. This is just one of the possible ways to deal with the problem, probably the easier and therefore the most suited to an exercise like this. That chain will be used at the end of the computation to determine the true call to the &amp;quot;real&amp;quot; Twitter client.&lt;/p&gt;
&lt;p&gt;
	The second interesting thing is a peculiar view we might adopt to analyze the code. Our &lt;span style="font-weight:bold;font-family:courier new,courier,monospace;"&gt;Where &lt;/span&gt;method might be seen as a way to navigate through types, and in this case we may say that &lt;span style="font-weight:bold;font-family:courier new,courier,monospace;"&gt;Where &lt;/span&gt;&amp;quot;goes from &lt;span style="font-weight:bold;font-family:courier new,courier,monospace;"&gt;Searcher &lt;/span&gt;to &lt;span style="font-weight:bold;font-family:courier new,courier,monospace;"&gt;Searcher&lt;/span&gt;&amp;quot;, so it actually keeps us in the same context. If we move forward to the next line in our query:&lt;/p&gt;
&lt;pre class="brush: csharp"&gt;
... orderby t.Date descending ...&lt;/pre&gt;
&lt;p&gt;
	we are asking Linq to perform an &lt;span style="font-weight:bold;font-family:courier new,courier,monospace;"&gt;orderby descending&lt;/span&gt;, which it will translate into this:&lt;/p&gt;
&lt;pre class="brush: csharp"&gt;
... searcher_from_previous_where.OrderByDescending(t =&amp;gt; t.Date) ...&lt;/pre&gt;
&lt;p&gt;
	This will match to this implementation:&lt;/p&gt;
&lt;pre class="brush: csharp"&gt;
public Sorter OrderByDescending(Expression&amp;lt;Func&amp;lt;SorterClause, object&amp;gt;&amp;gt; sortClause)
{
    return order(sortClause, false);
}

private Sorter order(Expression&amp;lt;Func&amp;lt;SorterClause, object&amp;gt;&amp;gt; sortClause, 
    bool ascending)
{
    var ue = sortClause.Body as UnaryExpression;
    if (ue != null &amp;amp;&amp;amp; 
        ue.Operand is MemberExpression)
        return new Sorter(((MemberExpression)ue.Operand).Member.Name, ascending, this);
    throw new NotSupportedException(
        &amp;quot;When doing OrderBy I understand UnaryExpression only, accessing members of SorterClause.&amp;quot;);
}&lt;/pre&gt;
&lt;p&gt;
	Here we can see that we are again doing some expression tree analysis (even more naive that before), and that our &lt;span style="font-weight:bold;font-family:courier new,courier,monospace;"&gt;OrderByDescending &lt;/span&gt;&amp;quot;goes from &lt;span style="font-weight:bold;font-family:courier new,courier,monospace;"&gt;Searcher &lt;/span&gt;to &lt;span style="font-weight:bold;font-family:courier new,courier,monospace;"&gt;Sorter&lt;/span&gt;&amp;quot;, changing our context. Our &lt;span style="font-weight:bold;font-family:courier new,courier,monospace;"&gt;Sorter &lt;/span&gt;type is quite similar to &lt;span style="font-weight:bold;font-family:courier new,courier,monospace;"&gt;Searcher&lt;/span&gt;, but it actually defines a new context, letting us know that we moved from the &amp;quot;filter&amp;quot; phase to the &amp;quot;sort&amp;quot; phase. &lt;span style="font-weight:bold;font-family:courier new,courier,monospace;"&gt;Sorter &lt;/span&gt;does not offer &lt;span style="font-weight:bold;font-family:courier new,courier,monospace;"&gt;Where &lt;/span&gt;methods anymore, but only &lt;span style="font-weight:bold;font-family:courier new,courier,monospace;"&gt;Select &lt;/span&gt;methods, which will be analyzed later, and this way it guides us to the right path while building our query, letting us take advantage of features like Visual Studio Intellisense which will suggest us only appropriate methods, and leveraging the compiler support which will emit errors in case we try to use unsupported Linq query operators.&lt;/p&gt;
&lt;p&gt;
	When we are done with sorting, our Linq query is dealing with a &lt;span style="font-weight:bold;font-family:courier new,courier,monospace;"&gt;Sorter &lt;/span&gt;instance, and our implementation offers us just one &amp;quot;way out&amp;quot;: using the &lt;span style="font-weight:bold;font-family:courier new,courier,monospace;"&gt;select &lt;/span&gt;operator. A Linq query must end with a call to a &lt;span style="font-weight:bold;font-family:courier new,courier,monospace;"&gt;select &lt;/span&gt;operator (or equivalent, like for grouping), so we should just add appropriate implementations of &lt;span style="font-weight:bold;font-family:courier new,courier,monospace;"&gt;Select &lt;/span&gt;returning an output which is meaningful for us, and in this case an &lt;span style="font-weight:bold;font-family:courier new,courier,monospace;"&gt;IEnumerable&amp;lt;T&amp;gt;&lt;/span&gt; will be just fine. The actual &lt;span style="font-weight:bold;font-family:courier new,courier,monospace;"&gt;T&lt;/span&gt; will be left generic in an implementation, whereas in another available overload it will be closed to a simple &lt;span style="font-weight:bold;font-family:courier new,courier,monospace;"&gt;Twit &lt;/span&gt;type we expose to make things simpler. Under the hood, the actual implementation of &lt;span style="font-weight:bold;font-family:courier new,courier,monospace;"&gt;IEnumerable&amp;lt;T&amp;gt;&lt;/span&gt; will just be an internal type aware of all the parameters we&amp;#39;ve been collecting along the chained calls, and on the act of &amp;quot;enumerating&amp;quot; it these parameters will be used all together to call the original ugly client, to receive its response and eventually to convert it in an enumeration of &lt;span style="font-weight:bold;font-family:courier new,courier,monospace;"&gt;Twit &lt;/span&gt;instances (possibly transformed via the correspondant &lt;span style="font-weight:bold;font-family:courier new,courier,monospace;"&gt;Select &lt;/span&gt;overload).&lt;/p&gt;
&lt;p&gt;
	I guess this naive exercise should demonstrate how Linq could be extended, in fact we shaped our types in order to have them nicely integrated with Linq query syntax. But there are many more different things we can do in this context to reinforce our initial concept of Linq as a &amp;quot;world&amp;quot; where we can put our things and have them play nicely. We&amp;#39;ll see some more of them in the next episodes :) &amp;nbsp;&lt;/p&gt;
</description><pubDate>Tue, 17 Jan 2012 22:13:56 GMT</pubDate><guid isPermaLink="true">http://www.robychechi.it:80/roby/extending-the-world-step-2</guid></item><item><title>Extending the world, step 1</title><link>http://www.robychechi.it:80/roby/extending-the-world-step-1</link><description>&lt;p&gt;
	After the &lt;a href="http://www.robychechi.it/roby/tech-blog/extending-the-world" target="_self" title="Introduction"&gt;general introduction&lt;/a&gt; to this short series of post, I would like to set up a sort of roadmap, defining the goals that I have while writing this stuff. But first, a sort of disclaimer: I&amp;#39;m not a big expert of these things at all, and I&amp;#39;m quite new to this kind of approach, but that&amp;#39;s exactly the reason why I want to write about it, to illustrate things from the point of view of someone who&amp;#39;s really learning to use this new mindset and the related techniques, because I know there are a lot of guys like me out there :) The code I will show will be written by myself in a sort of &amp;quot;learn by trial&amp;quot; process, but it will be strongly inspired by several sources, which I will try to mention as most precisely as possible. If someone reading these posts will find errors or omissions his comments will be welcomed.&lt;/p&gt;
&lt;p&gt;
	The points I would like to demonstrate are:&lt;/p&gt;
&lt;ol&gt;
	&lt;li&gt;
		how you can extend Linq to understand new types&lt;/li&gt;
	&lt;li&gt;
		how you can extend your types to make them live &amp;quot;better&amp;quot; inside Linq&lt;/li&gt;
	&lt;li&gt;
		how you can apply both strategies to write more functional code&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;
	The first 2 point will be mostly treated together because they are deeply related, I will try to make clear which side of the medal I will be looking at. And, by the way, I will not write at all about the process of writing a Query Provider, there is a lot of material about it and at the same time it&amp;#39;s a hard problem which indeed I had to solve already, I would never be able to talk about it in a useful form in just a few posts.&lt;/p&gt;
&lt;p&gt;
	Let&amp;#39;s start. First important statement: Linq is not for &lt;span style="font-weight:bold;font-family: Courier New;"&gt;IEnumerable&lt;/span&gt; and &lt;span style="font-weight:bold;font-family: Courier New;"&gt;IQueryable&lt;/span&gt; only. Linq is there for any type you want, and its query syntax is just &amp;quot;syntactic sugar&amp;quot; around the composition of chained calls over available methods, which might be extension methods too. As long as Linq is able to find (extension) methods with appropriate signatures for the types of the objects you are supplying as &amp;quot;sources&amp;quot;, it will be able to understand and execute the query you are writing. You already know that the query syntax understands a limited sets of methods, but the approach is still valid even on methods that are not among the ones Linq handles, as long as those methods are written with &amp;quot;composition&amp;quot; in mind. What that&amp;#39;s mean? Well, to me it&amp;#39;s simply that they should be &amp;quot;functions&amp;quot;: they receive inputs and always produce 1 output (not out or ref parameters here). If the output is of a type Linq is able to understand, you will be able to keep on chaining things as you like, writing &amp;quot;computations&amp;quot;, as they are called. Your code starts moving from an imperative style to a declarative one, and the advantage here is that the concern is not on the &amp;quot;how&amp;quot; of things, but on &amp;quot;what&amp;quot; you want from a computation. All the details get hidden inside the functions, and you just declare how you want to compose them, supplying &amp;quot;things&amp;quot; to customize their behavior. This classical imperative code:&lt;/p&gt;
&lt;pre class="brush: csharp"&gt;
foreach(var i in getNumbers)
    Console.WriteLine(i);
&lt;/pre&gt;
&lt;p&gt;
	could be rewritten like this:&lt;/p&gt;
&lt;pre class="brush: csharp"&gt;
getNumbers.ForEach(Console.WriteLine);
&lt;/pre&gt;
&lt;p&gt;
	where &lt;span style="font-weight:bold;font-family: Courier New;"&gt;ForEach&lt;/span&gt; is an extension method for &lt;span style="font-weight:bold;font-family: Courier New;"&gt;IEnumerable&amp;lt;T&amp;gt;&lt;/span&gt;. You might be thinking: there&amp;#39;s no such method on &lt;span style="font-weight:bold;font-family: Courier New;"&gt;IEnumerable&amp;lt;T&amp;gt;&lt;/span&gt;, but only on &lt;span style="font-weight:bold;font-family: Courier New;"&gt;List&amp;lt;T&amp;gt;&lt;/span&gt;. Right, but that&amp;#39;s where the magic begin: you can write it easily in a static class, and then add the right &lt;span style="font-weight:bold;font-family: Courier New;"&gt;using&lt;/span&gt; directive to have it available:&lt;/p&gt;
&lt;pre class="brush: csharp"&gt;
public static IEnumerable&amp;lt;T&amp;gt; ForEach&amp;lt;T&amp;gt;(
    this IEnumerable&amp;lt;T&amp;gt; source, 
    Action&amp;lt;T&amp;gt; action) 
    {
        foreach (T o in source) 
        { 
            action(o); 
            yield return o; 
        }
    } 
&lt;/pre&gt;
&lt;p&gt;
	What you are doing is defining a function in a composable way, extracting a common task (enumerating elements to do something on each one of them) and make it available for future uses. This is a quite stupid case, and I don&amp;#39;t mean you should really use this kind of &lt;span style="font-weight:bold;font-family: Courier New;"&gt;ForEach&lt;/span&gt;, in future I will try to show you more complex scenarios where you will hopefully get to appreciate the approach better. Such a function allows us to seamlessly integrate &amp;quot;lateral&amp;quot; actions in our computations:&lt;/p&gt;
&lt;pre class="brush: csharp"&gt;
var q = getNumbers()
        .ForEach(Console.WriteLine)
        .Where(i =&amp;gt; i%2 == 0)
        .OrderByDescending(i =&amp;gt; i)
        .Select(i =&amp;gt; 3*i);
&lt;/pre&gt;
&lt;p&gt;
	I guess you can already see some advantage of this approach: such a query would be much more &amp;quot;noisy&amp;quot; to write in the old plain imperative style, and our &amp;quot;insertion&amp;quot; of a cross cutting concern, like outputting an intermediate result to the console, has been easy and clean thanks to our extension method. I have more good news about it: we don&amp;#39;t have to start writing dozens of extension methods for every little operation like this one, because out there we can find several open source libraries full of useful little functions we can use in our computations. I can recommend &lt;a href="http://code.google.com/p/morelinq/" target="_blank" title="Morelinq"&gt;MoreLinq&lt;/a&gt;, but it&amp;#39;s not the only one for sure, and sometimes it&amp;#39;s just more fun to try to write your own extension methods.&lt;/p&gt;
&lt;p&gt;
	So far I&amp;#39;ve been cheating, you are right, I said I would have talked about types which are not &lt;span style="font-weight:bold;font-family: Courier New;"&gt;IEnumerable&amp;lt;T&amp;gt;&lt;/span&gt;. I just wanted to start easy, now let&amp;#39;s do another baby step towards our goal. Imagine you have this Twitter client library you found somewhere, which works just fine but exposes an ugly API, and when you have to use it your code starts look just bad. This library is as stupid to use as in the next example:&lt;/p&gt;
&lt;pre class="brush: csharp"&gt;
var client = new UglyTwitterClient();
var twits = client.GetTwitsFromSomeone(
    &amp;quot;@wasp_twit&amp;quot;, 
    &amp;quot;date desc&amp;quot;, 
    &amp;quot;#csharp&amp;quot;, &amp;quot;cats&amp;quot;);
&lt;/pre&gt;
&lt;p&gt;
	Well, maybe it&amp;#39;s not so ugly, I don&amp;#39;t know, but let&amp;#39;s say it is. For sure there are aspects, like the properties of a twit, which could be more strongly checked than just putting them in strings. And we are querying a system without using Linq, no way! We would prefer to write something like this:&lt;/p&gt;
&lt;pre class="brush: csharp"&gt;
var twits = from t in NiceTwitterClient
                      .Search(&amp;quot;@wasp_twit&amp;quot;)
            where t.Contains(&amp;quot;#csharp&amp;quot;)
            where t.Contains(&amp;quot;cats&amp;quot;)
            orderby t.Date descending
            select t;
&lt;/pre&gt;
&lt;p&gt;
	Ok, it&amp;#39;s easy, you have this method &lt;span style="font-weight:bold;font-family: Courier New;"&gt;Search&lt;/span&gt; which returns an &lt;span style="font-weight:bold;font-family: Courier New;"&gt;IEnumerable&amp;lt;string&amp;gt;&lt;/span&gt; so I can call &lt;span style="font-weight:bold;font-family: Courier New;"&gt;Contains()&lt;/span&gt;, and then... wait, we have a &lt;span style="font-weight:bold;font-family: Courier New;"&gt;Date&lt;/span&gt; property on the range variable, so it must be some type, maybe a &lt;span style="font-weight:bold;font-family: Courier New;"&gt;Twit&lt;/span&gt; type we can enumerate in order... enumerate where? On the client? No, I cannot simply download all the twits of this guy locally to filter them! Gosh, I have to implement &lt;span style="font-weight:bold;font-family: Courier New;"&gt;IQueryable&lt;/span&gt;, parse the expression tree, manage all the corner cases, do the remote call, unpack the data...&lt;/p&gt;
&lt;p&gt;
	As I said, here we don&amp;#39;t do &lt;span style="font-weight:bold;font-family: Courier New;"&gt;IQueryable&lt;/span&gt;. Here we extend Linq with our types, and that&amp;#39;s how this new Linq-enable client can be written. We need our &lt;span style="font-weight:bold;font-family: Courier New;"&gt;NiceTwitterClient&lt;/span&gt; and its static method &lt;span style="font-weight:bold;font-family: Courier New;"&gt;Search&lt;/span&gt;:&lt;/p&gt;
&lt;pre class="brush: csharp"&gt;
public static class NiceTwitterClient
{
    public static Searcher Search(string from)
    {
        return new Searcher(from);
    }	
    ...
}
&lt;/pre&gt;
&lt;p&gt;
	Search creates an instance of this &lt;span style="font-weight:bold;font-family: Courier New;"&gt;Searcher&lt;/span&gt; type, which will allow us to implement a &amp;quot;fluent interface&amp;quot; which will also be Linq-aware. To do so, our &lt;span style="font-weight:bold;font-family: Courier New;"&gt;Searcher&lt;/span&gt; will expose the Linq methods we decide to expose: &lt;span style="font-weight:bold;font-family: Courier New;"&gt;Where&lt;/span&gt;, &lt;span style="font-weight:bold;font-family: Courier New;"&gt;OrderBy&lt;/span&gt;, &lt;span style="font-weight:bold;font-family: Courier New;"&gt;OrderByDescending&lt;/span&gt;:&lt;/p&gt;
&lt;pre class="brush: csharp"&gt;
public Searcher Where(
    Expression&amp;lt;Func&amp;lt;SearcherClause, bool&amp;gt;&amp;gt; fc) 
{ ... } 
public Sorter OrderBy(
    Expression&amp;lt;Func&amp;lt;SorterClause, bool&amp;gt;&amp;gt; sc) 
{ ... } 
public Sorter OrderByDescending(
    Expression&amp;lt;Func&amp;lt;SorterClause, bool&amp;gt;&amp;gt; sc) 
{ ... } 
&lt;/pre&gt;
&lt;p&gt;
	Here we can notice another aspect of Linq extensibility, probably an expected one: extension methods are not the only way to join the Linq world, instance methods will do too. Those methods receive instances of &lt;span style="font-weight:bold;font-family: Courier New;"&gt;Expression&lt;/span&gt; class, or &amp;quot;expression trees&amp;quot;, and return instances of &lt;span style="font-weight:bold;font-family: Courier New;"&gt;Searcher&lt;/span&gt; or &lt;span style="font-weight:bold;font-family: Courier New;"&gt;Sorter&lt;/span&gt; types. The latter is very similar to &lt;span style="font-weight:bold;font-family: Courier New;"&gt;Searcher&lt;/span&gt;, but it&amp;#39;s meant to store info about the sorting clause we want in our query. Those types are really defining how our fluent interface evolves: &lt;span style="font-weight:bold;font-family: Courier New;"&gt;Searcher&lt;/span&gt; exposes only these 3 methods and 2 overloads of a &lt;span style="font-weight:bold;font-family: Courier New;"&gt;Select&lt;/span&gt; method, which will be discussed in details next time; &lt;span style="font-weight:bold;font-family: Courier New;"&gt;Sorter&lt;/span&gt; exposes the &lt;span style="font-weight:bold;font-family: Courier New;"&gt;Select&lt;/span&gt; overloads only. Linq query syntax is able to map them to the &lt;span style="font-weight:bold;font-family: Courier New;"&gt;where&lt;/span&gt;, &lt;span style="font-weight:bold;font-family: Courier New;"&gt;orderby&lt;/span&gt;, &lt;span style="font-weight:bold;font-family: Courier New;"&gt;orderby descending&lt;/span&gt; and &lt;span style="font-weight:bold;font-family: Courier New;"&gt;select&lt;/span&gt; operators, and environments like Visual Studio are able to help us with Intellisense. About this last point, this approach is even better than the &lt;span style="font-weight:bold;font-family: Courier New;"&gt;IQueryable&lt;/span&gt; one, because extending through this well known interface forces us to deal with ALL the Linq operators, which will be shown as available by the Intellisense and should be handled as invalid, and that&amp;#39;s possible at runtime only. Our approach makes Intellisense smarter, and moves the check of query correctness at compile time. Neat :)&lt;/p&gt;
&lt;p&gt;
	Next time I will illustrate the implementation of this exercise, and please remember that it is an exercise indeed, the code will just illustrate the concepts and should not be considered as complete or &amp;quot;production ready&amp;quot; at all, but if you are new to this concepts and features I&amp;#39;m quite sure it will be stimulating.&lt;/p&gt;
</description><pubDate>Tue, 17 Jan 2012 22:13:42 GMT</pubDate><guid isPermaLink="true">http://www.robychechi.it:80/roby/extending-the-world-step-1</guid></item><item><title>Extending the world</title><link>http://www.robychechi.it:80/roby/extending-the-world</link><description>&lt;p&gt;
	After a few months I&amp;#39;m back to write on my blog, but to be honest I had a good excuse, since my wife and I have dealt with a move abroad (I&amp;#39;ll talk about it separately), which is not exactly something trivial. However, we are slowly returning to normal, and today I managed to get a little time to write this post.&lt;/p&gt;
&lt;p&gt;
	From late August I&amp;#39;ve been working on an interesting project for a &lt;a href="http://www.cargill.com" target="_blank" title="Cargill"&gt;large company&lt;/a&gt;, side by side with &lt;a href="http://www.raboof.com" target="_blank" title="Atif"&gt;great&lt;/a&gt; &lt;a href="http://www.nut-cracker.com.ar/" target="_blank" title="Gustavo"&gt;guys&lt;/a&gt; who every day give me new inputs. One of the things that we most frequently discuss is the functional approach to programming. Nothing new, but unfortunately in the &amp;quot;mainstream&amp;quot; OO world functional programming is often seen as something old, just good for &lt;a href="http://www.youtube.com/watch?v=zmYqShvVDh4" target="_blank" title="FP Lectures"&gt;college professors with old PCs, CGA monitors, and weird text editors&lt;/a&gt;. Instead, it is a world that is rapidly changing, and it is more and more influencing the development of computer science, and its application to problems of everyday life. But probably this is not enough to decide to abandon the old and comfortable world of OOP for a difficult and perhaps dangerous &lt;a href="http://www.google.it/url?sa=t&amp;amp;rct=j&amp;amp;q=magical%20mystery%20tour&amp;amp;source=web&amp;amp;cd=3&amp;amp;ved=0CEwQFjAC&amp;amp;url=http%3A%2F%2Fen.wikipedia.org%2Fwiki%2FMagical_Mystery_Tour&amp;amp;ei=dmbqTqSEBKbl4QSk8-zkCA&amp;amp;usg=AFQjCNE9g0xdlFUXNzDWO80LYpYZAtLp7Q" target="_blank" title="Fab 4"&gt;magical mystery tour&lt;/a&gt;...&lt;/p&gt;
&lt;p&gt;
	Game over, then? Not really. The hours spent talking (and especially listening) about themes such as sequences, immutability, lazyness, higher order functions, monads, compositionality, and more, are slowly influencing the way I think and do programming, because most of them are applicable in OOP languages and in languages like C#. The turning point that transformed C# in a &amp;quot;functional space&amp;quot; has been the introduction of Linq. Here you have to remove all the marketing and mainstream technical comunication, which present Linq as the new ORM, a way to make queries directly from code, or in more advanced cases as something for which we can write a query provider that enable us to implement a idiomatic query model. Those are correct views but perhaps limiting, and they do not describe the essence of Linq but only some of the most popular applications. &amp;quot;My&amp;quot; idea now is more and more this one: Linq is an environment in which you can &amp;quot;extend the world&amp;quot; :)&lt;/p&gt;
&lt;p&gt;
	I&amp;#39;ll try to write more posts in the coming days about more specific aspects of this statement, now I will focus here on a quick look about one feature: extension methods. They are normally presented as a way to add methods to existing types for which you do not have the source code. In short, a sort of &amp;quot;trick&amp;quot; Microsoft has used to enrich types and interfaces (!) with useful implementations which were not introduced before. The fact that I mentioned the interfaces too should have you wondering about it: how do you add implementations to constructs which by definition do not allow them? Strange, isn&amp;#39;t it?&lt;/p&gt;
&lt;p&gt;
	So let&amp;#39;s try to reverse the point of view: Linq and its the query syntax are &amp;quot;the world&amp;quot;, or rather a &amp;quot;functional&amp;quot; world inside C#, with its required (although not enforced) rules of immutability, absence of side effects, deferred execution, compositionality; then there are the types of the BCL, including interfaces, but also the whole .NET Framework types set, and, why not, our own types, our own interfaces, as well as types and interfaces from any library around. We are envious of &lt;span style="font-weight:bold;font-family: Courier New;"&gt;IEnumerable&lt;/span&gt; and &lt;span style="font-weight:bold;font-family: Courier New;"&gt;IQueryable&lt;/span&gt;, and we&amp;#39;d like so much that our types could join them in Linq query, right? So what can we do? We should begin to write a query provider, shouldn&amp;#39;t we? Well, not necessarily, it is often more than enough to write a bunch of extension methods for our types, and here we go, suddenly they can participate in Linq queries! We did not extend our objects, we have extended Linq with them :) This way even the fact that you can &amp;quot;extend&amp;quot; interfaces with implementations makes more sense, because actually you are extending Linq to understand specific interfaces.&lt;/p&gt;
&lt;p&gt;
	Think about it, and next time I will bring some examples and some of related &lt;span style="text-decoration: line-through;"&gt;linq&lt;/span&gt; links. Just to make you curious, we&amp;#39;ll write code like this:&lt;/p&gt;
&lt;pre class="brush: csharp;"&gt;
var q = from i in 20.ToMaybe()
        from l in 22.ToMaybe()
        select i + l;

        Assert.IsTrue(q.HasValue);
        Assert.AreEqual(42, q.Value);

var r = from i in ToMaybe.Empty&amp;lt;int&amp;gt;()
        from l in 22.ToMaybe()
        select i + l;

        Assert.IsFalse(r.HasValue);&lt;/pre&gt;
&lt;p&gt;
	Published episodes:&lt;/p&gt;
&lt;ol&gt;
	&lt;li&gt;
		&lt;a href="http://www.robychechi.it/roby/tech-blog/extending-the-world-step-1"&gt;Episode 1&lt;/a&gt;&lt;/li&gt;
	&lt;li&gt;
		&lt;a href="http://www.robychechi.it/roby/tech-blog/extending-the-world-step-2"&gt;Episode 2&lt;/a&gt;&lt;/li&gt;
	&lt;li&gt;
		&lt;a href="http://www.robychechi.it/roby/tech-blog/extending-the-world-step-3"&gt;Episode 3&lt;/a&gt;&lt;/li&gt;
	&lt;li&gt;
		&lt;a href="http://www.robychechi.it/roby/tech-blog/extending-the-world-step-4"&gt;Episode 4&lt;/a&gt;&lt;/li&gt;
	&lt;li&gt;
		&lt;a href="http://www.robychechi.it/roby/tech-blog/extending-the-world-related-material"&gt;Related Material&lt;/a&gt;&lt;/li&gt;
&lt;/ol&gt;
</description><pubDate>Wed, 18 Jan 2012 21:36:37 GMT</pubDate><guid isPermaLink="true">http://www.robychechi.it:80/roby/extending-the-world</guid></item></channel></rss>