<?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:creativeCommons="http://backend.userland.com/creativeCommonsRssModule">

<channel>
	<title>semikolan.net &#187; functional programming</title>
	<atom:link href="http://semikolan.net/category/functional-programming/feed/" rel="self" type="application/rss+xml" />
	<link>http://semikolan.net</link>
	<description>Abhilash Kolanthara&#039;s blognoise ..</description>
	<lastBuildDate>Fri, 29 Jul 2011 10:08:39 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.3.2</generator>
<creativeCommons:license>http://creativecommons.org/licenses/by-sa/2.5/in/</creativeCommons:license>		<item>
		<title>Functional Programming in C# &#8211; Part 0 &#8211; First Class &amp; Higher Order Functions</title>
		<link>http://semikolan.net/2011/05/08/functional-programming-0-firstclass-higher-order-function/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=functional-programming-0-firstclass-higher-order-function</link>
		<comments>http://semikolan.net/2011/05/08/functional-programming-0-firstclass-higher-order-function/#comments</comments>
		<pubDate>Sun, 08 May 2011 08:36:32 +0000</pubDate>
		<dc:creator>abkolan</dc:creator>
				<category><![CDATA[.NET]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[functional programming]]></category>
		<category><![CDATA[programming]]></category>
		<category><![CDATA[First Class functions]]></category>
		<category><![CDATA[First Class Objects]]></category>
		<category><![CDATA[Functional]]></category>
		<category><![CDATA[Functional Programming]]></category>
		<category><![CDATA[Haskell]]></category>
		<category><![CDATA[Higher Order Functions]]></category>
		<category><![CDATA[Lamda Expressions]]></category>

		<guid isPermaLink="false">http://semikolan.net/?p=4</guid>
		<description><![CDATA[Ever since the pundits predicted that the doomsday of Moore&#8217;s Law was fast approaching* (*debatable) . There&#8217;s  been an eerie feeling amongst the producer &#8211; consumer cycle of microprocessors. The question on everybody&#8217;s mind seems to be- So what is the consequence of this ? Does it mean that the microprocessor developers like Intel, AMD [...]]]></description>
			<content:encoded><![CDATA[<!-- Start Shareaholic LikeButtonSetTop Automatic --><!-- End Shareaholic LikeButtonSetTop Automatic --><div class="tweetmeme_button" style="float: right; margin-left: 10px;">
			<a href="http://api.tweetmeme.com/share?url=http%3A%2F%2Fsemikolan.net%2F2011%2F05%2F08%2Ffunctional-programming-0-firstclass-higher-order-function%2F"><br />
				<img src="http://api.tweetmeme.com/imagebutton.gif?url=http%3A%2F%2Fsemikolan.net%2F2011%2F05%2F08%2Ffunctional-programming-0-firstclass-higher-order-function%2F&amp;style=normal&amp;service=bit.ly&amp;service_api=R_d741952f332d3c9302e0e249d4025838&amp;hashtags=.NET,C%23,First+Class+functions,First+Class+Objects,Functional,Functional+Programming,Haskell,Higher+Order+Functions,Lamda+Expressions,programming&amp;b=2" height="61" width="50" /><br />
			</a>
		</div>
<p>Ever since the pundits predicted that the doomsday of <a title="Moore's Law on Wikipedia" href="http://en.wikipedia.org/wiki/Moore%27s_law">Moore&#8217;s Law</a> was fast approaching* (*debatable) . There&#8217;s  been an eerie feeling amongst the producer &#8211; consumer cycle of microprocessors. The question on everybody&#8217;s mind seems to be- So what is the consequence of this ? Does it mean that the microprocessor developers like Intel, AMD et al. would close their shop and get into other domains ? (<em>for the love of God not another browser !</em>)  Well the answer is astounding  NO.  Parallel computing, Multi core architectures were an indirect consequence of this.</p>
<p>As a co-consequence of this, something that was ignored for almost 60 years ago made it way back into  limelight and became a buzz word. Lo and behold for here cometh Functional Programming ! Ever since Parallel Programming, Multi Core architecture and <a href="http://static.googleusercontent.com/external_content/untrusted_dlcp/labs.google.com/en//papers/mapreduce-osdi04.pdf">Google&#8217;s Map Reduce</a> came into the ZONE. Functional Programming is making sinusoidal waves all over the developer circuit. Functional Programming is as old as computers themselves and they rightly deserve all the credit people have been pouring all over it.</p>
<p>This is part 0 of an n part series &#8211; of my humble attempt in exploring the functional programming concepts using C#.</p>
<p><span id="more-4"></span></p>
<p>To understand the &#8216;F&#8217; in Functional Programming, we need to step back a little and revisit the approaches we used to hitherto to solve a trivial problem say -  filtering a sequence of numbers to make it contain only odd numbers.</p>
<h2>Procedural</h2>
<p>In the grand old days of  procedural languages we would have probably written something like this.</p>
<pre class="brush: csharp; title: ; notranslate">
void Main()
{
    List numbers = new List{1,2,3,4,5};
    result = FilterOnlyOddNumbers(numbers);
}

List FilterOnlyOddNumbers(List numbers)
{
    List result = new List();
    foreach(int n in numbers)
    {
       if(i%2 !=0)
       {
           result.Add(n);
       }
     }
    return result;
}
</pre>
<p>The problem with above code is every time I need a  new filtering logic, I would end up adding a new a method. Like the code below that filters out the even numbers.</p>
<pre class="brush: csharp; highlight: [6]; title: ; notranslate">
List FilterOnlyEvenNumbers(List numbers)
{
	List result = new List();
	foreach(int n in numbers)
 	{
 		if(i%2==0)
 		{
 			result.Add(n);
 		}
 	}
 	return result;
}
</pre>
<p>And what is hard to miss from the above code is that the only change between <code>FilterOnlyOddNumbers</code> and <code>FilterOnlyEvenNumbers</code> is the line #6 !!</p>
<h2>Object Oriented</h2>
<p>Enter Object Oriented paradigm &#8211; a paradigm that promised to cure us from the above problem of code redundancy using <em>Abstraction</em>..!!</p>
<p>And here&#8217;s what an object oriented junkie would have done with the problem of filtering numbers. Abstract out the logic for filtering the numbers to an interface <code>IPredicate</code></p>
<p>(line #6 of the earlier code segments)</p>
<pre class="brush: csharp; title: ; notranslate">
interface IPredicate
{
	bool FilterCondition(int n);
}
</pre>
<p>And we would rewrite our Filtering method to use the abstraction provided by the interface <code>IPredicate</code></p>
<pre class="brush: csharp; highlight: [6]; title: ; notranslate">
List FilterNums(List numbers,IPredicate p)
{
	List result = new List();
	foreach(int n in numbers)
 	{
 		if(p.FilterCondtion(n))
 		{
 			result.Add(n);
 		}
 	}
 	return result;
}
</pre>
<p>Notice how line 6 checks for the predicate of the filter condition. To use the <code>FilterNums</code> method we would need to create classes which implement the <code>IPredicate</code> interface. And Yes. this is the <a href="http://en.wikipedia.org/wiki/Strategy_pattern">Strategy design pattern</a> !</p>
<pre class="brush: csharp; title: ; notranslate">
class OddFilter:IPredicate
{
	public bool FilterCondtion(int n)
	{
		return n%2!=0;
	}
}

class EvenFilter:IPredicate
{
	public bool FilterCondition(int n)
	{
		return n%2==0;
	}
}
</pre>
<p>And invoking the <code>FilterNums</code> using poor man&#8217;s dependency injection.</p>
<pre class="brush: csharp; title: ; notranslate">
List oddNums  = FilterNums(ints,new OddFilter());
List evenNums = FilterNums(ints,new EvenFilter());
</pre>
<p>Ah Sweet ! Before this design inflates your object-oriented design purist ego and you start grinning ear to ear. Lets look at the shortcomings of this OO design.</p>
<p>In an OO universe everything is an object. If you look carefully at our OO design above, all we need is a predicate <code>FilterCondition</code> to achieve a trivial filtering function but we&#8217;re forced to abstract it into an interface and implementing the interface in a Filter subclass. And what&#8217;s worth noticing further, is that you would require as many  filter classes implementing the interface, each containing a just a couple of lines of code.  Better fix that before the class proliferation police come knocking at your door.</p>
<p>To draw a trivial analogy &#8211; consider the class <code>OddFilter</code> as a box which contains method <code>FilterCondition</code> &#8211; the ball inside the box <code>OddFilter</code>, whenever an <code>Oddfilter</code> is passed between functions, it is passed as boxes (objects) to and fro between functions. In short the boxes are the objects and member methods are the balls in the boxes.</p>
<p><a href="http://semikolan.net/wp-content/uploads/2011/04/fp-part0-1.png"><img class="alignnone size-full wp-image-251" title="fp-part0-1" src="http://semikolan.net/wp-content/uploads/2011/04/fp-part0-1.png" alt="" width="577" height="271" /></a></p>
<p>With respect to our <code>FilterNums</code> method - <code>FilterNums</code> receives the <code>OddFilter</code> object (box) and then unpacks the box (references to the method) to find the ball (<code>FilterConditon</code> method).  Looking closely we find that all we truly need is the ball (method) but we are over engineering the design by packing the ball into the box (object).  But wait a minute I cannot just throw a ball alone (method) between function calling boundaries because *<em>my programming language</em>* is object oriented everything which goes in and comes out of the function are objects !! <em>*my programming language* </em>only knows to throw and catch boxes !!</p>
<p>Or is it ?? :)</p>
<h2>Functional Programming</h2>
<p>One of the core concepts of Functional Programming is that all your functions in your programs are <em>First Class functions</em>. Err.. Well OK that sounds cool but what on God&#8217;s green earth is a <em>First Class Function</em> ?</p>
<p>It just means that Functions in the language gets same First Class treatment like the objects &#8211; meaning you can throw and receive just the functions between a function calling boundary without wrapping them in objects.</p>
<p>With respect to our earlier analogy we can just throw around just the ball between the methods with out unnecessarily packing them into boxes!</p>
<p><a href="http://semikolan.net/wp-content/uploads/2011/04/fp-part0-2.png"><img class="alignnone size-full wp-image-263" title="fp-part0-2" src="http://semikolan.net/wp-content/uploads/2011/04/fp-part0-2.png" alt="" width="573" height="284" /></a></p>
<p>In C#, this is achieved using delegates and lambda expressions.</p>
<p>And rewriting our <code>FilterNums</code> method using <code>Predicate&lt;int&gt;</code> delegate</p>
<pre class="brush: csharp; title: ; notranslate">
List FilterNums(List ints,Predicate Filter)
{
	List result = new List();
	foreach (int n in ints)
	{
		if(Filter(n))
		{
			result.Add(n);
		}
	}
	return result;
}
</pre>
<p>And invoking the <code>FilterNums</code> method is easy and elegant. And you do not have to create additional classes for each of  additional filter logic.</p>
<pre class="brush: csharp; title: ; notranslate">
List oddTodds = FilterNums(ints,i =&gt; i %2!=0);
List evenStevens = FilterNums(ints,i=&gt; i %2==0);
</pre>
<p>The FilterNums takes a first class function (Filter) as a parameter. Such functions that take in a functions as parameters or/and whose return types are functions are called as <em>Higher Order Functions</em>.</p>
<p>Now that you know the definitions and meanings of First Class functions and Higher Order functions you can now speak to a Haskell programmer.</p>
<p>This concludes Part 0 of this series, In the next post we&#8217;ll look at currying of a function and before I forget &#8211; you can you leave your <a href="http://www.google.co.in/search?hl=en&amp;q=chef%27s%20hat&amp;um=1&amp;ie=UTF-8&amp;tbm=isch">chef&#8217;s hat</a> at home :)</p>
<div class="shr-publisher-4"></div><!-- Start Shareaholic LikeButtonSetBottom Automatic --><div style="clear: both; min-height: 1px; height: 3px; width: 100%;"></div><div class='shareaholic-like-buttonset' style='float:none;height:30px;'><a class='shareaholic-tweetbutton' data-shr_count='horizontal' data-shr_href='http%3A%2F%2Fsemikolan.net%2F2011%2F05%2F08%2Ffunctional-programming-0-firstclass-higher-order-function%2F' data-shr_title='Functional+Programming+in+C%23+-+Part+0+-+First+Class+%26+Higher+Order+Functions'></a><a class='shareaholic-fblike' data-shr_layout='button_count' data-shr_showfaces='false' data-shr_href='http%3A%2F%2Fsemikolan.net%2F2011%2F05%2F08%2Ffunctional-programming-0-firstclass-higher-order-function%2F' data-shr_title='Functional+Programming+in+C%23+-+Part+0+-+First+Class+%26+Higher+Order+Functions'></a><a class='shareaholic-googleplusone' data-shr_size='medium' data-shr_count='true' data-shr_href='http%3A%2F%2Fsemikolan.net%2F2011%2F05%2F08%2Ffunctional-programming-0-firstclass-higher-order-function%2F' data-shr_title='Functional+Programming+in+C%23+-+Part+0+-+First+Class+%26+Higher+Order+Functions'></a></div><div style="clear: both; min-height: 1px; height: 3px; width: 100%;"></div><!-- End Shareaholic LikeButtonSetBottom Automatic -->]]></content:encoded>
			<wfw:commentRss>http://semikolan.net/2011/05/08/functional-programming-0-firstclass-higher-order-function/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
	</channel>
</rss>

