<?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>Kungfuice.com &#187; scala</title>
	<atom:link href="http://www.kungfuice.com/index.php/tag/scala/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.kungfuice.com</link>
	<description>The Ramblings Of A Programmer</description>
	<lastBuildDate>Mon, 27 Jul 2009 19:11:54 +0000</lastBuildDate>
	<generator>http://wordpress.org/?v=2.8.2</generator>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
			<item>
		<title>Reversing a String in Scala</title>
		<link>http://www.kungfuice.com/index.php/2009/02/08/reversing-a-string-in-scala/</link>
		<comments>http://www.kungfuice.com/index.php/2009/02/08/reversing-a-string-in-scala/#comments</comments>
		<pubDate>Sun, 08 Feb 2009 05:28:10 +0000</pubDate>
		<dc:creator>kungfuice</dc:creator>
				<category><![CDATA[Scala]]></category>
		<category><![CDATA[Technology]]></category>
		<category><![CDATA[programming]]></category>
		<category><![CDATA[Interview]]></category>
		<category><![CDATA[Recursion]]></category>
		<category><![CDATA[scala]]></category>

		<guid isPermaLink="false">http://www.kungfuice.com/?p=111</guid>
		<description><![CDATA[So I&#8217;ve been reading &#8220;Programming in Scala&#8221; by Martin Odersky, Lex Spoon and Bill Venners and I&#8217;ve been coming up with ways to get myself thinking and programming more in Scala.  Since I spent a better part of my week interviewing people I thought I&#8217;d take some time to write the famous &#8220;Reverse a String&#8221; [...]]]></description>
			<content:encoded><![CDATA[<p>So I&#8217;ve been reading &#8220;<a title="Artima - Programming in Scala" href="http://www.artima.com/shop/programming_in_scala">Programming in Scala</a>&#8221; by <a title="Martin Odersky" href="http://lamp.epfl.ch/~odersky/">Martin Odersky</a>, <a title="Lex Spoon" href="http://www.lexspoon.org/">Lex Spoon</a> and <a href="http://www.javacoffeebreak.com/articles/authorprofiles/venners_bill/index.html">Bill Venners</a> and I&#8217;ve been coming up with ways to get myself thinking and programming more in Scala.  Since I spent a better part of my week interviewing people I thought I&#8217;d take some time to write the famous &#8220;Reverse a String&#8221; interview question.  This is a pretty straight forward thing to do and thought it would be fun to experiment with some of Scala&#8217;s other cool features to get my feet wet.</p>
<p>On my first attempt I wound up with my usual tail-recursive implementation that makes use of an accumulator.</p>

<div class="wp_syntax"><div class="code"><pre class="java" style="font-family:monospace;"><span style="color: #008000; font-style: italic; font-weight: bold;">/**
 * Wrapper function.
 */</span>
def reverse<span style="color: #009900;">&#40;</span>str<span style="color: #339933;">:</span> <span style="color: #003399;">String</span><span style="color: #009900;">&#41;</span> <span style="color: #339933;">:</span> <span style="color: #003399;">String</span> <span style="color: #339933;">=</span> <span style="color: #009900;">&#123;</span>
      <span style="color: #000000; font-weight: bold;">if</span> <span style="color: #009900;">&#40;</span><span style="color: #009900;">&#40;</span>str <span style="color: #339933;">==</span> <span style="color: #000066; font-weight: bold;">null</span><span style="color: #009900;">&#41;</span> <span style="color: #339933;">||</span> <span style="color: #009900;">&#40;</span>str.<span style="color: #006633;">length</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #339933;">&amp;</span>lt<span style="color: #339933;">;=</span> <span style="color: #cc66cc;">1</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span>
          str
      reverse<span style="color: #009900;">&#40;</span>str, <span style="color: #0000ff;">&quot;&quot;</span><span style="color: #009900;">&#41;</span>
  <span style="color: #009900;">&#125;</span>
&nbsp;
 <span style="color: #008000; font-style: italic; font-weight: bold;">/**
   * tail call recursive with accumulator
   */</span>
  def reverse<span style="color: #009900;">&#40;</span>str<span style="color: #339933;">:</span> <span style="color: #003399;">String</span>, acc<span style="color: #339933;">:</span> <span style="color: #003399;">String</span><span style="color: #009900;">&#41;</span> <span style="color: #339933;">:</span> <span style="color: #003399;">String</span> <span style="color: #339933;">=</span> <span style="color: #009900;">&#123;</span>
      <span style="color: #000000; font-weight: bold;">if</span> <span style="color: #009900;">&#40;</span>str.<span style="color: #006633;">length</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #339933;">==</span> <span style="color: #cc66cc;">0</span><span style="color: #009900;">&#41;</span>
        acc
      <span style="color: #000000; font-weight: bold;">else</span>
        reverse<span style="color: #009900;">&#40;</span>str.<span style="color: #006633;">substring</span><span style="color: #009900;">&#40;</span><span style="color: #cc66cc;">1</span><span style="color: #009900;">&#41;</span>, str.<span style="color: #006633;">charAt</span><span style="color: #009900;">&#40;</span><span style="color: #cc66cc;">0</span><span style="color: #009900;">&#41;</span> <span style="color: #339933;">+</span> acc<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
  <span style="color: #009900;">&#125;</span></pre></div></div>

<p>This seemed pretty standard to me.  It doesn&#8217;t differ much from the Java implementation I&#8217;ve written a hundred times, nor is it really all that interesting.  I decided to jump ahead a few chapters in the book to see what I could accomplish using a left fold.  For those unfamiliar with what a fold left operation is I point you to the Wikipedia entry on it <a title="Fold (higher-order-functions) - Wikipedia" href="http://en.wikipedia.org/wiki/Fold_(higher-order_function)" target="_self">here</a>.  The basic idea as stated in the book &#8221;<a title="Artima - Programming in Scala" href="http://www.artima.com/shop/programming_in_scala">Programming in Scala</a>&#8220; is this: &#8220;A fold left operation (z /: xs) (op) involves three objects: a start value z, a list xs, and a binary operation op.  The result of the fold is op applied between successive elements of the list prefixed by z.&#8221;</p>
<p>Ok that seems like it applies very well to what we are trying to accomplish.  Rewritting the above methods into one clean line of Scala code yielded the following</p>

<div class="wp_syntax"><div class="code"><pre class="java" style="font-family:monospace;"><span style="color: #008000; font-style: italic; font-weight: bold;">/**
   * This will fold the list left, and should run in constant time allocation
   */</span>
  def reverseLeft<span style="color: #009900;">&#91;</span>T<span style="color: #009900;">&#93;</span><span style="color: #009900;">&#40;</span>xs<span style="color: #339933;">:</span> <span style="color: #003399;">List</span><span style="color: #009900;">&#91;</span>T<span style="color: #009900;">&#93;</span><span style="color: #009900;">&#41;</span> <span style="color: #339933;">=</span> <span style="color: #009900;">&#40;</span><span style="color: #003399;">List</span><span style="color: #009900;">&#91;</span>T<span style="color: #009900;">&#93;</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #339933;">/:</span> xs<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span><span style="color: #009900;">&#40;</span>ys, y<span style="color: #009900;">&#41;</span> <span style="color: #339933;">=&amp;</span>gt<span style="color: #339933;">;</span> y <span style="color: #339933;">::</span> ys<span style="color: #009900;">&#125;</span></pre></div></div>

<p>Pretty beautiful isn&#8217;t it?  It&#8217;s amazingly simple and achieves the same thing as the tail-recursive implementation.  I can&#8217;t express how excited I am to get through this book and really start doing real programming with Scala.</p>
<p>So I guess the next time you go for an interview try and remember this for the answer and see how the interviewers faces light up, either with glee or rage that you didn&#8217;t solve it using the standard recursive implementation <img src='http://www.kungfuice.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
<p>Until next time &#8230;</p>
]]></content:encoded>
			<wfw:commentRss>http://www.kungfuice.com/index.php/2009/02/08/reversing-a-string-in-scala/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Tail Recursive Algorithms In Scala</title>
		<link>http://www.kungfuice.com/index.php/2008/09/18/tail-recursive-algorithms-in-scala/</link>
		<comments>http://www.kungfuice.com/index.php/2008/09/18/tail-recursive-algorithms-in-scala/#comments</comments>
		<pubDate>Thu, 18 Sep 2008 16:56:38 +0000</pubDate>
		<dc:creator>kungfuice</dc:creator>
				<category><![CDATA[Computers]]></category>
		<category><![CDATA[java]]></category>
		<category><![CDATA[programming]]></category>
		<category><![CDATA[algorithms]]></category>
		<category><![CDATA[scala]]></category>

		<guid isPermaLink="false">http://www.kungfuice.com/?p=88</guid>
		<description><![CDATA[
&#60; ![endif]&#8211;&#62;After the NFJS conference this weekend I have been spending more and more time working in Scala and trying to learn the ins-and-outs of the language.  One of the neat things I came across was tail recursive algorithm optimization within the language itself.
When writing in a functional language like Scala you rely heavily on [...]]]></description>
			<content:encoded><![CDATA[<p><!--[if gte mso 10]></p>
<p><mce :style>< !   /* Style Definitions */  table.MsoNormalTable 	{mso-style-name:"Table Normal"; 	mso-tstyle-rowband-size:0; 	mso-tstyle-colband-size:0; 	mso-style-noshow:yes; 	mso-style-parent:""; 	mso-padding-alt:0in 5.4pt 0in 5.4pt; 	mso-para-margin:0in; 	mso-para-margin-bottom:.0001pt; 	mso-pagination:widow-orphan; 	font-size:10.0pt; 	font-family:"Times New Roman"; 	mso-ansi-language:#0400; 	mso-fareast-language:#0400; 	mso-bidi-language:#0400;} --></p>
<p>&lt; ![endif]&#8211;&gt;After the NFJS conference this weekend I have been spending more and more time working in Scala and trying to learn the ins-and-outs of the language.  One of the neat things I came across was tail recursive algorithm optimization within the language itself.</p>
<p>When writing in a functional language like Scala you rely heavily on recursive algorithms to do your work, instead of iterative algorithms more present in OO languages like Java. This leads to an interesting problem with running functional languages within the JVM.</p>
<p>The Java Virtual Machine does not have support for tail-recursive algorithm optimizations.  What does that mean? Basically the JVM cannot spot when to optimize calls stacks for recursive algorithms. Well who cares right?<span> </span>If you’re writing in Java this issue doesn’t usually come up since most of us simply write our loops and are happy with the performance the JVM offers us.</p>
<p>However, when you are writing a lot of recursive algorithms you quickly start to see how tail-recursive algorithms help makes your code more efficient.</p>
<p>For those of you who don&#8217;t remember what a tail-recursive algorithm is, here is a short little explanation:</p>
<p>&#8220;<em>A Tail-recursive function is a function that ends in a recursive call to itself (effectively not building up any deferred operations). Tail recursive functions have the ability to re-use the same stack frame over and over and therefore are not bound by the number of available stack frames.  Many people have written the simple factorial function recursively, but many have noticed that if you pass it a value of N that is large enough you will see a dreaded Out of Memory exception. </em></p>
<p><em>The reason for this is due to the factorial functions deferred operation statement that comes at the end of the method.<span> </span>Let’s look at the simple factorial algorithm</em></p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
</pre></td><td class="code"><pre class="java" style="font-family:monospace;"><span style="color: #666666; font-style: italic;">//INPUT: n is an Integer such that n &amp;gt;= 1</span>
<span style="color: #000066; font-weight: bold;">int</span> fact<span style="color: #009900;">&#40;</span><span style="color: #000066; font-weight: bold;">int</span> n<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>n <span style="color: #339933;">==</span> <span style="color: #cc66cc;">1</span><span style="color: #009900;">&#41;</span>
      <span style="color: #000000; font-weight: bold;">return</span> <span style="color: #cc66cc;">1</span><span style="color: #339933;">;</span>
   <span style="color: #000000; font-weight: bold;">else</span>
      <span style="color: #000000; font-weight: bold;">return</span> n<span style="color: #339933;">*</span> fact<span style="color: #009900;">&#40;</span>n<span style="color: #339933;">-</span><span style="color: #cc66cc;">1</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span></pre></td></tr></table></div>

<p><em><span> </span>H You can see that at then end of the algorithm we have a deferred operation of multiplying n with the next value computed from factorial, this goes on and on until we finally hit a factorial function that returns one, at which point the stack is popped and everything returns nicely. However we are now bound by the available stack frames in terms of computing n (Also by the max size of an int, but that’s beside the point).</em></p>
<p><em>In a tail-recursive algorithm you do not see this deferred execution, and therefore the same stack frame can be reused over and over again.<span> </span>Here is the same algorithm rewritten using a tail-recursive algorithm.</em></p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
</pre></td><td class="code"><pre class="java" style="font-family:monospace;"><span style="color: #666666; font-style: italic;">//INPUT: n is an Integer such that n &amp;gt;= 1</span>
<span style="color: #000066; font-weight: bold;">int</span> fact<span style="color: #009900;">&#40;</span><span style="color: #000066; font-weight: bold;">int</span> n<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
    <span style="color: #000000; font-weight: bold;">return</span> fact_support<span style="color: #009900;">&#40;</span>n, <span style="color: #cc66cc;">1</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span>
&nbsp;
<span style="color: #000066; font-weight: bold;">int</span> fact_support<span style="color: #009900;">&#40;</span><span style="color: #000066; font-weight: bold;">int</span> n, <span style="color: #000066; font-weight: bold;">int</span> acc<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>n <span style="color: #339933;">==</span> <span style="color: #cc66cc;">0</span><span style="color: #009900;">&#41;</span> <span style="color: #000000; font-weight: bold;">return</span> acc<span style="color: #339933;">;</span>
    <span style="color: #000000; font-weight: bold;">else</span> <span style="color: #000000; font-weight: bold;">return</span> fact_support<span style="color: #009900;">&#40;</span>n<span style="color: #339933;">-</span><span style="color: #cc66cc;">1</span>,acc<span style="color: #339933;">*</span>n<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span></pre></td></tr></table></div>

<p><em>As you can see there are no deferred operations in this example we have effectively gotten rid of having to use n number of stack frames.<span> </span>Each call to fact_support brings with it the current accumulated sum, and thus does not need to wait to “pop” the stack and rely on the stack pop to accumulate the sum of the factorials.</em></p>
<p class="MsoNormal">As you can see tail-recursive optimizations are very important to languages where recursion is relied on heavily.<span> </span>Without this type of optimization many of the recursive algorithms are now bound by the number of available stack frames.</p>
<p class="MsoNormal">
<p class="MsoNormal">So that can’t be so hard right? Why not just write all your algorithms to use tail-recursion? Well for one it’s not always possible to do this, but also it puts a lot of work in the hands of the developer.<span> </span>We have this beautiful thing called the JVM that should be able to spot cases where optimization can occur.</p>
<p class="MsoNormal">
<p class="MsoNormal">Unfortunately the JVM doesn’t know how to spot this optimization, therefore the Scala compiler must look at ways of optimizing your code.<span> </span>Even more unfortunate the Scala documentation explicitly states that you should not rely on the Scala compiler making this optimization.</p>
<p class="MsoNormal">
<p class="MsoNormal">It may optimize your code, but it may not as well, so really the only way to be sure is to write your algorithms guaranteeing that tail-recursion is being utilized from the get-go.</p>
<p class="MsoNormal">
<p class="MsoNormal">It would be really nice to see the JVM improved to allow for this type of optimization to be done in the Hotspot, and there has been talk about improving the JVM to support functional languages, but I guess time will only tell.</p>
<p></mce></p>
]]></content:encoded>
			<wfw:commentRss>http://www.kungfuice.com/index.php/2008/09/18/tail-recursive-algorithms-in-scala/feed/</wfw:commentRss>
		<slash:comments>6</slash:comments>
		</item>
	</channel>
</rss>
