<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	xmlns:georss="http://www.georss.org/georss" xmlns:geo="http://www.w3.org/2003/01/geo/wgs84_pos#" xmlns:media="http://search.yahoo.com/mrss/"
	>

<channel>
	<title>Looking Sharp</title>
	<atom:link href="http://lookingsharp.wordpress.com/feed/" rel="self" type="application/rss+xml" />
	<link>http://lookingsharp.wordpress.com</link>
	<description></description>
	<lastBuildDate>Mon, 28 Mar 2011 19:04:00 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.com/</generator>
<cloud domain='lookingsharp.wordpress.com' port='80' path='/?rsscloud=notify' registerProcedure='' protocol='http-post' />
<image>
		<url>http://s2.wp.com/i/buttonw-com.png</url>
		<title>Looking Sharp</title>
		<link>http://lookingsharp.wordpress.com</link>
	</image>
	<atom:link rel="search" type="application/opensearchdescription+xml" href="http://lookingsharp.wordpress.com/osd.xml" title="Looking Sharp" />
	<atom:link rel='hub' href='http://lookingsharp.wordpress.com/?pushpress=hub'/>
		<item>
		<title>Picking the Right Tool for the Job</title>
		<link>http://lookingsharp.wordpress.com/2011/03/28/picking-the-right-tool-for-the-job/</link>
		<comments>http://lookingsharp.wordpress.com/2011/03/28/picking-the-right-tool-for-the-job/#comments</comments>
		<pubDate>Mon, 28 Mar 2011 19:03:47 +0000</pubDate>
		<dc:creator>Tormod Fjeldskår</dc:creator>
				<category><![CDATA[C#]]></category>
		<category><![CDATA[F#]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[bowling]]></category>
		<category><![CDATA[dojo]]></category>
		<category><![CDATA[functional]]></category>
		<category><![CDATA[imperative]]></category>
		<category><![CDATA[kata]]></category>

		<guid isPermaLink="false">http://lookingsharp.wordpress.com/?p=442</guid>
		<description><![CDATA[When your only tool is a hammer, every problem looks like a nail. - Abraham Maslow I recently organized a coding dojo where we solved the bowling kata. In short, the bowling kata is about programming a score-keeper for a game of ten-pin bowling. At any given time during the game, the score-keeper must be [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=lookingsharp.wordpress.com&amp;blog=8649446&amp;post=442&amp;subd=lookingsharp&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<blockquote><p><em>When your only tool is a hammer, every problem looks like a nail.</em><br />
- Abraham Maslow</p></blockquote>
<p>I recently organized a <a href="http://codingdojo.org/cgi-bin/wiki.pl?WhatIsCodingDojo">coding dojo</a> where we solved the <a href="http://codingdojo.org/cgi-bin/wiki.pl?KataBowling">bowling kata</a>. In short, the bowling kata is about programming a score-keeper for a game of ten-pin bowling. At any given time during the game, the score-keeper must be able to yield the current score for all players. Additionally, the program must be able to tell which player is the current player, in order to assign scores correctly.</p>
<p>I began solving the kata in my programming language of choice, C#. The solution naturally converged to an imperative state machine, incrementing scores as the game progressed. This lead to entangled code with many special cases, struggling with the tracking of arbitrary strikes and spares. </p>
<p>Then I realized that the problem is in fact two-fold. One part of the problem is to keep track of which player knocks over which pins, while the other part is the actual calculation of the scores. Given a sequence of numbers representing the amount of pins knocked over, the score can be calculated as a relatively simple function. At this point, I reached for my .NET toolbox and picked the tool best suited for writing functional code, F#.</p>
<pre class="brush: fsharp;">
module BowlingCalculator

[&lt;CompiledNameAttribute(&quot;CalculateScore&quot;)&gt;]
let calcScore pins =

    let rec calcScore pins frame =

        match pins with

        // Strike with determined bonus
        | 10 :: y :: z :: rest -&gt; 10 + y + z + calcScore (y :: z :: rest) (frame + 1)

        // Strike -without- determined bonus
        | 10 :: y :: [] -&gt; 0

        // Spare with determined bonus
        | x :: y :: z :: rest when x + y = 10 -&gt; 10 + z + calcScore (z :: rest) (frame + 1)

        // Spare -without- determined bonus
        | x :: y :: [] when x + y = 10 -&gt; 0

        // Open frame
        | x :: y :: rest -&gt; x + y + calcScore (rest) (frame + 1)

        // Special last frame
        | x :: y :: z :: [] when frame = 10 -&gt; x + y + z

        // Otherwise
        | _ -&gt; 0

    calcScore pins 1
</pre>
<p>If you are familiar with functional programming and pattern matching, the code above should be pretty obvious. I will not go into much depth explaining it, but suffice it to say that it is a recursive function traversing the list of pins knocked over, aggregating the score as it goes.</p>
<p>The rest of the program, responsible for keeping track of state, was kept in C#. After adding a reference to the F# module, calling into the calculating function is as simple as:</p>
<pre class="brush: csharp;">
public class Player
{
    private readonly List&lt;int&gt; pinsKnockedOver;

    // snip...

    public int CalculateScore()
    {
        var pins = ListModule.OfSeq(pinsKnockedOver);
        return BowlingCalculator.CalculateScore(pins);
    }
}
</pre>
<p>Both being first class .NET citizens, interoperability between C# and F# is a breeze. The only hitch at this point was that my F# function required an <a href="http://msdn.microsoft.com/en-us/library/ee370372.aspx">F# list</a> as its argument, while the <code>Player</code> class uses a regular <code><a href="http://msdn.microsoft.com/en-us/library/6sh2ey19.aspx">List&lt;T&gt;</a></code> to keep track of the pins knocked over. <code><a href="http://msdn.microsoft.com/en-us/library/ee340325.aspx">ListModule.OfSeq()</a></code> converts any <code><a href="http://msdn.microsoft.com/en-us/library/9eekhta0.aspx">IEnumerable&lt;T&gt;</a></code> into an F# list, solving that problem with ease.</p>
<p>The complete source code is available on GitHub at <a href="https://github.com/tormodfj/katas/tree/master/mixed/Bowling">https://github.com/tormodfj/katas/tree/master/mixed/Bowling</a>. </p>
<p>In my opinion, this solution takes the best from two worlds, using the imperative C# for state tracking and the functional F# for calculations. Learning the functional paradigm is like acquiring a new tool in your toolbox, enabling you to view problems from other points of view.</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/lookingsharp.wordpress.com/442/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/lookingsharp.wordpress.com/442/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/lookingsharp.wordpress.com/442/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/lookingsharp.wordpress.com/442/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/lookingsharp.wordpress.com/442/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/lookingsharp.wordpress.com/442/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/lookingsharp.wordpress.com/442/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/lookingsharp.wordpress.com/442/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/lookingsharp.wordpress.com/442/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/lookingsharp.wordpress.com/442/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/lookingsharp.wordpress.com/442/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/lookingsharp.wordpress.com/442/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/lookingsharp.wordpress.com/442/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/lookingsharp.wordpress.com/442/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=lookingsharp.wordpress.com&amp;blog=8649446&amp;post=442&amp;subd=lookingsharp&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://lookingsharp.wordpress.com/2011/03/28/picking-the-right-tool-for-the-job/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/6ec51edc3200f7edeb2a2addb07c1574?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">tormod</media:title>
		</media:content>
	</item>
		<item>
		<title>Converting an IList&lt;T&gt; to an FSharpList&lt;T&gt;</title>
		<link>http://lookingsharp.wordpress.com/2011/03/08/converting-an-ilist-to-an-fsharplist/</link>
		<comments>http://lookingsharp.wordpress.com/2011/03/08/converting-an-ilist-to-an-fsharplist/#comments</comments>
		<pubDate>Tue, 08 Mar 2011 22:09:48 +0000</pubDate>
		<dc:creator>Tormod Fjeldskår</dc:creator>
				<category><![CDATA[F#]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[list]]></category>
		<category><![CDATA[recursion]]></category>
		<category><![CDATA[interop]]></category>

		<guid isPermaLink="false">http://lookingsharp.wordpress.com/?p=422</guid>
		<description><![CDATA[When calling F# functions from other .NET languages, you may encounter situations where you need to pass parameters of type 'T list. F# lists are immutable linked lists, appearing as the type FSharpList&#60;T&#62; in other .NET languages. Hence, passing a typical IList&#60;T&#62; is not possible. Luckily, converting an IList&#60;T&#62; to an FSharpList&#60;T&#62; is easily accomplished [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=lookingsharp.wordpress.com&amp;blog=8649446&amp;post=422&amp;subd=lookingsharp&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>When calling F# functions from other .NET languages, you may encounter situations where you need to pass parameters of type <code>'T list</code>. F# lists are immutable linked lists, appearing as the type <a href="http://msdn.microsoft.com/en-us/library/ee370372.aspx"><code>FSharpList&lt;T&gt;</code></a> in other .NET languages. Hence, passing a typical <code>IList&lt;T&gt;</code> is not possible. Luckily, converting an <code>IList&lt;T&gt;</code> to an <code>FSharpList&lt;T&gt;</code> is easily accomplished by recursively calling <code>FSharpList&lt;T&gt;.Cons</code>, passing each element of the source list. I keep the following code around for those occasions:</p>
<pre class="brush: csharp;">
public static class Interop
{
	public static FSharpList&lt;T&gt; ToFSharpList&lt;T&gt;(this IList&lt;T&gt; input)
	{
		return CreateFSharpList(input, 0);
	}

	private static FSharpList&lt;T&gt; CreateFSharpList&lt;T&gt;(IList&lt;T&gt; input, int index)
	{
		if(index &gt;= input.Count)
		{
			return FSharpList&lt;T&gt;.Empty;
		}
		else
		{
			return FSharpList&lt;T&gt;.Cons(input[index], CreateFSharpList(input, index + 1));
		}
	}
}
</pre>
<p>Note how F# lists are terminated using <code>FSharpList&lt;T&gt;.Empty</code>. Using this piece of code is as simple as:</p>
<pre class="brush: csharp;">
var list = new List&lt;int&gt; { 1, 2, 3, 4 };
var fsharpList = list.ToFSharpList();
</pre>
<p><strong>Update:</strong> <a href="http://twitter.com/rickasaurus">@rickasaurus</a> made me aware of the <a href="http://msdn.microsoft.com/en-us/library/ee340325.aspx"><code>List.ofSeq&lt;'T&gt;</code></a> function in the F# core library. This function solves the same issue. And, unlike my solution, its implementation is not prone to stack overflows when the input list grows large. In C#, this function is called like this:</p>
<pre class="brush: csharp;">
var list = new List&lt;int&gt; { 1, 2, 3, 4 };
var fsharpList = ListModule.OfSeq(list);
</pre>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/lookingsharp.wordpress.com/422/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/lookingsharp.wordpress.com/422/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/lookingsharp.wordpress.com/422/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/lookingsharp.wordpress.com/422/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/lookingsharp.wordpress.com/422/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/lookingsharp.wordpress.com/422/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/lookingsharp.wordpress.com/422/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/lookingsharp.wordpress.com/422/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/lookingsharp.wordpress.com/422/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/lookingsharp.wordpress.com/422/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/lookingsharp.wordpress.com/422/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/lookingsharp.wordpress.com/422/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/lookingsharp.wordpress.com/422/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/lookingsharp.wordpress.com/422/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=lookingsharp.wordpress.com&amp;blog=8649446&amp;post=422&amp;subd=lookingsharp&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://lookingsharp.wordpress.com/2011/03/08/converting-an-ilist-to-an-fsharplist/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/6ec51edc3200f7edeb2a2addb07c1574?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">tormod</media:title>
		</media:content>
	</item>
		<item>
		<title>Simple but Useful Extension Methods</title>
		<link>http://lookingsharp.wordpress.com/2010/11/05/simple-but-useful-extension-methods/</link>
		<comments>http://lookingsharp.wordpress.com/2010/11/05/simple-but-useful-extension-methods/#comments</comments>
		<pubDate>Fri, 05 Nov 2010 16:34:30 +0000</pubDate>
		<dc:creator>Tormod Fjeldskår</dc:creator>
				<category><![CDATA[C#]]></category>
		<category><![CDATA[Programming]]></category>

		<guid isPermaLink="false">http://lookingsharp.wordpress.com/?p=408</guid>
		<description><![CDATA[In my previous post, I gave a fairly quick introduction to extension methods in C#. This post will present two examples to illustrate how readability can be improved by means of very simple extension methods. One of the most common checks you perform on a string is whether it has any value. The string type [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=lookingsharp.wordpress.com&amp;blog=8649446&amp;post=408&amp;subd=lookingsharp&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>In my <a href="http://lookingsharp.wordpress.com/2010/11/04/extension-methods-in-csharp/">previous post</a>, I gave a fairly quick introduction to extension methods in C#. This post will present two examples to illustrate how readability can be improved by means of very simple extension methods.</p>
<p>One of the most common checks you perform on a string is whether it has any value. The <code>string</code> type has a static <code>IsNullOrEmpty</code> method intended for this purpose. The reason this method is static is that it could never check for <code>null</code> if it was an instance method. Rather, it would throw a <code>NullReferenceException</code>. Consider this extension method, however.</p>
<pre class="brush: csharp;">
public static class Extensions
{
	public static bool IsNullOrEmpty(this string value)
	{
		return string.IsNullOrEmpty(value);
	}
}
</pre>
<p>Being static, this method can be invoked even when <code>value</code> is <code>null</code>. But, due to the fact that it is defined as an extension method, you can invoke it using instance method syntax, improving readability.</p>
<pre class="brush: csharp;">
string foo = null;
if(foo.IsNullOrEmpty())
{
	// Do something
}
</pre>
<p>Another common scenario is parsing string values into corresponding enumeration values. Again, .NET provides a static method for this purpose. The <code>Enum</code> type has a static <code>Parse</code> method which takes a <code>Type</code> parameter and a <code>string</code> parameter, and returns an <code>object</code> which then has to be casted to the specified type.</p>
<pre class="brush: csharp;">
string day = &quot;Monday&quot;;
DayOfWeek dayOfWeek = (DayOfWeek)Enum.Parse(typeof(DayOfWeek), day);
</pre>
<p>The signal-to-noise ratio of that second line of code is rather poor. Consider the following generic extension method.</p>
<pre class="brush: csharp;">
public static class Extensions
{
	public static T ToEnum&lt;T&gt;(this string value)
	{
		return (T)Enum.Parse(typeof(T), value);
	}
}
</pre>
<p>Notice how this method does exactly the same as the concrete <code>DayOfWeek</code> example above. With this extension method in place, however, each parse operation can now be reduced to the following.</p>
<pre class="brush: csharp;">
string day = &quot;Monday&quot;;
DayOfWeek dayOfWeek = day.ToEnum&lt;DayOfWeek&gt;();
</pre>
<p>Again, the major benefit is with the readability. </p>
<p>The examples in this post are extremely simple, but they illustrate how easily you can improve readability by simply wrapping existing functionality in a reasonably named extension methods. For more handy extension methods, I recommend browsing through this StackOverflow thread:<br />
<a href="http://stackoverflow.com/questions/271398/post-your-extension-goodies-for-c-net">http://stackoverflow.com/questions/271398/post-your-extension-goodies-for-c-net</a></p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/lookingsharp.wordpress.com/408/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/lookingsharp.wordpress.com/408/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/lookingsharp.wordpress.com/408/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/lookingsharp.wordpress.com/408/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/lookingsharp.wordpress.com/408/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/lookingsharp.wordpress.com/408/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/lookingsharp.wordpress.com/408/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/lookingsharp.wordpress.com/408/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/lookingsharp.wordpress.com/408/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/lookingsharp.wordpress.com/408/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/lookingsharp.wordpress.com/408/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/lookingsharp.wordpress.com/408/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/lookingsharp.wordpress.com/408/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/lookingsharp.wordpress.com/408/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=lookingsharp.wordpress.com&amp;blog=8649446&amp;post=408&amp;subd=lookingsharp&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://lookingsharp.wordpress.com/2010/11/05/simple-but-useful-extension-methods/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/6ec51edc3200f7edeb2a2addb07c1574?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">tormod</media:title>
		</media:content>
	</item>
		<item>
		<title>Extension Methods in C#</title>
		<link>http://lookingsharp.wordpress.com/2010/11/04/extension-methods-in-csharp/</link>
		<comments>http://lookingsharp.wordpress.com/2010/11/04/extension-methods-in-csharp/#comments</comments>
		<pubDate>Thu, 04 Nov 2010 19:03:18 +0000</pubDate>
		<dc:creator>Tormod Fjeldskår</dc:creator>
				<category><![CDATA[C#]]></category>
		<category><![CDATA[Programming]]></category>

		<guid isPermaLink="false">http://lookingsharp.wordpress.com/?p=395</guid>
		<description><![CDATA[Extension methods were introduced as a C# feature in version 3. An extension method is really nothing but a plain old static method. The difference is how you can invoke that static method. Conventionally, a static method is called by explicitly telling the compiler which class contains the method. int absoluteValue = Math.Abs(-5); Here, the [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=lookingsharp.wordpress.com&amp;blog=8649446&amp;post=395&amp;subd=lookingsharp&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>Extension methods were introduced as a C# feature in version 3. An extension method is really nothing but a plain old static method. The difference is how you can invoke that static method. Conventionally, a static method is called by explicitly telling the compiler which class contains the method.</p>
<pre class="brush: csharp;">
int absoluteValue = Math.Abs(-5);
</pre>
<p>Here, the static method <code>Abs</code> is called on the <code>Math</code> class with the argument <code>-5</code>. If the <code>Abs</code> method was declared an extension method, the first parameter could have been passed using instance method invocation syntax.</p>
<pre class="brush: csharp;">
int absoluteValue = -5.Abs(); // Not valid
</pre>
<p>The most obvious place to find extension methods in .NET is in the LINQ namespaces. One such extension method is <code>Enumerable.Where</code>. Consider these two invocations of this method.</p>
<pre class="brush: csharp;">
var values = new int[]{ 1, 2, 3, 4, 5 };

var filtered1 = values.Where(i =&gt; i &lt; 3);
var filtered2 = Enumerable.Where(values, i =&gt; i &lt; 3);
</pre>
<p>The two calls to <code>Where</code> are equivalent. In fact, the C# compiler will simply transform the former syntax into the latter before compilation. This transformation does require, however, that the compiler looks for a static method called <code>Where</code> in all static classes in all included namespaces, but this operation is reasonably fast.</p>
<p>Creating your own extension methods is very easy. The only requirements are that the method is static, its class is static and the first parameter of the method specifies a <code>this</code> keyword. Consider this example</p>
<pre class="brush: csharp;">
public static class IntExtensions
{
	public static bool IsEven(this int value)
	{
		return value % 2 == 0;
	}

	public static bool IsOdd(this int value)
	{
		return !value.IsEven();
	}
}
</pre>
<p>These two extension methods will seemingly augment all <code>int</code>s with the two methods <code>IsEven</code> and <code>IsOdd</code>, making the following code compile.</p>
<pre class="brush: csharp;">
if(2.IsEven() &amp;&amp; 3.IsOdd())
{
	Console.WriteLine(&quot;All is good&quot;);
}
</pre>
<p>Extension methods can drastically improve readability, especially when performing multiple operations. Consider these two lines of code.</p>
<pre class="brush: csharp;">
Utils.DoSomethingElse(Utils.DoSomething(Utils.Transform(x, &quot;arg1&quot;), &quot;arg2&quot;));
x.Transform(&quot;arg1&quot;).DoSomething(&quot;arg2&quot;).DoSomethingElse();
</pre>
<p>There is no argument that the second line is much easier to interpret while reading than the first line. Extension methods make such a &#8220;chaining&#8221; syntax of static method calls possible.</p>
<p>Before you go bananas and convert all your static utility methods to extension methods, however, consider this warning from <a href="http://msdn.microsoft.com/en-us/library/ms364047(VS.80).aspx">MSDN</a>:</p>
<blockquote><p>Extension methods are less discoverable and more limited in functionality than instance methods. For those reasons, it is recommended that extension methods be used sparingly and only in situations where instance methods are not feasible or possible.</p></blockquote>
<p>In my next post, I will present a couple of simple but handy extension methods which can be useful in most any project.</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/lookingsharp.wordpress.com/395/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/lookingsharp.wordpress.com/395/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/lookingsharp.wordpress.com/395/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/lookingsharp.wordpress.com/395/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/lookingsharp.wordpress.com/395/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/lookingsharp.wordpress.com/395/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/lookingsharp.wordpress.com/395/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/lookingsharp.wordpress.com/395/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/lookingsharp.wordpress.com/395/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/lookingsharp.wordpress.com/395/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/lookingsharp.wordpress.com/395/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/lookingsharp.wordpress.com/395/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/lookingsharp.wordpress.com/395/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/lookingsharp.wordpress.com/395/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=lookingsharp.wordpress.com&amp;blog=8649446&amp;post=395&amp;subd=lookingsharp&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://lookingsharp.wordpress.com/2010/11/04/extension-methods-in-csharp/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/6ec51edc3200f7edeb2a2addb07c1574?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">tormod</media:title>
		</media:content>
	</item>
		<item>
		<title>Tail Recursion in C# and F#</title>
		<link>http://lookingsharp.wordpress.com/2010/03/08/tail-recursion-in-csharp-and-fsharp/</link>
		<comments>http://lookingsharp.wordpress.com/2010/03/08/tail-recursion-in-csharp-and-fsharp/#comments</comments>
		<pubDate>Mon, 08 Mar 2010 19:08:31 +0000</pubDate>
		<dc:creator>Tormod Fjeldskår</dc:creator>
				<category><![CDATA[C#]]></category>
		<category><![CDATA[F#]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[c#]]></category>
		<category><![CDATA[recursion]]></category>
		<category><![CDATA[tail recursion]]></category>

		<guid isPermaLink="false">http://lookingsharp.wordpress.com/?p=346</guid>
		<description><![CDATA[For those of you who are unfamiliar with the notion of tail recursion, let me quote Wikipedia&#8217;s definition. In computer science, tail recursion (or tail-end recursion) is a special case of recursion in which the last operation of the function, the tail call, is a recursive call Tail recursion is essential in functional languages like [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=lookingsharp.wordpress.com&amp;blog=8649446&amp;post=346&amp;subd=lookingsharp&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>For those of you who are unfamiliar with the notion of tail recursion, let me quote <a href="http://en.wikipedia.org/wiki/Tail_recursion">Wikipedia&#8217;s definition</a>.</p>
<blockquote><p><em>In computer science, tail recursion (or tail-end recursion) is a special case of recursion in which the last operation of the function, the tail call, is a recursive call</em></p></blockquote>
<p>Tail recursion is essential in functional languages like F#, where iterative solutions are often implemented using recursion. If the recursion gets too deep, a stack overflow occurs, and your program crashes brutally. The rationale behind tail recursion is that <em>if the recursive call is the last operation of the function, the stack frame of the current function invocation can be discarded before the recursive function invocation is made</em>.</p>
<p>Rather than spending too much time discussing programming theory, let me present two equivalent programs, both containing tail recursion.</p>
<p><strong>C#</strong></p>
<pre class="brush: csharp;">
class Program
{
	static int n = 1000000;

	static void Countdown()
	{
		if (0 &gt; n--) return;
		Countdown();
	}

	static void Main(string[] args)
	{
		Countdown();
		Console.WriteLine(&quot;Done&quot;);
	}
}
</pre>
<p><strong>F#</strong></p>
<pre class="brush: fsharp;">
let n = 1000000

let rec countdown n =
    match n with
    | 0 -&gt; ()
    | _ -&gt; countdown (n-1)

countdown n
printfn &quot;Done&quot;
</pre>
<p>These two programs are semantically equivalent. They both use tail recursion to count from 1&nbsp;000&nbsp;000 to zero, before writing &#8220;Done&#8221; to the console.</p>
<p>Let us first look at the F# solution. Apart from being precise and easy to comprehend, it actually works. In fact, the F# compiler is smart enough to optimize the <code>countdown</code> function into a simple <code>while</code> loop, producing MSIL equivalent to the following C# code:</p>
<pre class="brush: csharp;">
public static void countdown(int n)
{
    while (true)
    {
        switch (n)
        {
            case 0:
                return;
        }
        n--;
    }
}
</pre>
<p>But what about the tail recursive C# solution? While tail recursion optimization <a href="https://connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx?FeedbackID=166013&amp;wa=wsignin1.0">has been proposed to Microsoft</a>, the current C# compiler does nothing of the kind. Hence, the resulting MSIL contains a recursive <code>Countdown</code> method. The question is then: &#8220;Will the C# solution result in a stack overflow?&#8221; Interestingly, the answer is: &#8220;It depends.&#8221;</p>
<p>It turns out, if you compile the C# code with &#8220;Platform target: Any CPU&#8221; and run it on a 64-bit version of the Microsoft .NET runtime, the JIT compiler will actually perform tail recursion optimization from the MSIL itself, resulting in a working program. If, however, you compile with &#8220;Platform target: x86&#8243; or run the program on a 32-bit version of the Microsoft .NET runtime, a stack overflow occurs. This behavior is described in the blog post &#8220;<a href="http://blogs.msdn.com/davbr/pages/tail-call-jit-conditions.aspx">Tail call JIT conditions</a>&#8221; by David Broman. Basically, the feature sets of the 64-bit and 32-bit versions of the JIT compiler do not coincide.</p>
<p>So, unless you are 100&nbsp;% certain that your C# application will run on the 64-bit runtime, do no employ tail recursion with the intent of preventing stack overflows. Then again, if you are writing imperative C# code, tail recursion will probably not cross your mind as the best solution to any of your problems.</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/lookingsharp.wordpress.com/346/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/lookingsharp.wordpress.com/346/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/lookingsharp.wordpress.com/346/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/lookingsharp.wordpress.com/346/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/lookingsharp.wordpress.com/346/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/lookingsharp.wordpress.com/346/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/lookingsharp.wordpress.com/346/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/lookingsharp.wordpress.com/346/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/lookingsharp.wordpress.com/346/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/lookingsharp.wordpress.com/346/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/lookingsharp.wordpress.com/346/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/lookingsharp.wordpress.com/346/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/lookingsharp.wordpress.com/346/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/lookingsharp.wordpress.com/346/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=lookingsharp.wordpress.com&amp;blog=8649446&amp;post=346&amp;subd=lookingsharp&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://lookingsharp.wordpress.com/2010/03/08/tail-recursion-in-csharp-and-fsharp/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/6ec51edc3200f7edeb2a2addb07c1574?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">tormod</media:title>
		</media:content>
	</item>
	</channel>
</rss>
