<?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/"
	>

<channel>
	<title>Khelll&#039;s Blog &#187; Functional Programming</title>
	<atom:link href="http://khelll.com/blog/tag/functional-programming/feed/" rel="self" type="application/rss+xml" />
	<link>http://khelll.com/blog</link>
	<description>Cool Web Development...</description>
	<lastBuildDate>Thu, 13 Oct 2011 03:48:34 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=</generator>
		<item>
		<title>Scala is my next choice</title>
		<link>http://khelll.com/blog/scala/scala-is-my-next-choice/</link>
		<comments>http://khelll.com/blog/scala/scala-is-my-next-choice/#comments</comments>
		<pubDate>Sun, 12 Jul 2009 11:39:45 +0000</pubDate>
		<dc:creator>khelll</dc:creator>
				<category><![CDATA[Scala]]></category>
		<category><![CDATA[Functional Programming]]></category>

		<guid isPermaLink="false">http://www.khelll.com/blog/?p=435</guid>
		<description><![CDATA[<div class="addthis_toolbox addthis_default_style " addthis:url='http://khelll.com/blog/scala/scala-is-my-next-choice/' addthis:title='Scala is my next choice '  ><a class="addthis_button_facebook_like" fb:like:layout="button_count"></a><a class="addthis_button_tweet"></a><a class="addthis_counter addthis_pill_style"></a></div>I have done Pascal, C, C++, Java, PHP, Ruby, Groovy and recently Scala, which I found it to be a unique language compared to anything else I have ever worked with. My journey with this language started after the Twitter&#8217;s &#8230; <a href="http://khelll.com/blog/scala/scala-is-my-next-choice/">Continue reading <span class="meta-nav">&#8594;</span></a><div class="addthis_toolbox addthis_default_style addthis_32x32_style" addthis:url='http://khelll.com/blog/scala/scala-is-my-next-choice/' addthis:title='Scala is my next choice' ><a class="addthis_button_twitter"></a><a class="addthis_button_facebook"></a><a class="addthis_button_email"></a><a class="addthis_button_print"></a><a class="addthis_button_compact"></a></div>]]></description>
			<content:encoded><![CDATA[<div class="addthis_toolbox addthis_default_style " addthis:url='http://khelll.com/blog/scala/scala-is-my-next-choice/' addthis:title='Scala is my next choice '  ><a class="addthis_button_facebook_like" fb:like:layout="button_count"></a><a class="addthis_button_tweet"></a><a class="addthis_counter addthis_pill_style"></a></div><p>I have done Pascal, C, C++, Java, PHP, Ruby, Groovy and recently Scala, which I found it to be a unique language compared to anything else I have ever worked with. My journey with this language started after the Twitter&#8217;s Ruby vs Scala <a href="http://topsecretproject.finitestatemachine.com/2009/04/the-great-twitter-ruby-vs-scala-war-debate/">debate</a>. Now and after few months of work with this language I really want to share you two ideas that are no secrets anymore:</p>
<ul>
<li>Scala Does Rock.</li>
<li>I do believe this language should be taught in CS colleges and institutes.</li>
</ul>
<p>I&#8217;m going to justify my opinion during this article, just before doing so I have few notes I feel like I have to address:</p>
<ul>
<li>This article is not to compare languages, it&#8217;s to address why you should learn Scala.</li>
<li>Scala has 2 implementations right now, one that runs on the <a href="http://en.wikipedia.org/wiki/Java_Virtual_Machine">JVM</a>, and one that runs on the <a href="http://en.wikipedia.org/wiki/Common_Language_Runtime">CLR</a>. However the JVM one  is more mature, and I believe it&#8217;s better to stick to the <a href="http://www.infoq.com/interviews/Lift-Scala-David-Pollak">advice</a> of David Pollack(Lift framework creator) to use <code>F#</code> if you want to work with <code>.Net</code> framework. However I will stick to JVM implementation in this article.</li>
<li>I&#8217;m a Rubiest, and I still like Ruby cause it&#8217;s the best dynamic language ever, but I like Scala also because it has some features that are so powerful for other work domains.</li>
</ul>
<p>Now, let&#8217;s dive into the some reasons that&#8217;s makes Scala my next language of choice:</p>
<h2>A hyper language</h2>
<p>Scala is a hyper language that enables you to code in <a href="http://en.wikipedia.org/wiki/Imperative_programming">imperative</a> and <a href="http://en.wikipedia.org/wiki/Functional_programming">functional</a> paradigms, so you can code with the normal imperative style just like we do in C, Java, PHP and many other languages, or you can code in a functional style like we do in Lisp for example, or you can mix both, just like we do in Ruby or Groovy.</p>
<p>However, one distinct to Ruby and Groovy when talking about the functional paradigm, is that Scala almost supports all known features of functional languages, like Pattern matching, Lazy initialization, Partial Functions, Immutability, etc&#8230;  </p>
<p>That&#8217;s said, it&#8217;s important to address the fact that the power of Scala comes from it&#8217;s support for the functional paradigm, which makes the language a high-level one. A high-level language makes you focus on &#8216;what&#8217; to do rather than &#8216;how&#8217; to do.</p>
<p>Look at this Java example:</p>

<div class="wp_syntax"><div class="code"><pre class="java" style="font-family:monospace;"><span style="color: #000066; font-weight: bold;">int</span><span style="color: #009900;">&#91;</span><span style="color: #009900;">&#93;</span> x <span style="color: #339933;">=</span> <span style="color: #009900;">&#123;</span><span style="color: #cc66cc;">1</span>,<span style="color: #cc66cc;">2</span>,<span style="color: #cc66cc;">3</span>,<span style="color: #cc66cc;">4</span>,<span style="color: #cc66cc;">5</span>,<span style="color: #cc66cc;">6</span><span style="color: #009900;">&#125;</span><span style="color: #339933;">;</span>
ArrayList<span style="color: #339933;">&lt;</span>Integer<span style="color: #339933;">&gt;</span> res <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">new</span> ArrayList<span style="color: #339933;">&lt;</span>Integer<span style="color: #339933;">&gt;</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #000000; font-weight: bold;">for</span> <span style="color: #009900;">&#40;</span><span style="color: #000066; font-weight: bold;">int</span> v <span style="color: #339933;">:</span> x<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
  <span style="color: #000000; font-weight: bold;">if</span> <span style="color: #009900;">&#40;</span>v <span style="color: #339933;">%</span> <span style="color: #cc66cc;">2</span> <span style="color: #339933;">==</span> <span style="color: #cc66cc;">1</span><span style="color: #009900;">&#41;</span> res.<span style="color: #006633;">add</span><span style="color: #009900;">&#40;</span><span style="color: #000000; font-weight: bold;">new</span> <span style="color: #003399;">Integer</span><span style="color: #009900;">&#40;</span>v<span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span></pre></div></div>

<p>If you focus on the previous example, you will notice that the &#8216;what&#8217; part of what I want to do (Filtering odd values) comes on the 4th line, and the other lines are just the &#8216;how&#8217; part of it(result var initialization and a loop), thus if I want to write another filter for even numbers, It will take me another 5 lines to do the same, while in a high-level languages like Scala, you will need to express the &#8216;what&#8217; part only:</p>

<div class="wp_syntax"><div class="code"><pre class="scala" style="font-family:monospace;"><span style="color: #0000ff; font-weight: bold;">val</span> x <span style="color: #000080;">=</span> Array<span style="color: #F78811;">&#40;</span><span style="color: #F78811;">1</span>,<span style="color: #F78811;">2</span>,<span style="color: #F78811;">3</span>,<span style="color: #F78811;">4</span>,<span style="color: #F78811;">5</span>,<span style="color: #F78811;">6</span><span style="color: #F78811;">&#41;</span>
<span style="color: #0000ff; font-weight: bold;">val</span> res <span style="color: #000080;">=</span> x filter <span style="color: #F78811;">&#40;</span> <span style="color: #000080;">_</span> <span style="color: #000080;">%</span> <span style="color: #F78811;">2</span> <span style="color: #000080;">==</span> <span style="color: #F78811;">1</span> <span style="color: #F78811;">&#41;</span> <span style="color: #008000; font-style: italic;">//filtering odd numbers</span>
<span style="color: #0000ff; font-weight: bold;">val</span> res2 <span style="color: #000080;">=</span> x filter <span style="color: #F78811;">&#40;</span> <span style="color: #000080;">_</span> <span style="color: #000080;">%</span> <span style="color: #F78811;">2</span> <span style="color: #000080;">==</span> <span style="color: #F78811;">0</span> <span style="color: #F78811;">&#41;</span> <span style="color: #008000; font-style: italic;">//filtering even numbers</span></pre></div></div>

<p>Notice how the previous code snippet is more readable and more concise than the Java equivalent.</p>
<h2>Efficient</h2>
<p>Scala is an efficient language, actually due to the <a href="http://stronglytypedblog.blogspot.com/2009/07/java-vs-Scala-vs-groovy-performance.html">latest benchmarks</a> Scala is almost as fast as Java. The JVM implementation of Scala compiles down to <a href="http://en.wikipedia.org/wiki/Bytecode">bytecode</a>, but during so, the code passes through optimization phaze. An optimization example is the <a href="http://en.wikipedia.org/wiki/Tail_recursion">tail recursion optimization</a>, to help you stick to the functional paradigm without sacrificing the performance. Another example is the optimization done to convert Scala value type objects to Java primitive types. </p>
<h2> Scalable </h2>
<p>The name of Scala language comes form the word &#8216;Scalable&#8217;, meaning that this language grows with the demand of its users. <strong>So basically you can add new type and control structures</strong>. For example I want to add a simple &#8216;loop&#8217; control structure:</p>

<div class="wp_syntax"><div class="code"><pre class="scala" style="font-family:monospace;"><span style="color: #008000; font-style: italic;">// simple implementation</span>
<span style="color: #0000ff; font-weight: bold;">def</span> loop<span style="color: #F78811;">&#40;</span>range<span style="color: #000080;">:</span> Range<span style="color: #F78811;">&#41;</span><span style="color: #F78811;">&#40;</span>op<span style="color: #000080;">:</span> Int<span style="color: #000080;">=&gt;</span> Unit<span style="color: #F78811;">&#41;</span> <span style="color: #F78811;">&#123;</span>
     range foreach <span style="color: #F78811;">&#40;</span>op<span style="color: #F78811;">&#41;</span>                       
<span style="color: #F78811;">&#125;</span>
&nbsp;
loop<span style="color: #F78811;">&#40;</span><span style="color: #F78811;">1</span> to <span style="color: #F78811;">5</span><span style="color: #F78811;">&#41;</span><span style="color: #F78811;">&#123;</span>println<span style="color: #F78811;">&#125;</span> <span style="color: #008000; font-style: italic;">// 1 2 3 4 5</span>
loop<span style="color: #F78811;">&#40;</span><span style="color: #F78811;">1</span> to <span style="color: #F78811;">5</span><span style="color: #F78811;">&#41;</span><span style="color: #F78811;">&#123;</span>x <span style="color: #000080;">=&gt;</span> <span style="color: #0000ff; font-weight: bold;">if</span> <span style="color: #F78811;">&#40;</span>x <span style="color: #000080;">%</span> <span style="color: #F78811;">2</span> <span style="color: #000080;">==</span> <span style="color: #F78811;">0</span><span style="color: #F78811;">&#41;</span> println<span style="color: #F78811;">&#40;</span>x<span style="color: #F78811;">&#41;</span><span style="color: #F78811;">&#125;</span> <span style="color: #008000; font-style: italic;">// 2 4</span></pre></div></div>

<p>A more comprehensive example is the <a href="http://www.Scala-lang.org/docu/files/api/Scala/actors/Actor.html">Actor lib</a>, which is added as an extension to the language, we will talk about it later on.</p>
<p>However what makes Scala Scalable is two related things: being pure object oriented and being functional.</p>
<h3>Object Oriented</h3>
<ul>
<li>Everything in Scala is an object(except for the objects&#8217; methods), so there is no need to differentiate between primitive or reference types, this is called: <strong>Uniform Object Model</strong>. But as I mentioned earlier during the optimization process, value type objects are converted to Java primitive types, so don&#8217;t be worried about the performance.<br />
There are also singleton objects to group class methods inside them.</li>
<li>All operations are method calls, <code>+ - * ! /</code> all are methods, so there no need for operator overloading.   </li>
<li>A great fine-grained access control, where you can control access for certain methods for certain packages also.</li>
<li>Scala has <code>traits</code>, similar to <code>mixins</code> in Ruby, which are like <code>interfaces</code> in Java but have some of their methods implemented, thus you can have rich wrappers and interfaces out of the box.</li>
</ul>
<h3>Functional</h3>
<p>A functional language has many characteristics, however what we care for in our Scalability context is 2 facts:</p>
<h4>Functions are first-class values</h4>
<p>Which means that you can pass them as values and return them as values as well. This leads to concise readable code just like the filtering examples mentioned above.</p>
<h4>Pure functions</h4>
<p>Scala encourages pure functions that have no side effects, meaning: when you have the same input, you will always have the same output. This will result in safer and easier to test code.<br />
But how does Scala encourages pure functions? By <strong>immutability</strong>: Favoring fixed references(like final in java or constants in other languages) and having immutable data structures that once created can&#8217;t be modified. </p>
<p>Immutability is the safe guard to have pure functions, but it&#8217;s not the only way. You still can write safe code without immutability. That&#8217;s why Scala doesn&#8217;t force immutability but it encourages it. Eventually you will find that many data structures in Scala have 2 implementations, one is mutable and the other is immutable, immutable data structures are imported by default.</p>
<p>Some concerns regarding performance might arise when talking about immutability, and while these concerns are valid in this context, it turned out that things are somehow reversed when it comes to Scala. Immutable data structures tend to be more efficient than mutable ones. One reason for that is the existence of a robust garbage collector like the one of JVM. You can find more information about the efficiency of immutable data structures in Scala in this <a href="http://www.codecommit.com/blog/Scala/Scala-collections-for-the-easily-bored-part-1">blog post</a>.</p>
<h2>Better concurrency model</h2>
<p>When it comes to threading, Scala supports the traditional <code>shared data</code> model. However and after long experiments with this model, many people found it to be so hard to to implement and test concurrent code written using this model. You will always have to consider deadlocks and race conditions. Thus Scala suggests another concurrency model called <a href = "http://www.Scala-lang.org/node/242">Actors</a>, where an actor <strong>sends and receives asynchronous messages in it&#8217;s inbox instead of sharing data</strong>. This is called: <code>shared nothing</code> model. Once you stop thinking about shared data, you relief yourself from the headache of thinking of code synchronization and deadlocks problems. </p>
<p>Together the immutability nature of the sent messages and the serial processing of messages in the actor, leads to easier concurrency support.<br />
There are 2 articles(<a href="http://www.ibm.com/developerworks/java/library/j-Scala02049.html?S_TACT=105AGX02&#038;S_CMP=EDU">1</a>,<a href="http://www.ibm.com/developerworks/java/library/j-Scala04109.html?S_TACT=105AGX02&#038;S_CMP=EDU">2</a>) on the IBM developerWorks website that cover Scala concurrency deeply. Please refer back to them to have a better idea about this topic.</p>
<p>Before I move to the next point I need to mention the fact that some people consider the use of <code>Actors</code> as an evolutionary progress in programming languages. As Java came and relieved programmers from the headache of pointers and memory management, Scala came to relief programmers from thinking all the time of code synchronization and the problems raised by shared data model.</p>
<h2>Statically typed</h2>
<p>When i wanted to cover this point, I found myself trying to weigh both the pros and cons of a statically typed language. Actually there is an endless debate regarding this topic but I tried to sum things up to two points that I found most people talking about:</p>
<h3>Code written in statically typed languages is more robust</h3>
<p>It&#8217;s true that with the existence of TDD most of the talk about dynamically typed systems and robust code starts to lose its value, but one fact still exists: in dynamically typed languages you write more tests to check types, while in statically typed ones, you leave things out for the compiler. Also some people argue that with a statically typed language you have a better self documenting code.</p>
<h3>Code written in statically typed languages is so strict and verbose</h3>
<p>Fans(just like me) of dynamically typed languages argue that they can produce more dynamic code structures through duck typing. Also they complain about the verbosity introduced with statically typed languages.
 </ol>
<p>You can read more about static versus dynamic typing <a href="http://www.pathf.com/blogs/2009/04/static-typing-and-the-paranoid-style-of-programming/">here</a>. </p>
<p>Scala as a statically typed language will gain the first point, but how about the second one?<br />
Scala has a<strong> flexible</strong> type system, and may be the best of it&#8217;s type. So in many cases this system will be able to infer the type in case you didn&#8217;t specify it.<br />
For example you can do this:</p>

<div class="wp_syntax"><div class="code"><pre class="scala" style="font-family:monospace;"><span style="color: #0000ff; font-weight: bold;">val</span> list<span style="color: #000080;">:</span> List<span style="color: #F78811;">&#91;</span>String<span style="color: #F78811;">&#93;</span> <span style="color: #000080;">=</span> List<span style="color: #F78811;">&#40;</span><span style="color: #6666FF;">&quot;one&quot;</span>, <span style="color: #6666FF;">&quot;two&quot;</span>, <span style="color: #6666FF;">&quot;three&quot;</span><span style="color: #F78811;">&#41;</span>
<span style="color: #008000; font-style: italic;">//list: List[String] = List(one, two, three)</span>
&nbsp;
<span style="color: #0000ff; font-weight: bold;">val</span> s<span style="color: #000080;">:</span> String <span style="color: #000080;">=</span> <span style="color: #6666FF;">&quot;Hello World!&quot;</span>
<span style="color: #008000; font-style: italic;">//s: java.lang.String = hello world!</span></pre></div></div>

<p>But you can do this also:</p>

<div class="wp_syntax"><div class="code"><pre class="scala" style="font-family:monospace;"><span style="color: #0000ff; font-weight: bold;">val</span> list <span style="color: #000080;">=</span> List<span style="color: #F78811;">&#40;</span><span style="color: #6666FF;">&quot;one&quot;</span>, <span style="color: #6666FF;">&quot;two&quot;</span>, <span style="color: #6666FF;">&quot;three&quot;</span><span style="color: #F78811;">&#41;</span>
<span style="color: #008000; font-style: italic;">//list: List[String] = List(one, two, three)</span>
&nbsp;
<span style="color: #0000ff; font-weight: bold;">val</span> s <span style="color: #000080;">=</span> <span style="color: #6666FF;">&quot;Hello World!&quot;</span>
<span style="color: #008000; font-style: italic;">//s: java.lang.String = hello world!</span></pre></div></div>

<p>Well, that&#8217;s cool as it solves the verbosity problem somehow. But what about things like duck typing?<br />
Again: Scala&#8217;s type system has some flexibility that enables you to do things like:</p>

<div class="wp_syntax"><div class="code"><pre class="scala" style="font-family:monospace;"><span style="color: #0000ff; font-weight: bold;">def</span> eat<span style="color: #F78811;">&#91;</span>T <span style="color: #000080;">&lt;:</span> Animal<span style="color: #F78811;">&#93;</span><span style="color: #F78811;">&#40;</span>a<span style="color: #000080;">:</span> T<span style="color: #F78811;">&#41;</span> <span style="color: #008000; font-style: italic;">// whatever</span></pre></div></div>

<p>Where we define the Type <code>T</code> to be a sub type of <code>Animal</code>. It can be more flexible even:</p>

<div class="wp_syntax"><div class="code"><pre class="scala" style="font-family:monospace;"><span style="color: #0000ff; font-weight: bold;">def</span> eat<span style="color: #F78811;">&#91;</span>T <span style="color: #000080;">&lt;:</span> <span style="color: #F78811;">&#123;</span><span style="color: #0000ff; font-weight: bold;">def</span> eat<span style="color: #F78811;">&#40;</span><span style="color: #F78811;">&#41;</span><span style="color: #000080;">:</span> Unit<span style="color: #F78811;">&#125;</span><span style="color: #F78811;">&#93;</span><span style="color: #F78811;">&#40;</span>a<span style="color: #000080;">:</span> T<span style="color: #F78811;">&#41;</span> <span style="color: #008000; font-style: italic;">// whatever</span></pre></div></div>

<p>Where we define the type <code>T</code> to be a type that has the method <code>eat.</code><br />
Actually Scala&#8217;s type system is so rich, you can find more about that <a href="http://www.artima.com/Scalazine/articles/Scalas_type_system.html">here</a>.</p>
<h2>Pattern matching</h2>
<p>I have to admit that I hesitated a lot to write about this feature, actually I didn&#8217;t want to cover functional features of Scala, but after I read <a href="http://blog.rubybestpractices.com/posts/gregory/008-decorator-delegator-disco.html">this</a> specific post regarding <code>switch</code> use with objects, I thought it&#8217;s good to talk about this feature.<br />
So basically and taken from this <a href="http://www.artima.com/scalazine/articles/pattern_matching.html">post </a>:</p>
<blockquote><p>
So what does pattern matching do? It lets you match a value against several cases, sort of like a switch statement in Java. But instead of just matching numbers, which is what switch statements do, you match what are essentially the creation forms of objects. </p></blockquote>
<p>And the following example:</p>

<div class="wp_syntax"><div class="code"><pre class="scala" style="font-family:monospace;">x <span style="color: #0000ff; font-weight: bold;">match</span> <span style="color: #F78811;">&#123;</span>
  <span style="color: #0000ff; font-weight: bold;">case</span> Address<span style="color: #F78811;">&#40;</span>Name<span style="color: #F78811;">&#40;</span>first, last<span style="color: #F78811;">&#41;</span>, street, city, state, zip<span style="color: #F78811;">&#41;</span> <span style="color: #000080;">=&gt;</span> println<span style="color: #F78811;">&#40;</span>last + <span style="color: #6666FF;">&quot;, &quot;</span> + zip<span style="color: #F78811;">&#41;</span>
  <span style="color: #0000ff; font-weight: bold;">case</span> <span style="color: #000080;">_</span> <span style="color: #000080;">=&gt;</span> println<span style="color: #F78811;">&#40;</span><span style="color: #6666FF;">&quot;not an address&quot;</span><span style="color: #F78811;">&#41;</span> <span style="color: #008000; font-style: italic;">// the default case</span>
<span style="color: #F78811;">&#125;</span></pre></div></div>

<p>In the first case, the pattern Name(first, last) is nested inside the pattern Address(&#8230;). The last value, which was passed to the Name constructor, is &#8220;extracted&#8221; and therefore usable in the expression to the right of the arrow. </p>
<p>Then </p>
<blockquote><p><strong>The purpose of pattern matching</strong></p>
<p>So why do you need pattern matching? We all have complicated data. If we adhere to a strict object-oriented style, then we don&#8217;t want to look inside these trees of data. Instead, we want to call methods, and let the methods do the right thing. If we have the ability to do that, we don&#8217;t need pattern matching so much, because the methods do what we need. But there are many situations where the objects don&#8217;t have the methods we need, and we can&#8217;t (or don&#8217;t want to) add new methods to the objects. </p></blockquote>
<p>So, Pattern matching is considered a valid way of extensibility, and it offers a great solution to this problem apart from the verbosity that comes with <a href="http://en.wikipedia.org/wiki/Visitor_pattern">Visitor design pattern</a>.</p>
<p>Anyway, it&#8217;s highly recommended that you read the &#8220;<em>Two directions of extensibility</em>&#8221; in the previous mentioned article.</p>
<h2>Easy DSLs</h2>
<p>Scala is very good for coding <a href="http://en.wikipedia.org/wiki/Domain-specific_language">DSLs</a>. Actually Scala is suitable for both Internal and external DSLs. You can find in this <a href="http://www.artima.com/weblogs/viewpost.jsp?thread=251945">article</a> a little comparison of features between Ruby and Scala for writing internal DSLs. Check this cool post on internal DSLs using Scala: <a href=" http://gabrielsw.blogspot.com/2009/06/boolean-algebra-internal-dsl-in-scala.html">Boolean Algebra Internal DSL in Scala (aka fun with Unicode names )</a>.<br />
Also when it comes to External DSLs, Scala should be your first choice, and the reason behind that is the <a href="http://www.Scala-lang.org/docu/files/api/Scala/util/parsing/combinator/Parsers.html">parser combinator</a> lib, that makes writing compilers for new languages is really cool. You&#8217;d better follow this cool <a href="http://www.codecommit.com/blog/Scala/the-magic-behind-parser-combinators">post</a> to get a better idea about what Scala can do.</p>
<h2>Interoperable with Java code</h2>
<p>The JVM implementation of Scala have seamless integration with Java platform, actually many Scala types compiles down to Java types, so you can use Java libs safely. Also you can make some work between JVM languages like <a href="http://www.jRuby.org">JRuby</a>, <a href="http://groovy.codehaus.org/"> Groovy</a>, <a href= "http://clojure.org/">Clojure</a> and others.<br />
<a href="http://www.codecommit.com/blog/java/interop-between-java-and-scala">Here</a> is a good post with examples.</p>
<h2>Educational language</h2>
<p>I had 2 habits that I kept practicing during the learning curve of Scala :</p>
<ul>
<li>Going to Wikipedia every while to read more about the new technical terms I passed by; terms like <a href="http://en.wikipedia.org/wiki/First-class_function">Function literals</a>, <a href="http://en.wikipedia.org/wiki/Referential_transparency_%28computer_science%29">Referentially transparent</a>, <a href="http://en.wikipedia.org/wiki/Partial_function">Partial functions</a>, <a href="http://en.wikipedia.org/wiki/Currying">Currying</a> and so many other terms.</li>
<li>Revising my knowledge in other languages to check if these terms are implemented somehow.</li>
</ul>
<p>Both of these two habits made me gain more knowledge and increased the quality of my code through some good practices like: writing pure methods that has no side effect and focusing on the &#8216;what&#8217; part of my code, leaving the &#8216;how&#8217; one to language abstractions..  </p>
<h2>Team</h2>
<p>Scala was designed by <a href="http://people.epfl.ch/martin.odersky">Martin Odersky</a> the man running the Programming Methods Laboratory (LAMP) group at Swiss Federal Institute of Technology in Lausanne (EPFL). Odersky was approached by Sun to write the Java 1.1 compiler, he was the lead developer of javac from Java 1.1 through Java 1.4. Also he is the guy behind Java Generics.<br />
Scala is being maintained by Odersky and his team at EPFL. However there are other talented folks who helped shaping Scala over years, you can check the full list <a href="http://www.Scala-lang.org/node/89">here</a>.</p>
<h2>Roots</h2>
<p>Scala was inspired by many languages:</p>
<ul>
<li>Most of the syntax is coming from Java and C#.</li>
<li>	Other elements where adopted from Java such as: basic types, class libraries, and its execution model.</li>
<li>Its uniform object model was pioneered by Smalltalk.</li>
<li>Its idea of universal nesting is also present in Algol, Simula, and, more recently in Beta and gbeta.</li>
<li>Its uniform access principle for method invocation and field selection comes from Eiffel.</li>
<li>Its approach to functional programming is quite similar in spirit to the ML family of languages, which has SML, OCaml, and F# as prominent members.</li>
<li>Many higher-order functions in Scalaâ€™s standard library are also present in ML or Haskell. </li>
<li>Scalaâ€™s implicit parameters were motivated by Haskellâ€™s type classes. Scalaâ€™s actor-based concurrency library was heavily inspired by Erlang.</li>
<li>The specific idea of treating an infix operator as a function and permitting a function literal (or block) as a parameter, which enables libraries to define control structures can be traced back to Iswim and Smalltalk.</li>
</ul>
<h2>Experts&#8217; Opinions</h2>
<p>This <a href="http://www.infoq.com/news/2009/07/scala-replace-java">article</a> is a very good one showing some for experts&#8217; opinions regarding Scala language. Actually it has some surprises like James Strachan&#8217;s(creator of Groovy language) statement: </p>
<blockquote><p>I can honestly say if someone had shown me the Programming in Scala book by Martin Odersky, Lex Spoon &#038; Bill Venners back in 2003 I&#8217;d probably have never created Groovy </p></blockquote>
<p>Also I have found these interviews to be very useful:</p>
<ul>
<li><a href="http://on-ruby.blogspot.com/2009/03/beginning-scala-author-interview-with.html">Beginning Scala &#8212; Author Interview with David Pollak</a></li>
<li>  <a href="http://on-ruby.blogspot.com/2009/03/dean-wampler-and-alex-payne-author.html"> Dean Wampler and Alex Payne: Author Interview</a></li>
<li>  <a href="http://on-ruby.blogspot.com/2009/03/author-interview-venkat-subramaniam.html">Author Interview: Venkat Subramaniam</a></li>
</ul>
<hr/>
<strong>At the end of this point I like to sum things up:</strong><br />
I like Scala because it&#8217;s efficient, educational, has better concurrency model, and very good for writing DSLs.<br />
<strong>I also want to share another secret with you:</strong><br />
 I&#8217;m planning to write a book on Scala language, I have an idea at mind and would like to coauthor with any guy from the Scala camp, please ping me if you have the same attention as mine.</p>
<hr/>
<h2>Real World Examples</h2>
<ul>
<li><a href="http://www.artima.com/scalazine/articles/twitter_on_scala.html">Twitter</a></li>
<li> <a href="http://liftweb.net/">Lift</a> framework.</li>
<li><a href="http://www.scala-lang.org/node/1658">Many other</a> examples</li>
</ul>
<h2>Resources</h2>
<ul>
<li><a href="http://www.artima.com/shop/programming_in_scala">Programming in Scala</a> book.</li>
<li><a href="http://www.apress.com/book/view/1430219890">Beginning Scala</a> book.</li>
<li><a href="http://www.scala-lang.org/node/198">Scala reference manuals </a> page, contains very useful free PDFs </li>
<li><a href="http://www.ibm.com/developerworks/views/java/libraryview.jsp?search_by=scala+neward">Scala series</a> on IBM developerWorks website.</li>
</ul>
<div class="addthis_toolbox addthis_default_style addthis_32x32_style" addthis:url='http://khelll.com/blog/scala/scala-is-my-next-choice/' addthis:title='Scala is my next choice' ><a class="addthis_button_twitter"></a><a class="addthis_button_facebook"></a><a class="addthis_button_email"></a><a class="addthis_button_print"></a><a class="addthis_button_compact"></a></div>]]></content:encoded>
			<wfw:commentRss>http://khelll.com/blog/scala/scala-is-my-next-choice/feed/</wfw:commentRss>
		<slash:comments>28</slash:comments>
		</item>
		<item>
		<title>Ruby Currying</title>
		<link>http://khelll.com/blog/ruby/ruby-currying/</link>
		<comments>http://khelll.com/blog/ruby/ruby-currying/#comments</comments>
		<pubDate>Mon, 25 May 2009 04:36:46 +0000</pubDate>
		<dc:creator>khelll</dc:creator>
				<category><![CDATA[Functional Programming]]></category>
		<category><![CDATA[Ruby]]></category>
		<category><![CDATA[currying]]></category>

		<guid isPermaLink="false">http://www.khelll.com/blog/?p=401</guid>
		<description><![CDATA[<div class="addthis_toolbox addthis_default_style " addthis:url='http://khelll.com/blog/ruby/ruby-currying/' addthis:title='Ruby Currying '  ><a class="addthis_button_facebook_like" fb:like:layout="button_count"></a><a class="addthis_button_tweet"></a><a class="addthis_counter addthis_pill_style"></a></div>Update: This post was updated to show the difference between Currying and Partial Functions. Currying is a concept in Functional Programming that&#8217;s enabled by Higher-order functions. It&#8217;s best described as: the ability to take a function that accepts n parameters &#8230; <a href="http://khelll.com/blog/ruby/ruby-currying/">Continue reading <span class="meta-nav">&#8594;</span></a><div class="addthis_toolbox addthis_default_style addthis_32x32_style" addthis:url='http://khelll.com/blog/ruby/ruby-currying/' addthis:title='Ruby Currying' ><a class="addthis_button_twitter"></a><a class="addthis_button_facebook"></a><a class="addthis_button_email"></a><a class="addthis_button_print"></a><a class="addthis_button_compact"></a></div>]]></description>
			<content:encoded><![CDATA[<div class="addthis_toolbox addthis_default_style " addthis:url='http://khelll.com/blog/ruby/ruby-currying/' addthis:title='Ruby Currying '  ><a class="addthis_button_facebook_like" fb:like:layout="button_count"></a><a class="addthis_button_tweet"></a><a class="addthis_counter addthis_pill_style"></a></div><p><strong>Update: This post was updated to show the difference between Currying and Partial Functions.</strong><br />
<strong>Currying</strong> is a concept in Functional Programming that&#8217;s enabled by Higher-order functions. It&#8217;s best described as: the ability to take a function that accepts n parameters and turns it into a composition of <code>n</code> functions each of them take 1 parameter.  Check this function <em>f</em> which takes 3 params <em>x</em>,<em>y</em>,<em>z</em></p>
<p><code>f(x,y,z) = 4*x+3*y+2*z</code></p>
<p>Currying means that we can rewrite the function as a composition of 3 functions(a function for each param):</p>
<p><code>f(x)(y)(z) = 2*z+(3*y+(4*x))</code></p>
<p>The direct use of this is what is called <strong>Partial Function</strong> where if you have a function that accepts n parameters then you can generate from it one of more functions with some parameter values already filled in.  Ruby 1.9 comes with support for currying concept(through the Proc#curry method) and this blog post is explaining how you can use it effectively.<br />
I&#8217;m going to walk you through a simple example to explain the concept, however i need to mention few things:<br />
1- The main example is taken from the free <a href="http://www.scala-lang.org/sites/default/files/linuxsoft_archives/docu/files/ScalaByExample.pdf">Scala By Example</a> book(First-Class Functions chapter), however i have replaced recursion calls by simple <code>upto</code> iterators.<br />
2- In Ruby 1.9 you can use block.(*args) just like you use <code>block.call(*args)</code> or <code>block[*args]</code> in Ruby 1.8, so i&#8217;ll stick to  <code>block.(*)</code> notation.<br />
3- I could have used the <code>inject</code> method, but i preferred readability to concise code. </p>
<p>Let&#8217;s start the simple tutorial by adding three methods:<br />
1- A method to sum all integers between two given numbers <code>a</code> and <code>b</code>.<br />
2- A method to sum the squares of all integers between two given numbers <code>a</code> and <code>b</code>.<br />
3- A method to to sum the powers <code>2^n</code> of all integers <code>n</code> between two given numbers <code>a</code> and <code>b</code>.</p>

<div class="wp_syntax"><div class="code"><pre class="ruby" style="font-family:monospace;"><span style="color:#008000; font-style:italic;">###################################</span>
<span style="color:#008000; font-style:italic;"># Normal definitions</span>
<span style="color:#008000; font-style:italic;">###################################</span>
sum_ints = <span style="color:#CC0066; font-weight:bold;">lambda</span> <span style="color:#9966CC; font-weight:bold;">do</span> <span style="color:#006600; font-weight:bold;">|</span>a,b<span style="color:#006600; font-weight:bold;">|</span>
  s = <span style="color:#006666;">0</span> ; a.<span style="color:#9900CC;">upto</span><span style="color:#006600; font-weight:bold;">&#40;</span>b<span style="color:#006600; font-weight:bold;">&#41;</span><span style="color:#006600; font-weight:bold;">&#123;</span><span style="color:#006600; font-weight:bold;">|</span>n<span style="color:#006600; font-weight:bold;">|</span> s <span style="color:#006600; font-weight:bold;">+</span>= n <span style="color:#006600; font-weight:bold;">&#125;</span> ; s 
<span style="color:#9966CC; font-weight:bold;">end</span>
&nbsp;
sum_of_squares = <span style="color:#CC0066; font-weight:bold;">lambda</span> <span style="color:#9966CC; font-weight:bold;">do</span> <span style="color:#006600; font-weight:bold;">|</span>a,b<span style="color:#006600; font-weight:bold;">|</span>
  s = <span style="color:#006666;">0</span> ; a.<span style="color:#9900CC;">upto</span><span style="color:#006600; font-weight:bold;">&#40;</span>b<span style="color:#006600; font-weight:bold;">&#41;</span><span style="color:#006600; font-weight:bold;">&#123;</span><span style="color:#006600; font-weight:bold;">|</span>n<span style="color:#006600; font-weight:bold;">|</span> s <span style="color:#006600; font-weight:bold;">+</span>= n<span style="color:#006600; font-weight:bold;">**</span><span style="color:#006666;">2</span> <span style="color:#006600; font-weight:bold;">&#125;</span> ;s 
<span style="color:#9966CC; font-weight:bold;">end</span>
&nbsp;
sum_of_powers_of_2 = <span style="color:#CC0066; font-weight:bold;">lambda</span> <span style="color:#9966CC; font-weight:bold;">do</span> <span style="color:#006600; font-weight:bold;">|</span>a,b<span style="color:#006600; font-weight:bold;">|</span>
  s = <span style="color:#006666;">0</span> ; a.<span style="color:#9900CC;">upto</span><span style="color:#006600; font-weight:bold;">&#40;</span>b<span style="color:#006600; font-weight:bold;">&#41;</span><span style="color:#006600; font-weight:bold;">&#123;</span><span style="color:#006600; font-weight:bold;">|</span>n<span style="color:#006600; font-weight:bold;">|</span> s <span style="color:#006600; font-weight:bold;">+</span>= <span style="color:#006666;">2</span><span style="color:#006600; font-weight:bold;">**</span>n <span style="color:#006600; font-weight:bold;">&#125;</span> ; s 
<span style="color:#9966CC; font-weight:bold;">end</span>
&nbsp;
<span style="color:#CC0066; font-weight:bold;">puts</span> sum_ints.<span style="color:#006600; font-weight:bold;">&#40;</span><span style="color:#006666;">1</span>,<span style="color:#006666;">5</span><span style="color:#006600; font-weight:bold;">&#41;</span> <span style="color:#008000; font-style:italic;">#=&gt; 15</span>
<span style="color:#CC0066; font-weight:bold;">puts</span> sum_of_squares.<span style="color:#006600; font-weight:bold;">&#40;</span><span style="color:#006666;">1</span>,<span style="color:#006666;">5</span><span style="color:#006600; font-weight:bold;">&#41;</span> <span style="color:#008000; font-style:italic;">#=&gt; 55</span>
<span style="color:#CC0066; font-weight:bold;">puts</span> sum_of_powers_of_2.<span style="color:#006600; font-weight:bold;">&#40;</span><span style="color:#006666;">1</span>,<span style="color:#006666;">5</span><span style="color:#006600; font-weight:bold;">&#41;</span> <span style="color:#008000; font-style:italic;">#=&gt; 62</span></pre></div></div>

<p>Cool, however if you focus on the 3 methods, you will notice that these methods are all instances of a pattern &Sigma;f(n) for a range of  values a -> b. We can factor out the common pattern by defining a method sum:</p>

<div class="wp_syntax"><div class="code"><pre class="ruby" style="font-family:monospace;"><span style="color:#008000; font-style:italic;">############################################</span>
<span style="color:#008000; font-style:italic;"># Some refactoring to make some abstraction</span>
<span style="color:#008000; font-style:italic;"># Passing the sum mechanism itself</span>
<span style="color:#008000; font-style:italic;">############################################</span>
&nbsp;
sum = <span style="color:#CC0066; font-weight:bold;">lambda</span> <span style="color:#9966CC; font-weight:bold;">do</span> <span style="color:#006600; font-weight:bold;">|</span>f,a,b<span style="color:#006600; font-weight:bold;">|</span>
  s = <span style="color:#006666;">0</span> ; a.<span style="color:#9900CC;">upto</span><span style="color:#006600; font-weight:bold;">&#40;</span>b<span style="color:#006600; font-weight:bold;">&#41;</span><span style="color:#006600; font-weight:bold;">&#123;</span><span style="color:#006600; font-weight:bold;">|</span>n<span style="color:#006600; font-weight:bold;">|</span> s <span style="color:#006600; font-weight:bold;">+</span>= f.<span style="color:#006600; font-weight:bold;">&#40;</span>n<span style="color:#006600; font-weight:bold;">&#41;</span> <span style="color:#006600; font-weight:bold;">&#125;</span> ; s 
<span style="color:#9966CC; font-weight:bold;">end</span>
&nbsp;
<span style="color:#CC0066; font-weight:bold;">puts</span> sum.<span style="color:#006600; font-weight:bold;">&#40;</span><span style="color:#CC0066; font-weight:bold;">lambda</span><span style="color:#006600; font-weight:bold;">&#123;</span><span style="color:#006600; font-weight:bold;">|</span>x<span style="color:#006600; font-weight:bold;">|</span> x<span style="color:#006600; font-weight:bold;">&#125;</span>,<span style="color:#006666;">1</span>,<span style="color:#006666;">5</span><span style="color:#006600; font-weight:bold;">&#41;</span> <span style="color:#008000; font-style:italic;">#=&gt; 15</span>
<span style="color:#CC0066; font-weight:bold;">puts</span> sum.<span style="color:#006600; font-weight:bold;">&#40;</span><span style="color:#CC0066; font-weight:bold;">lambda</span><span style="color:#006600; font-weight:bold;">&#123;</span><span style="color:#006600; font-weight:bold;">|</span>x<span style="color:#006600; font-weight:bold;">|</span> x<span style="color:#006600; font-weight:bold;">**</span><span style="color:#006666;">2</span><span style="color:#006600; font-weight:bold;">&#125;</span>,<span style="color:#006666;">1</span>,<span style="color:#006666;">5</span><span style="color:#006600; font-weight:bold;">&#41;</span> <span style="color:#008000; font-style:italic;">#=&gt; 55</span>
<span style="color:#CC0066; font-weight:bold;">puts</span> sum.<span style="color:#006600; font-weight:bold;">&#40;</span><span style="color:#CC0066; font-weight:bold;">lambda</span><span style="color:#006600; font-weight:bold;">&#123;</span><span style="color:#006600; font-weight:bold;">|</span>x<span style="color:#006600; font-weight:bold;">|</span> <span style="color:#006666;">2</span><span style="color:#006600; font-weight:bold;">**</span>x<span style="color:#006600; font-weight:bold;">&#125;</span>,<span style="color:#006666;">1</span>,<span style="color:#006666;">5</span><span style="color:#006600; font-weight:bold;">&#41;</span> <span style="color:#008000; font-style:italic;">#=&gt; 62</span></pre></div></div>

<p>Ok, but what about having the formal definitions for the 3 methods? How can we have those definitions out of the <code>sum</code> method? Well that&#8217;s the use of currying and partial functions, in our case we just need to pass the first param to the <code>sum</code> method to specify what type of sum is it:</p>

<div class="wp_syntax"><div class="code"><pre class="ruby" style="font-family:monospace;"><span style="color:#008000; font-style:italic;">###################################</span>
<span style="color:#008000; font-style:italic;"># More refactoring using currying</span>
<span style="color:#008000; font-style:italic;"># Currying was added to Ruby 1.9</span>
<span style="color:#008000; font-style:italic;"># Via Proc#curry</span>
<span style="color:#008000; font-style:italic;">###################################</span>
&nbsp;
<span style="color:#008000; font-style:italic;"># generate the currying</span>
currying = sum.<span style="color:#9900CC;">curry</span>
&nbsp;
<span style="color:#008000; font-style:italic;"># Generate the partial functions</span>
sum_ints = currying.<span style="color:#006600; font-weight:bold;">&#40;</span><span style="color:#CC0066; font-weight:bold;">lambda</span><span style="color:#006600; font-weight:bold;">&#123;</span><span style="color:#006600; font-weight:bold;">|</span>x<span style="color:#006600; font-weight:bold;">|</span> x<span style="color:#006600; font-weight:bold;">&#125;</span><span style="color:#006600; font-weight:bold;">&#41;</span>
sum_of_squares = currying.<span style="color:#006600; font-weight:bold;">&#40;</span><span style="color:#CC0066; font-weight:bold;">lambda</span><span style="color:#006600; font-weight:bold;">&#123;</span><span style="color:#006600; font-weight:bold;">|</span>x<span style="color:#006600; font-weight:bold;">|</span> x<span style="color:#006600; font-weight:bold;">**</span><span style="color:#006666;">2</span><span style="color:#006600; font-weight:bold;">&#125;</span><span style="color:#006600; font-weight:bold;">&#41;</span>
sum_of_powers_of_2 = currying.<span style="color:#006600; font-weight:bold;">&#40;</span><span style="color:#CC0066; font-weight:bold;">lambda</span><span style="color:#006600; font-weight:bold;">&#123;</span><span style="color:#006600; font-weight:bold;">|</span>x<span style="color:#006600; font-weight:bold;">|</span> <span style="color:#006666;">2</span><span style="color:#006600; font-weight:bold;">**</span>x<span style="color:#006600; font-weight:bold;">&#125;</span><span style="color:#006600; font-weight:bold;">&#41;</span>
&nbsp;
<span style="color:#CC0066; font-weight:bold;">puts</span> sum_ints.<span style="color:#006600; font-weight:bold;">&#40;</span><span style="color:#006666;">1</span>,<span style="color:#006666;">5</span><span style="color:#006600; font-weight:bold;">&#41;</span> <span style="color:#008000; font-style:italic;">#=&gt; 15</span>
<span style="color:#CC0066; font-weight:bold;">puts</span> sum_of_squares.<span style="color:#006600; font-weight:bold;">&#40;</span><span style="color:#006666;">1</span>,<span style="color:#006666;">5</span><span style="color:#006600; font-weight:bold;">&#41;</span> <span style="color:#008000; font-style:italic;">#=&gt; 55</span>
<span style="color:#CC0066; font-weight:bold;">puts</span> sum_of_powers_of_2.<span style="color:#006600; font-weight:bold;">&#40;</span><span style="color:#006666;">1</span>,<span style="color:#006666;">5</span><span style="color:#006600; font-weight:bold;">&#41;</span> <span style="color:#008000; font-style:italic;">#=&gt; 62</span></pre></div></div>

<p>That&#8217;s it! I hope I could clarify the use of currying, if not just add your comment here <img src='http://khelll.com/blog/wp-includes/images/smilies/icon_wink.gif' alt=';)' class='wp-smiley' />  </p>
<div class="addthis_toolbox addthis_default_style addthis_32x32_style" addthis:url='http://khelll.com/blog/ruby/ruby-currying/' addthis:title='Ruby Currying' ><a class="addthis_button_twitter"></a><a class="addthis_button_facebook"></a><a class="addthis_button_email"></a><a class="addthis_button_print"></a><a class="addthis_button_compact"></a></div>]]></content:encoded>
			<wfw:commentRss>http://khelll.com/blog/ruby/ruby-currying/feed/</wfw:commentRss>
		<slash:comments>8</slash:comments>
		</item>
		<item>
		<title>Ruby and Functional Programming</title>
		<link>http://khelll.com/blog/ruby/ruby-and-functional-programming/</link>
		<comments>http://khelll.com/blog/ruby/ruby-and-functional-programming/#comments</comments>
		<pubDate>Sun, 24 May 2009 12:28:30 +0000</pubDate>
		<dc:creator>khelll</dc:creator>
				<category><![CDATA[Functional Programming]]></category>
		<category><![CDATA[Ruby]]></category>

		<guid isPermaLink="false">http://www.khelll.com/blog/?p=351</guid>
		<description><![CDATA[<div class="addthis_toolbox addthis_default_style " addthis:url='http://khelll.com/blog/ruby/ruby-and-functional-programming/' addthis:title='Ruby and Functional Programming '  ><a class="addthis_button_facebook_like" fb:like:layout="button_count"></a><a class="addthis_button_tweet"></a><a class="addthis_counter addthis_pill_style"></a></div>Ruby is known to support the functional paradigm. This article is going to walk you through the Functional Programming page on WikiPedia, to revise the general concepts of functional programming and to explain how Ruby supports them. According to wikipedia, &#8230; <a href="http://khelll.com/blog/ruby/ruby-and-functional-programming/">Continue reading <span class="meta-nav">&#8594;</span></a><div class="addthis_toolbox addthis_default_style addthis_32x32_style" addthis:url='http://khelll.com/blog/ruby/ruby-and-functional-programming/' addthis:title='Ruby and Functional Programming' ><a class="addthis_button_twitter"></a><a class="addthis_button_facebook"></a><a class="addthis_button_email"></a><a class="addthis_button_print"></a><a class="addthis_button_compact"></a></div>]]></description>
			<content:encoded><![CDATA[<div class="addthis_toolbox addthis_default_style " addthis:url='http://khelll.com/blog/ruby/ruby-and-functional-programming/' addthis:title='Ruby and Functional Programming '  ><a class="addthis_button_facebook_like" fb:like:layout="button_count"></a><a class="addthis_button_tweet"></a><a class="addthis_counter addthis_pill_style"></a></div><p>Ruby is known to support the functional paradigm. This article is going to walk you through the Functional Programming <a href="http://en.wikipedia.org/wiki/Functional_programming">page</a> on WikiPedia, to revise the general concepts of functional programming and to explain how Ruby supports them.<br />
According to wikipedia, a functional programming can be described as follows:</p>
<blockquote><p>In computer science, functional programming is a programming paradigm that treats computation as the evaluation of mathematical functions and avoids state and mutable data. It emphasizes the application of functions, in contrast to the imperative programming style, which emphasizes changes in state. Functional programming has its roots in the lambda calculus, a formal system developed in the 1930s to investigate function definition, function application, and recursion. Many functional programming languages can be viewed as embellishments to the lambda calculus.</p></blockquote>
<p>That&#8217;s a clear definition, however and if it&#8217;s not, the following walk through some <strong>concepts</strong> of functional programming should result in a better understanding:  </p>
<h2>Pure functions</h2>
<blockquote><p>In practice, the difference between a mathematical function and the notion of a &#8220;function&#8221; used in imperative programming is that imperative functions can have side effects, changing the value of already calculated computations. Because of this they lack referential transparency, i.e. the same language expression can result in different values at different times depending on the state of the executing program. Conversely, in functional code, the output value of a function depends only on the arguments that are input to the function, so calling a function f twice with the same value for an argument x will produce the same result f(x) both times. Eliminating side-effects can make it much easier to understand and predict the behavior of a program, which is one of the key motivations for the development of functional programming.</p></blockquote>
<p>Pure functions support the mathematical definition of a function:</p>
<p><em> y = f(x)</em></p>
<p>Which means:<br />
1- A function should return the same exact value given the same exact input.<br />
2- A function does one thing exactly(has one clear mission), it has no side effects like changing some other value or write to stream or any other mission rather than its assigned one.</p>
<p>In fact Ruby doesn&#8217;t force you to write pure functions, but certainly it helps you to do so. Actually exercising yourself to write in pure functional style when possible helps you really in many ways:<br />
1- It makes your code clean, readable and self-documenting.<br />
2- It makes your code more &#8220;thread safe&#8221;<br />
3- It helps you more when it comes to TDD.</p>
<p>Let&#8217;s have a look on how Ruby helps you do Pure functional code:</p>
<h3>The <code>!</code> symbol</h3>
<p>Most of Ruby programmers know the <code>!</code> symbol that comes at the end of method names like <code>gsub!</code>, <code>merge!</code> and many other methods. The <code>!</code> symbol means: &#8220;Use it cautiously&#8221;. However If you focus more, you will notice that <strong>most of time</strong>, the <code>!</code> symbol means: &#8220;This is a method that has a side effect; it alters the object which is invoked on!&#8221;.</p>

<div class="wp_syntax"><div class="code"><pre class="ruby" style="font-family:monospace;">s = <span style="color:#996600;">&quot;hello&quot;</span> <span style="color:#008000; font-style:italic;">#=&gt; &quot;hello&quot;</span>
up_s = s.<span style="color:#9900CC;">upcase</span> <span style="color:#008000; font-style:italic;">#=&gt; &quot;HELLO&quot;</span>
<span style="color:#CC0066; font-weight:bold;">puts</span> s.<span style="color:#9900CC;">upcase</span>! <span style="color:#008000; font-style:italic;">#=&gt; &quot;HELLO&quot;</span>
<span style="color:#CC0066; font-weight:bold;">puts</span> s <span style="color:#008000; font-style:italic;">#=&gt; &quot;HELLO&quot;</span></pre></div></div>

<p>As you can see, the <code>upcase!</code> method is not a pure functional method cause it has a side effect, it changes the string itself. On the other hand, the <code>upcase</code> method is a pure functional one as it returns the corresponding value with no other side effects.</p>
<p>On all hows, it&#8217;s highly recommended that you stick to this convention of method naming when you code in Ruby.</p>
<h3>Expressions</h3>
<p><strong>Everything is evaluated as an expression in Ruby</strong>: literals, method calls, variables&#8230; even a control structure has a value. For example you can do this in Ruby:</p>

<div class="wp_syntax"><div class="code"><pre class="ruby" style="font-family:monospace;"><span style="color:#9966CC; font-weight:bold;">if</span> num == <span style="color:#996600;">&quot;one&quot;</span> <span style="color:#9966CC; font-weight:bold;">then</span> val = <span style="color:#006666;">1</span>
<span style="color:#9966CC; font-weight:bold;">elsif</span> num == <span style="color:#996600;">&quot;two&quot;</span> <span style="color:#9966CC; font-weight:bold;">then</span> val = <span style="color:#006666;">2</span>
<span style="color:#9966CC; font-weight:bold;">else</span> <span style="color:#9966CC; font-weight:bold;">then</span> val = <span style="color:#006666;">3</span>
<span style="color:#9966CC; font-weight:bold;">end</span></pre></div></div>

<p>But that is a weak use of Ruby&#8217;s power, instead you&#8217;d better do:</p>

<div class="wp_syntax"><div class="code"><pre class="ruby" style="font-family:monospace;">val = <span style="color:#9966CC; font-weight:bold;">if</span> num == <span style="color:#996600;">&quot;one&quot;</span> <span style="color:#9966CC; font-weight:bold;">then</span>   <span style="color:#006666;">1</span>
<span style="color:#9966CC; font-weight:bold;">elsif</span> num == <span style="color:#996600;">&quot;two&quot;</span> <span style="color:#9966CC; font-weight:bold;">then</span>  <span style="color:#006666;">2</span>
<span style="color:#9966CC; font-weight:bold;">else</span> <span style="color:#006666;">3</span>
<span style="color:#9966CC; font-weight:bold;">end</span></pre></div></div>

<h3>Return value</h3>
<p>Ruby returns the last expression value as the return value of the method invocation, so you don&#8217;t need an explicit <code>return</code> statement.</p>

<div class="wp_syntax"><div class="code"><pre class="ruby" style="font-family:monospace;"><span style="color:#9966CC; font-weight:bold;">def</span> greeting<span style="color:#006600; font-weight:bold;">&#40;</span>name<span style="color:#006600; font-weight:bold;">&#41;</span>
  <span style="color:#996600;">&quot;Hello #{name}!&quot;</span>
<span style="color:#9966CC; font-weight:bold;">end</span>
<span style="color:#CC0066; font-weight:bold;">puts</span> greeting<span style="color:#006600; font-weight:bold;">&#40;</span><span style="color:#996600;">'khelll'</span><span style="color:#006600; font-weight:bold;">&#41;</span> <span style="color:#008000; font-style:italic;">#=&gt; &quot;Hello khelll!&quot;</span></pre></div></div>

<p>Together, the auto returned value and evaluating code as expressions are indeed a big support for pure functional code as finally they both serve the fact of having a value out of your method.</p>
<h2>Higher-order functions</h2>
<p>Functions are higher-order when they can take other functions as arguments, and return them as results. This is done in Ruby using lambda and block logic. If you don&#8217;t know how to use blocks, please do yourself a favor and visit this <a href="http://www.robertsosinski.com/2008/12/21/understanding-ruby-blocks-procs-and-lambdas/">comprehensive article</a> by Robert Sosinski.</p>
<p>Blocks in Ruby can help you do very nice things, one of them is ability to add control structure like syntax to your code. Check the following example, where a loop control structure is being defined:</p>

<div class="wp_syntax"><div class="code"><pre class="ruby" style="font-family:monospace;"><span style="color:#008000; font-style:italic;"># a trivial example that adds a loop control structure</span>
<span style="color:#008000; font-style:italic;"># it takes a range and yields the passed block.</span>
<span style="color:#9966CC; font-weight:bold;">def</span> <span style="color:#CC0066; font-weight:bold;">loop</span><span style="color:#006600; font-weight:bold;">&#40;</span>x,<span style="color:#006600; font-weight:bold;">&amp;</span>b<span style="color:#006600; font-weight:bold;">&#41;</span>
  <span style="color:#9966CC; font-weight:bold;">for</span> i <span style="color:#9966CC; font-weight:bold;">in</span> x <span style="color:#9966CC; font-weight:bold;">do</span>
    b.<span style="color:#9900CC;">call</span><span style="color:#006600; font-weight:bold;">&#40;</span>i<span style="color:#006600; font-weight:bold;">&#41;</span>
  <span style="color:#9966CC; font-weight:bold;">end</span>
<span style="color:#9966CC; font-weight:bold;">end</span>
&nbsp;
<span style="color:#008000; font-style:italic;"># use the above defined method</span>
<span style="color:#CC0066; font-weight:bold;">loop</span><span style="color:#006600; font-weight:bold;">&#40;</span><span style="color:#006666;">1</span>..<span style="color:#006666;">10</span><span style="color:#006600; font-weight:bold;">&#41;</span> <span style="color:#9966CC; font-weight:bold;">do</span> <span style="color:#006600; font-weight:bold;">|</span>x<span style="color:#006600; font-weight:bold;">|</span>
  <span style="color:#CC0066; font-weight:bold;">puts</span> x
<span style="color:#9966CC; font-weight:bold;">end</span></pre></div></div>

<p><a href="http://www.khelll.com/blog/ruby/ruby-and-internal-dsls/">Internal DSLs</a> is also one of the nice things that you can achieve with block syntax in Ruby.</p>
<h3>Currying and Partial Functions</h3>
<p>Higher-order functions enable <strong>Currying</strong>, which the ability to take a function that accepts n parameters and turns it into a composition of n functions each of them take 1 parameter. A direct use of currying is the <strong>Partial Functions</strong> where if you have a function that accepts n parameters then you can generate from it one of more functions with some parameter values already filled in. Ruby 1.9 comes with support for this concept. check the following example:</p>

<div class="wp_syntax"><div class="code"><pre class="ruby" style="font-family:monospace;"><span style="color:#008000; font-style:italic;"># defining a proc that sums 2 numbers</span>
plus = <span style="color:#CC0066; font-weight:bold;">lambda</span> <span style="color:#006600; font-weight:bold;">&#123;</span><span style="color:#006600; font-weight:bold;">|</span>a,b<span style="color:#006600; font-weight:bold;">|</span> a <span style="color:#006600; font-weight:bold;">+</span> b<span style="color:#006600; font-weight:bold;">&#125;</span> <span style="color:#008000; font-style:italic;">#=&gt; #&lt;Proc:0x8e236ac@(irb):1 (lambda)&gt; </span>
&nbsp;
<span style="color:#008000; font-style:italic;"># notice the new call to procs in ruby 1.9 using the period symbol</span>
plus.<span style="color:#006600; font-weight:bold;">&#40;</span><span style="color:#006666;">3</span>,<span style="color:#006666;">5</span><span style="color:#006600; font-weight:bold;">&#41;</span> <span style="color:#008000; font-style:italic;">#=&gt; 8 </span>
&nbsp;
<span style="color:#008000; font-style:italic;"># i want a modified version of the above proc that fills the first parameter with the value '1'</span>
<span style="color:#008000; font-style:italic;"># so i generate the currying then i use a partial function by supplying the first parameter</span>
<span style="color:#008000; font-style:italic;"># with value '1'</span>
plus_one = plus.<span style="color:#9900CC;">curry</span>.<span style="color:#006600; font-weight:bold;">&#40;</span><span style="color:#006666;">1</span><span style="color:#006600; font-weight:bold;">&#41;</span> <span style="color:#008000; font-style:italic;">#=&gt; #&lt;Proc:0x8dde908&gt;</span>
&nbsp;
<span style="color:#008000; font-style:italic;"># I can use the new proc as normal</span>
plus_one.<span style="color:#006600; font-weight:bold;">&#40;</span><span style="color:#006666;">5</span><span style="color:#006600; font-weight:bold;">&#41;</span> <span style="color:#008000; font-style:italic;">#=&gt; 6</span></pre></div></div>

<p>For extended example about currying, check <a href="http://www.khelll.com/blog/ruby/ruby-currying/">Ruby Currying</a> blog post by me <img src='http://khelll.com/blog/wp-includes/images/smilies/icon_wink.gif' alt=';)' class='wp-smiley' />  . </p>
<h2>Type systems and pattern matching</h2>
<p>Pattern matching allows complicated control decisions based on data structure to be expressed in a concise manner. in simpler words, it&#8217;s a data structure based matching. Pure functional languages should support this concept, however and afaik this is still not supported in Ruby, but there are several trials to add this concept. check this <a href="http://etorreborre.blogspot.com/2007/04/pattern-matching-with-ruby.html">blog post</a> by Eric Torreborre.</p>
<h2>Strict versus lazy evaluation</h2>
<p>Strict evaluation always fully evaluates function arguments before invoking the function. Lazy evaluation does not evaluate function arguments unless their values are required to be evaluated. One use of Lazy evaluation is the performance increases due to avoiding unnecessary calculations.</p>
<p>However as the following example shows, Ruby use Strict evaluation strategy:</p>

<div class="wp_syntax"><div class="code"><pre class="ruby" style="font-family:monospace;"><span style="color:#CC0066; font-weight:bold;">print</span> length<span style="color:#006600; font-weight:bold;">&#40;</span><span style="color:#006600; font-weight:bold;">&#91;</span><span style="color:#006666;">2</span><span style="color:#006600; font-weight:bold;">+</span><span style="color:#006666;">1</span>, <span style="color:#006666;">3</span><span style="color:#006600; font-weight:bold;">*</span><span style="color:#006666;">2</span>, <span style="color:#006666;">1</span><span style="color:#006600; font-weight:bold;">/</span><span style="color:#006666;">0</span>, <span style="color:#006666;">5</span><span style="color:#006600; font-weight:bold;">-</span><span style="color:#006666;">4</span><span style="color:#006600; font-weight:bold;">&#93;</span><span style="color:#006600; font-weight:bold;">&#41;</span>
<span style="color:#006600; font-weight:bold;">=&gt;</span>ZeroDivisionError: divided by <span style="color:#006666;">0</span></pre></div></div>

<p>The third parameter of the passed array contains a division by zero operation and as Ruby is doing strict evaluation, the above snippet of code will raise an exception.</p>
<h2>Recursion</h2>
<p>Iteration (looping) in functional languages is usually accomplished via recursion. Ruby doesn&#8217;t force you to recursion but it allows you to do so. However following recursion style has it&#8217;s own tax: Performance.<br />
Ruby 1.9 comes with some &#8220;tail call optimizations&#8221;, more <a href="http://www.reddit.com/r/ruby/comments/8lz33/ruby_19_has_tail_call_optimization">here</a>.</p>
<h2>Conclusion</h2>
<p>1- As you can tell, Ruby helps you write in functional style but it doesn&#8217;t force you to it.<br />
2- Writing in functional style enhances your code and makes it more self documented. Actually it will make it more thread-safe also.<br />
3- The main support for FB in ruby comes from the use of blocks and lambdas, also from the fact that everything is evaluated as an expression.<br />
4- Ruby still lack an important aspect of FP: Pattern Matching and Lazy Evaluation.<br />
5- There should be more work on tail recursion optimization, to encourage developers to use recursion.<br />
6- Any other thoughts?</p>
<div class="addthis_toolbox addthis_default_style addthis_32x32_style" addthis:url='http://khelll.com/blog/ruby/ruby-and-functional-programming/' addthis:title='Ruby and Functional Programming' ><a class="addthis_button_twitter"></a><a class="addthis_button_facebook"></a><a class="addthis_button_email"></a><a class="addthis_button_print"></a><a class="addthis_button_compact"></a></div>]]></content:encoded>
			<wfw:commentRss>http://khelll.com/blog/ruby/ruby-and-functional-programming/feed/</wfw:commentRss>
		<slash:comments>8</slash:comments>
		</item>
	</channel>
</rss>

