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

<channel>
	<title>Sliding up the banister &#187; Scala</title>
	<atom:link href="http://joelneely.wordpress.com/category/functional-programming/scala/feed/" rel="self" type="application/rss+xml" />
	<link>http://joelneely.wordpress.com</link>
	<description>Sneaking up on functional programming</description>
	<lastBuildDate>Mon, 17 Sep 2012 10:54:28 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.com/</generator>
<cloud domain='joelneely.wordpress.com' port='80' path='/?rsscloud=notify' registerProcedure='' protocol='http-post' />
<image>
		<url>http://s2.wp.com/i/buttonw-com.png</url>
		<title>Sliding up the banister &#187; Scala</title>
		<link>http://joelneely.wordpress.com</link>
	</image>
	<atom:link rel="search" type="application/opensearchdescription+xml" href="http://joelneely.wordpress.com/osd.xml" title="Sliding up the banister" />
	<atom:link rel='hub' href='http://joelneely.wordpress.com/?pushpress=hub'/>
		<item>
		<title>Why Data Structures Matter</title>
		<link>http://joelneely.wordpress.com/2011/03/05/why-data-structures-matter/</link>
		<comments>http://joelneely.wordpress.com/2011/03/05/why-data-structures-matter/#comments</comments>
		<pubDate>Sat, 05 Mar 2011 23:06:17 +0000</pubDate>
		<dc:creator>joelneely</dc:creator>
				<category><![CDATA[Scala]]></category>
		<category><![CDATA[algorithms]]></category>
		<category><![CDATA[JVM]]></category>
		<category><![CDATA[JPR]]></category>

		<guid isPermaLink="false">http://joelneely.wordpress.com/?p=188</guid>
		<description><![CDATA[Our experience on Day 0 of JPR11 yielded a nice example of the need to choose an appropriate implementation of an abstract concept. As I mentioned in the previous post, we experimented with Michael Barker&#8217;s Scala implementation of Guy Steele&#8217;s parallelizable word-splitting algorithm (slides 51-67). Here&#8217;s the core of the issue. Given a type-compatible associative [&#8230;]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=joelneely.wordpress.com&#038;blog=2876257&#038;post=188&#038;subd=joelneely&#038;ref=&#038;feed=1" width="1" height="1" />]]></description>
				<content:encoded><![CDATA[<p>Our experience on <a href="http://joelneely.wordpress.com/2011/02/24/jpr-2011-day-0/">Day 0 of JPR11</a> yielded a nice example of the need to choose an appropriate implementation of an abstract concept. As I mentioned in the previous post, we experimented with <a href="https://github.com/mikeb01/jpr11-dojo/">Michael Barker&#8217;s Scala implementation</a> of Guy Steele&#8217;s <a href="http://strangeloop2010.com/talks/14299">parallelizable word-splitting algorithm</a> (slides 51-67). Here&#8217;s the core of the issue.</p>
<p>Given a type-compatible associative operator and sequence of values, we can fold the operator over the sequence to obtain a single accumulated value.  For example, because addition of integers is associative, addition can be folded over the sequence:</p>
<blockquote><p><code>1, 2, 3, 4, 5, 6, 7, 8</code></p></blockquote>
<p>from the left:</p>
<blockquote><p><code>((((((1 + 2) + 3) + 4) + 5) + 6) + 7) + 8</code></p></blockquote>
<p>or the right:</p>
<blockquote><p><code>1 + (2 + (3 + (4 + (5 + (6 + (7 + 8))))))</code></p></blockquote>
<p>or from the middle outward, by recursive/parallel splitting:</p>
<blockquote><p><code>((1 + 2) + (3 + 4)) + ((5 + 6) + (7 + 8))</code></p></blockquote>
<p>A 2-D view shows even more clearly the opportunity to evaluate sub-expressions in parallel. Assuming that addition is a constant-time operation, the left fold:</p>
<div style="text-align:center;"><img src="http://joelneely.files.wordpress.com/2011/03/foldleftplain.jpg?w=219&#038;h=325" alt="foldLeftPlain.jpg" border="0" width="219" height="325" /></div>
<p>and the right fold:</p>
<div style="text-align:center;"><img src="http://joelneely.files.wordpress.com/2011/03/foldrightplain.jpg?w=219&#038;h=325" alt="foldRightPlain.jpg" border="0" width="219" height="325" /></div>
<p>require linear time, but the balanced tree:</p>
<div style="text-align:center;"><img src="http://joelneely.files.wordpress.com/2011/03/foldtreeplain.jpg?w=312&#038;h=271" alt="foldTreePlain.jpg" border="0" width="312" height="271" /></div>
<p>can be done in logarithmic time.</p>
<p>But the associative operation for the word-splitting task involves accumulating lists of words. With a naive implementation of linked lists, appending is not a constant-time operation; it is linear on the length of the left operand. So for this operation the right fold is linear on the size of the task:</p>
<div style="text-align:center;"><img src="http://joelneely.files.wordpress.com/2011/03/foldrightlinear.jpg?w=219&#038;h=325" alt="foldRightLinear.jpg" border="0" width="219" height="325" /></div>
<p>the left fold is quadratic:</p>
<div style="text-align:center;"><img src="http://joelneely.files.wordpress.com/2011/03/foldleftlinear.jpg?w=585&#038;h=325" alt="foldLeftLinear.jpg" border="0" width="585" height="325" /></div>
<p>and the recursive/parallel version is linear:</p>
<div style="text-align:center;"><img src="http://joelneely.files.wordpress.com/2011/03/foldtreelinear.jpg?w=312&#038;h=271" alt="foldTreeLinear.jpg" border="0" width="312" height="271" /></div>
<p>Comparing just the &#8220;parallel-activity-versus-time&#8221; parts of those diagrams makes it clear that right fold is as fast as the parallel version, and also does less total work:</p>
<div style="text-align:center;"><img src="http://joelneely.files.wordpress.com/2011/03/comparelinear.jpg?w=585&#038;h=295" alt="compareLinear.jpg" border="0" width="585" height="295" /></div>
<p>Of course, there are other ways to implement the sequence-of-words concept, and that is the whole point. This little example provides a nice illustration of how parallel execution of the wrong implementation is not a win.</p>
<hr />
<p>The title of this post is a not-very-subtle (but respectful) reference to &#8220;<a href="http://www.cse.chalmers.se/~rjmh/Papers/whyfp.html">Why Functional Programming Matters</a>&#8220;, an excellent summary by <a href="http://en.wikipedia.org/wiki/John_Hughes_%28computer_scientist%29">John</a> <a href="http://www.infoq.com/interviews/john-hughes-fp">Hughes</a> that deserves to be <a href="http://weblog.raganwald.com/2007/03/why-why-functional-programming-matters.html">more widely read</a>.</p>
<p><a href="http://www.amazon.com/gp/product/0521663504?ie=UTF8&amp;tag=slidiuptheban-20&amp;linkCode=as2&amp;camp=1789&amp;creative=9325&amp;creativeASIN=0521663504">Purely Functional Data Structures</a><img src="http://www.assoc-amazon.com/e/ir?t=slidiuptheban-20&amp;l=as2&amp;o=1&amp;a=0521663504" width="1" height="1" border="0" alt="" style="border:none!important;margin:0!important;" />, by Chris Okasaki, covers a nice collection of algorithms that avoid the trap mentioned above.</p>
<div style="text-align:center;"><img src="http://joelneely.files.wordpress.com/2011/03/41xlpaczql-_sl160_.jpg?w=105&#038;h=160" alt="41XlPaC+ZqL._SL160_.jpg" border="0" width="105" height="160" /></div>
<p>Also, video from <a href="http://www.nescala.org/2011/">this year&#8217;s Northeast Scala Symposium</a> is now on-line for the session on <a href="http://vimeo.com/20262239">functional data structures in Scala</a>, presented by <a href="http://www.codecommit.com/blog/">Daniel Spiewak</a>.</p>
<br />Filed under: <a href='http://joelneely.wordpress.com/category/algorithms/'>algorithms</a>, <a href='http://joelneely.wordpress.com/category/jpr/'>JPR</a>, <a href='http://joelneely.wordpress.com/category/jvm/'>JVM</a>, <a href='http://joelneely.wordpress.com/category/functional-programming/scala/'>Scala</a>  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/joelneely.wordpress.com/188/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/joelneely.wordpress.com/188/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=joelneely.wordpress.com&#038;blog=2876257&#038;post=188&#038;subd=joelneely&#038;ref=&#038;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://joelneely.wordpress.com/2011/03/05/why-data-structures-matter/feed/</wfw:commentRss>
		<slash:comments>12</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/c3ae6a1b8d708b79b6b85ecc365266a4?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">joelneely</media:title>
		</media:content>

		<media:content url="http://joelneely.files.wordpress.com/2011/03/foldleftplain.jpg" medium="image">
			<media:title type="html">foldLeftPlain.jpg</media:title>
		</media:content>

		<media:content url="http://joelneely.files.wordpress.com/2011/03/foldrightplain.jpg" medium="image">
			<media:title type="html">foldRightPlain.jpg</media:title>
		</media:content>

		<media:content url="http://joelneely.files.wordpress.com/2011/03/foldtreeplain.jpg" medium="image">
			<media:title type="html">foldTreePlain.jpg</media:title>
		</media:content>

		<media:content url="http://joelneely.files.wordpress.com/2011/03/foldrightlinear.jpg" medium="image">
			<media:title type="html">foldRightLinear.jpg</media:title>
		</media:content>

		<media:content url="http://joelneely.files.wordpress.com/2011/03/foldleftlinear.jpg" medium="image">
			<media:title type="html">foldLeftLinear.jpg</media:title>
		</media:content>

		<media:content url="http://joelneely.files.wordpress.com/2011/03/foldtreelinear.jpg" medium="image">
			<media:title type="html">foldTreeLinear.jpg</media:title>
		</media:content>

		<media:content url="http://joelneely.files.wordpress.com/2011/03/comparelinear.jpg" medium="image">
			<media:title type="html">compareLinear.jpg</media:title>
		</media:content>

		<media:content url="http://www.assoc-amazon.com/e/ir?t=slidiuptheban-20&#38;l=as2&#38;o=1&#38;a=0521663504" medium="image" />

		<media:content url="http://joelneely.files.wordpress.com/2011/03/41xlpaczql-_sl160_.jpg" medium="image">
			<media:title type="html">41XlPaC+ZqL._SL160_.jpg</media:title>
		</media:content>
	</item>
		<item>
		<title>Scala and Programming 2.0</title>
		<link>http://joelneely.wordpress.com/2008/05/16/scala-and-programming-20/</link>
		<comments>http://joelneely.wordpress.com/2008/05/16/scala-and-programming-20/#comments</comments>
		<pubDate>Fri, 16 May 2008 17:17:55 +0000</pubDate>
		<dc:creator>joelneely</dc:creator>
				<category><![CDATA[education]]></category>
		<category><![CDATA[programming languages]]></category>
		<category><![CDATA[Scala]]></category>

		<guid isPermaLink="false">http://joelneely.wordpress.com/?p=44</guid>
		<description><![CDATA[I commented elsewhere on how the &#8220;Architecture of Participation&#8221; idea may be percolating into the field of programming languages. I am especially interested in seeing whether the adoption of Scala provides evidence of this phenomenon. Scala is a strongly, statically typed language implemented on the JVM&#8212;all characteristics that raise eyebrows (if not noses) in some [&#8230;]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=joelneely.wordpress.com&#038;blog=2876257&#038;post=44&#038;subd=joelneely&#038;ref=&#038;feed=1" width="1" height="1" />]]></description>
				<content:encoded><![CDATA[<p>I <a href="http://dobbscodetalk.com/index.php?option=com_myblog&amp;task=view&amp;id=434&amp;Itemid=85">commented elsewhere</a> on how the &#8220;<a href="http://www.oreillynet.com/pub/a/oreilly/tim/articles/architecture_of_participation.html">Architecture of Participation</a>&#8221; idea may be percolating into the field of programming languages. I am especially interested in seeing whether the adoption of <a href="http://www.scala-lang.org/">Scala</a> provides evidence of this phenomenon.</p>
<p>Scala is a strongly, statically typed language implemented on the JVM&mdash;all characteristics that raise eyebrows (if not noses) in some circles. However, Scala&#8217;s ultralight approach to syntax is very much in line with the current taste for highly flexible notation and internal DSLs as a tool of expression.</p>
<p>Type inference is a very attractive compiler feature. And it&#8217;s great to get performance improvements &#8220;for free&#8221; every time the JVM team makes <a href="http://java.sun.com/javase/technologies/hotspot/">HotSpot</a> smarter about JIT compilation, method in-lining, etc. But every time I revisit the ideas in <a href="http://www.parleys.com/display/PARLEYS/Scala?showComments=true">Martin Odersky&#8217;s Scala talk at Javapolis 2007</a>, I&#8217;m impressed with the design of Scala as a notation that invites participation.</p>
<p>Time will tell.</p>
<br /><img alt="" border="0" src="http://feeds.wordpress.com/1.0/categories/joelneely.wordpress.com/44/" /> <img alt="" border="0" src="http://feeds.wordpress.com/1.0/tags/joelneely.wordpress.com/44/" /> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/joelneely.wordpress.com/44/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/joelneely.wordpress.com/44/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=joelneely.wordpress.com&#038;blog=2876257&#038;post=44&#038;subd=joelneely&#038;ref=&#038;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://joelneely.wordpress.com/2008/05/16/scala-and-programming-20/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/c3ae6a1b8d708b79b6b85ecc365266a4?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">joelneely</media:title>
		</media:content>
	</item>
		<item>
		<title>Project Euler 5: Multiplicity</title>
		<link>http://joelneely.wordpress.com/2008/04/26/project-euler-5-multiplicity/</link>
		<comments>http://joelneely.wordpress.com/2008/04/26/project-euler-5-multiplicity/#comments</comments>
		<pubDate>Sun, 27 Apr 2008 01:48:31 +0000</pubDate>
		<dc:creator>joelneely</dc:creator>
				<category><![CDATA[functional programming]]></category>
		<category><![CDATA[Project Euler]]></category>
		<category><![CDATA[Scala]]></category>

		<guid isPermaLink="false">http://joelneely.wordpress.com/?p=41</guid>
		<description><![CDATA[The fifth problem from Project Euler asks for &#8220;the smallest number that is evenly divisible by all of the numbers from 1 to 20&#8243;. The key, for me, was to paraphrase that as &#8220;the least common multiple of 1 to 20&#8243;. The least common multiple (lcm) of two natural numbers is their product divided by [&#8230;]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=joelneely.wordpress.com&#038;blog=2876257&#038;post=41&#038;subd=joelneely&#038;ref=&#038;feed=1" width="1" height="1" />]]></description>
				<content:encoded><![CDATA[<p>The <a href="http://projecteuler.net/index.php?section=problems&amp;id=5">fifth problem</a> from <a href="http://projecteuler.net/">Project Euler</a> asks for &#8220;the smallest number that is evenly divisible by all of the numbers from 1 to 20&#8243;. The key, for me, was to paraphrase that as &#8220;the least common multiple of 1 to 20&#8243;.</p>
<p>The least common multiple (<i>lcm</i>) of two natural numbers is their product divided by their greatest common divisor (<i>gcd</i>, a well-known lab rat). So, the stock definitions of <i>lcm</i> and <i>gcd</i>, along with one quick fold, are all we need.</p>
<pre>
  def divisibleByAll(lo: Int, hi: Int) = {
    def gcd(a: Int, b: Int) = gcd1(a max b, a min b)
    def gcd1(a: Int, b: Int): Int = if (b == 0) a else gcd(b, a % b)
    def lcm(a: Int, b: Int) = a * (b / gcd(a, b))
    (lo to hi).foldLeft(1)(lcm(_, _))
  }
</pre>
<p>There is one subtlety in this code; <code>gcd</code> is only there to insure that the (natural) arguments to <code>gcd1</code> are correctly ordered (larger first). That is only needed once; if <code>a &gt;= b</code>, then <code>a % b</code> <i>cannot</i> be larger than <code>b</code>, so the recursion in <code>gcd1</code> is guaranteed to maintain the larger-first argument ordering.</p>
<p>Finally, this design encounters integer overflow at 1..24, changing the inner functions to work with <code>Long</code> gets us up to 1..42 before long overflow kicks in.</p>
<p>It should be obvious that the answers for 1..21 and 1..22 are the same as for 1..20, but I had to do a double-take while scanning for the limits. Duh.</p>
<br /><img alt="" border="0" src="http://feeds.wordpress.com/1.0/categories/joelneely.wordpress.com/41/" /> <img alt="" border="0" src="http://feeds.wordpress.com/1.0/tags/joelneely.wordpress.com/41/" /> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/joelneely.wordpress.com/41/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/joelneely.wordpress.com/41/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=joelneely.wordpress.com&#038;blog=2876257&#038;post=41&#038;subd=joelneely&#038;ref=&#038;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://joelneely.wordpress.com/2008/04/26/project-euler-5-multiplicity/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/c3ae6a1b8d708b79b6b85ecc365266a4?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">joelneely</media:title>
		</media:content>
	</item>
		<item>
		<title>Three X eerhT</title>
		<link>http://joelneely.wordpress.com/2008/04/26/three-x-eerht/</link>
		<comments>http://joelneely.wordpress.com/2008/04/26/three-x-eerht/#comments</comments>
		<pubDate>Sat, 26 Apr 2008 20:40:49 +0000</pubDate>
		<dc:creator>joelneely</dc:creator>
				<category><![CDATA[functional programming]]></category>
		<category><![CDATA[Project Euler]]></category>
		<category><![CDATA[Scala]]></category>

		<guid isPermaLink="false">http://joelneely.wordpress.com/?p=40</guid>
		<description><![CDATA[The fourth task from Project Euler is to find the largest palindrome that is a product of two three-digit numbers. (I&#8217;m assuming decimal. ) Name no one man The first sub-task is to determine whether the decimal representation of an integer is palindromic. A direct approach yields this: def reverseInt(n: Int) = { def rev(a: [&#8230;]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=joelneely.wordpress.com&#038;blog=2876257&#038;post=40&#038;subd=joelneely&#038;ref=&#038;feed=1" width="1" height="1" />]]></description>
				<content:encoded><![CDATA[<p>The <a href="http://projecteuler.net/index.php?section=problems&amp;id=4">fourth task</a> from <a href="http://projecteuler.net/">Project Euler</a> is to find the largest <a href="http://en.wikipedia.org/wiki/Palindromic_number">palindrome</a> that is a product of two three-digit numbers. (I&#8217;m assuming decimal. <img src='http://s1.wp.com/wp-includes/images/smilies/icon_wink.gif' alt=';-)' class='wp-smiley' />  )</p>
<h4>Name no one man</h4>
<p>The first sub-task is to determine whether the decimal representation of an integer is palindromic. A direct approach yields this:</p>
<pre>
  def reverseInt(n: Int) = {
    def rev(a: Int, b: Int): Int =
      if (a == 0)
        b
      else
        rev(a / 10, b * 10 + a % 10)
    rev(n, 0)
  }
</pre>
<pre>
  def isPalindrome(n: Int) = {
    reverseInt(n) == n
  }
</pre>
<p>I&#8217;m not approaching this by way of string conversion, for three reasons:</p>
<ul>
<li>Nothing in the problem statement involves strings;</li>
<li>Expressing the solution in terms of string manipulation doesn&#8217;t make the solution significantly easier to understand; and</li>
<li>Doing so would be slower.</li>
</ul>
<p>Now on to the more interesting part.</p>
<h4>Seek no monkees</h4>
<p>The problem can be solved by searching a two-dimensional space, where each dimension ranges over the three-digit integers. A moment&#8217;s thought provides the following additional facts we can use:</p>
<ul>
<li>Multiplication is symmetric, so there&#8217;s no need to examine both products of two different numbers (<code>a * b</code> and <code>b * a</code>).</li>
<li>The Scala expression <code>100 to 999</code> provides the three-digit integers.</li>
<li>We can ignore 100 as a candidate, because any multiple of 100 must end in a zero, which isn&#8217;t the first digit of any multi-digit decimal number in standard notation.</li>
<li>There&#8217;s a solution, because 101 &times; 101 = 10201, which is palindromic. (It&#8217;s nice to know that the search function doesn&#8217;t need to deal with an empty solution space.)</li>
</ul>
<p>Going for the obvious, we can construct the products of non-redundant pairs of three-digit numbers, filter the products for palindromes, and capture the maximum of the palindromes:</p>
<pre>
  def maxOfPalindromes() = {
    (
      for {
        a &lt;- 101 to 999
        b  a max b)
  }
</pre>
<p>It would be easy to parameterize this for the range to be searched (either by bounds or by number of digits), but I want to focus on the search performance.</p>
<h4>Top spot</h4>
<p>The version above takes about 152 ms on my laptop, which seems entirely too much time for this small a task. The following diagram shows the search space, as a context for the rest of the post.</p>
<div style="text-align:center;"><img src="http://joelneely.files.wordpress.com/2008/04/search2d.jpg?w=192&#038;h=192" alt="search2d.jpg" border="0" width="192" height="192" /></div>
<p>The names in the diagram describe the state of the search at a given instant:</p>
<ul>
<li><code>lo</code> and <code>hi</code> &mdash; the lower and upper bounds (inclusive) of the range being searched;</li>
<li><code>a</code> and <code>b</code> &mdash; the current position in the search space;</li>
<li><code>c</code> &mdash; the value at that position (the product of <code>a</code> and <code>b</code>); and</li>
<li><code>x</code> &mdash; the largest palindrome found thus far. </li>
</ul>
<p>In his landmark book, <i>A Discipline of Programming</i> (published 32 years ago!), <a href="http://www.cs.utexas.edu/users/EWD/">Edsger Dijkstra</a> stated the &#8220;Linear Search Theorem&#8221;. I&#8217;ll paraphrase it informally for our purposes as:</p>
<blockquote><p>
When searching for the maximum value having some property, examine the values in decreasing order; the first satisfactory value found will be the maximum.
</p></blockquote>
<p>Assuming that we apply this to both <code>a</code> and <code>b</code>, the green area has been examined and the blue area has not. We can express the next state of the search in a decision table (each row&#8217;s condition assumes that conditions on all previous rows failed):</p>
<table align="center" border="1" cellspacing="0" cellpadding="2">
<tr>
<th rowspan="2">Condition</th>
<th rowspan="2">Action</th>
<th colspan="4">State changes</th>
</tr>
<tr align="center">
<td>next <code>a</code></td>
<td>next <code>b</code></td>
<td>next <code>x</code></td>
</tr>
<tr align="center">
<td><code>a &lt; lo</code></td>
<td>Search complete<br /><code>x</code> is the result</td>
<td colspan="3"><i>n/a</i></td>
</tr>
<tr align="center">
<td><code>b &lt; a</code></td>
<td>Current row searched,<br />move to next blue row</td>
<td><code>a - 1</code></td>
<td><code>hi</code></td>
<td><code>x</code></td>
</tr>
<tr align="center">
<td><code>c &lt;= x</code></td>
<td><code>c</code> and rest of this row eliminated,<br />move to next blue row</td>
<td><code>a - 1</code></td>
<td><code>hi</code></td>
<td><code>x</code></td>
</tr>
<tr align="center">
<td><code>isPalindrome(c)</code></td>
<td><code>c</code> is new max palindrome<br />(rest of this row is smaller values)</td>
<td><code>a - 1</code></td>
<td><code>hi</code></td>
<td><code>c</code></td>
</tr>
<tr align="center">
<td><i>otherwise</i></td>
<td><code>c</code> eliminated,<br />continue searching current row</td>
<td><code>a</code></td>
<td><code>b - 1</code></td>
<td><code>x</code></td>
</tr>
</table>
<p>The decision table translates directly to a tail-recursive function. I&#8217;ll use a bit of scope management to avoid computing <code>c</code> unless it will be used.</p>
<pre>
  def maxPalindromeIn(lo: Int, hi: Int) = {
    def loop(a: Int, b: Int, x: Int): Int = {
      if (a &lt; lo)
        x
      else if (b &lt; a)
        loop(a - 1, hi, x)
      else {
        val c = a * b
        if (c &lt;= x)
          loop(a - 1, hi, x)
        else if (isPalindrome(c))
          loop(a - 1, hi, c)
        else
          loop(a , b - 1, x)
      }
    }
    loop(hi, hi, 0)
  }
</pre>
<pre>
  def maxPalindrome3x3() = maxPalindromeIn(101, 999)
</pre>
<p>This runs in about 445&micro;s, a speedup factor of well over 300.</p>
<h4>I prefer &pi;</h4>
<p>Let me round this post off with a few observations.</p>
<p><i>Performance is not the most important issue.</i> I probably need to state that clearly, having quoted run time so often in this and recent Project Euler posts. I believe that speed, small memory footprint, and any other measure of economy, should be subordinate and subsequent to good design and correctness.</p>
<p><i>Those who forget history are condemned to repeat it.</i> Over twenty years ago, when the dreaded &#8220;G&#8221; word was still occasionally heard in polite programming circles, a misguided letter to the editor of the <a href="http://www.acm.org/publications/cacm/"><i>Communications of the ACM</i></a> attempted to claim that <code>goto</code> was necessary to effective programming and offered a small problem in defense of that claim. <a href="http://www.cs.utexas.edu/users/EWD/transcriptions/EWD10xx/EWD1009.html">Dijkstra&#8217;s response</a> addressed the errors and approach of the claim and its &#8220;solution&#8221;; his demonstration used the idea of the two-dimensional application of the Linear Search theorem.</p>
<p><i>There are important ideas that transcend programming model.</i> The ideas in <i>A Discipline of Programming</i> are all presented in an imperative style, yet the clarity of design makes the concepts important to FP as well. That book is not an easy read (I <i>worked</i> rather than <i>read</i> through it when I got my copy in 1976) but it rewards the investment richly. <a href="http://www.cs.cornell.edu/gries/gries.html">David Gries</a> gave a tutorial-style presentation of many of the same core ideas in <i>The Science of Programming</i>. I cannot possibly recommend them highly enough.</p>
<p><i>Compare and contrast.</i> It&#8217;s useful to see how others approach a problem, after you&#8217;ve solved it yourself.</p>
<ul>
<li>The <a href="http://www.haskell.org/">Haskell web site</a> has <a href="http://www.haskell.org/haskellwiki/Project_euler">Haskell solutions to the Project Euler problems</a>; another site offers <a href="http://pyeuler.wikidot.com/">Python-based solutions of the first several</a>. However, these sites have very little explanation of the solution or design strategy (my focus).</li>
<li>You can <a href="http://projecteuler.net/index.php?section=register">register at Project Euler</a> to track your own progress, and read the comments posted by others when you&#8217;ve completed a problem. (Comments are closed for the earlier problems.)</li>
<li><a href="http://basildoncoder.com/blog/">Russ Gray (Basildon Coder)</a> is working through the problems in a variety of languages and posting on his experiences. His discussion of the first problem is what tipped me over the edge into this series.</li>
<li><a href="http://srtsolutions.com/blogs/diannemarsh/archive/tags/euler/default.aspx">Dianne Marsh</a> (a friend from Java Posse Roundup) is also doing Project Euler problems in Scala. Apparently she&#8217;s roped in collegues from <a href="http://srtsolutions.com/">SRT</a>: <a href="http://srtsolutions.com/blogs/billwagner/archive/tags/Euler/default.aspx">Bill Wagner</a> in C#, <a href="http://srtsolutions.com/blogs/darrellhawley/archive/tags/euler/default.aspx">Darrell Hawley</a> in Python, <a href="http://srtsolutions.com/blogs/marinafedner/archive/tags/euler/default.aspx">Marina Fedner</a> in Ruby, and <a href="http://srtsolutions.com/blogs/annemarsan/archive/tags/Euler+problems/default.aspx">Anne Marsan</a> in Matlab.
</li>
<li>I&#8217;m also aware of <a href="http://blogs.msdn.com/chrsmith/archive/tags/Project+Euler/default.aspx">a partial set of solutions in F# by Chris Smith</a></li>
</ul>
<p>My RSS reader is subscribed to the fellow solvers above; many of them have other interesting things to say beyond Project Euler!</p>
<hr />
<p>Recommended reading:</p>
<ul>
<li><a href="http://www.amazon.com/gp/product/013215871X?ie=UTF8&amp;tag=slidiuptheban-20&amp;linkCode=as2&amp;camp=1789&amp;creative=9325&amp;creativeASIN=013215871X">A Discipline of Programming (Prentice-Hall Series in Automatic Computation)</a><img src="http://www.assoc-amazon.com/e/ir?t=slidiuptheban-20&amp;l=as2&amp;o=1&amp;a=013215871X" width="1" height="1" border="0" alt="" style="border:none !important;margin:0 !important;" /></li>
<li><a href="http://www.amazon.com/gp/product/0387964800?ie=UTF8&amp;tag=slidiuptheban-20&amp;linkCode=as2&amp;camp=1789&amp;creative=9325&amp;creativeASIN=0387964800">The Science of Programming (Monographs in Computer Science)</a><img src="http://www.assoc-amazon.com/e/ir?t=slidiuptheban-20&amp;l=as2&amp;o=1&amp;a=0387964800" width="1" height="1" border="0" alt="" style="border:none !important;margin:0 !important;" /></li>
</ul>
<br /><img alt="" border="0" src="http://feeds.wordpress.com/1.0/categories/joelneely.wordpress.com/40/" /> <img alt="" border="0" src="http://feeds.wordpress.com/1.0/tags/joelneely.wordpress.com/40/" /> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/joelneely.wordpress.com/40/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/joelneely.wordpress.com/40/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=joelneely.wordpress.com&#038;blog=2876257&#038;post=40&#038;subd=joelneely&#038;ref=&#038;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://joelneely.wordpress.com/2008/04/26/three-x-eerht/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/c3ae6a1b8d708b79b6b85ecc365266a4?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">joelneely</media:title>
		</media:content>

		<media:content url="http://joelneely.files.wordpress.com/2008/04/search2d.jpg" medium="image">
			<media:title type="html">search2d.jpg</media:title>
		</media:content>

		<media:content url="http://www.assoc-amazon.com/e/ir?t=slidiuptheban-20&#38;l=as2&#38;o=1&#38;a=013215871X" medium="image" />

		<media:content url="http://www.assoc-amazon.com/e/ir?t=slidiuptheban-20&#38;l=as2&#38;o=1&#38;a=0387964800" medium="image" />
	</item>
		<item>
		<title>A composite function</title>
		<link>http://joelneely.wordpress.com/2008/04/24/a-composite-function/</link>
		<comments>http://joelneely.wordpress.com/2008/04/24/a-composite-function/#comments</comments>
		<pubDate>Thu, 24 Apr 2008 13:18:38 +0000</pubDate>
		<dc:creator>joelneely</dc:creator>
				<category><![CDATA[functional programming]]></category>
		<category><![CDATA[Mathematics]]></category>
		<category><![CDATA[Project Euler]]></category>
		<category><![CDATA[Scala]]></category>

		<guid isPermaLink="false">http://joelneely.wordpress.com/?p=38</guid>
		<description><![CDATA[The previous post began working with problem 3 from Project Euler. The allFactors function produced a list of the prime factors of its argument (all occurrences of all prime factors), such as: scala&#62; val nums = allFactors(96000) nums: List[Long] = List(5, 5, 5, 3, 2, 2, 2, 2, 2, 2, 2, 2) It would be [&#8230;]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=joelneely.wordpress.com&#038;blog=2876257&#038;post=38&#038;subd=joelneely&#038;ref=&#038;feed=1" width="1" height="1" />]]></description>
				<content:encoded><![CDATA[<p>The <a href="http://joelneely.wordpress.com/2008/04/19/prime-time-programming/">previous post</a> began working with <a href="http://projecteuler.net/index.php?section=problems&amp;id=3">problem 3</a> from <a href="http://projecteuler.net/">Project Euler</a>. The <code>allFactors</code> function produced a list of the prime factors of its argument (all occurrences of all prime factors), such as:</p>
<pre>
  scala&gt; val nums = allFactors(96000)
  nums: List[Long] = List(5, 5, 5, 3, 2, 2, 2, 2, 2, 2, 2, 2)
</pre>
<p>It would be nice to have a representation that&#8217;s a bit closer to the conventional <i>5<sup>3</sup> &times; 3<sup>1</sup> &times; 2<sup>8</sup></i>, which makes clear the exponent for each prime factor.</p>
<p>In thinking about solutions to that issue, we get a prime use case for Scala&#8217;s composite nature as a hybrid OO/FP language. In addition, we encounter another heuristic for avoiding errors (functional or otherwise).</p>
<h4>A separate piece</h4>
<p>One easy solution is to write a separate function that collapses a list of values into a list of value&ndash;count pairs, for which we can define a <i>type alias</i> as:</p>
<pre>
  type PrimePower = (Long, Int)
</pre>
<p>The <code>partition</code> method on <code>List</code> is perfect for our current need; given a condition (represented as a boolean-valued function), it splits the list into the prefix that satisfies the condition and the remainder.</p>
<pre>
  scala&gt; nums.partition(_ == 5)
  res82: (List[Long], List[Long]) = (List(5, 5, 5),List(3, 2, 2, 2, 2, 2, 2, 2, 2))
</pre>
<p>Of course, the length of the prefix <b>is</b> the exponent, so the function almost writes itself:</p>
<pre>
  def groupCount(fs: List[Long]): List[PrimePower] = fs match {
    case Nil =&gt; Nil
    case p :: _ =&gt;
      val (ps, rest) = fs.partition(_ == p)
      (p, ps.length) :: groupCount(rest)
  }
</pre>
<p>If factor list is empty, the result is an empty list. On the other hand, if <code>fs</code> begins with some prime <code>p</code>, we split the prefix containing all <code>ps</code> from the <code>rest</code> of the list, and return a list containing the <code>PrimePower</code> for <code>p</code> consed onto the <code>groupCount</code>ed <code>rest</code> of the original list.</p>
<pre>
  scala&gt; groupCount(nums)              
  res86: List[()] = List((5,3), (3,1), (2,8))
</pre>
<p>The advantages of writing this as a separate function are ease of testing and availability for re-use. On the other hand, it would be interesting to see the consequences of directly producing the prime powers.</p>
<h4>One list to bind them</h4>
<p>For reference, here&#8217;s the function from last time, with the inner alternatives labeled for reference and highlighting on the parts we need to consider:</p>
<pre>
  def allFactors(t: Long) = {
    def loop(q: Long, fs: List[<b><u>Long</u></b>], d: Long): List[<b><u>Long</u></b>] =
      if (q == 1)
        fs                        // case 1
      else if (q &lt; d * d)
        <b><u>q</u></b> :: fs                   // case 2
      else if (q % d == 0)
        loop(<b><u>q / d</b></u>, <b><u>d</b></u> :: fs, d)  // case 3
      else
        loop(q, fs, d + 1)        // case 4
    loop(t, Nil, 2)
  }
</pre>
<p>The result will be <code>List[PrimePower]</code>, which is the new type of the second argument and result of <code>loop</code>.</p>
<p>Case 2 deals with a quotient which we know to be prime, because all possible divisors have been exhausted. Given that <code>q</code> occurs exactly once, we replace <code>q :: fs</code> with <code>(q, 1) :: fs</code> as the result.</p>
<p>Case 3 requires the most thought. It only accounts for a single occurrence of a divisor; <code>q / d</code> removes one factor of <code>d</code> from <code>q</code> and <code>d :: fs</code> saves that occurrence in the list being accumulated.</p>
<h4>Help me, Rhonda!</h4>
<p>We could use a helper function to handle <code>d</code>, based on whether it is another occurrence of the previous divisor or a new divisor not previously seen. Because that distinction is based on data in the list, it seems natural to drive the logic by matching on the list:</p>
<pre>
  def countFactor(f: Long, fs: List[PrimePower]) = fs match {
    case (d, c) :: rest if f == d =&gt; (d, c + 1) :: rest
    case _                        =&gt; (f, 1) :: fs
  }
</pre>
<p>To test <code>countFactor</code>, we need to iterate it over a sequence of values for <code>f</code> with <code>fs</code> initially <code>Nil</code>. This looks like a job for a fold!</p>
<pre>
  def testCountFactor(ls: List[Long]) =
    ls.foldRight(Nil: List[PrimePower])(countFactor(_, _))
</pre>
<p>In the interest of space, I won&#8217;t include all the test scenarios: <code>Nil</code>, a list of length 1, all values equal, all values different, etc. As the old saying goes, checking those is &#8220;left as an exercise for the reader&#8221;.</p>
<h4>True confessions</h4>
<p>Substituting a call to <code>countFactor</code> into case 3, along with the other changes already discussed, gives us this&#8230;</p>
<pre>
  def allFactorsCounted(t: Long) = {
    def loop(q: Long, fs: List[PrimePower], d: Long): List[PrimePower] =
      if (q == 1)
        fs                                    // case 1
      else if (q &lt; d * d)
        (q, 1) :: fs                          // case 2
      else if (q % d == 0)
        loop(q / d, countFactor(d, fs), d)    // case 3
      else
        loop(q, fs, d + 1)                    // case 4
    loop(t, Nil, 2)
  }
</pre>
<p>&#8230;which behaves as follows&#8230;</p>
<pre>
  scala&gt; val nums2 = allFactorsCounted(96000)                                            
  nums2: List[()] = List((5,1), (5,2), (3,1), (2,8))
</pre>
<p>&#8230;or, I should say, &#8220;<b>mis</b>behaves as follows&#8221;! What went wrong? </p>
<p>The root cause of this error is the special-case code in case 2, which is doing two things at once: handling a prime factor (in its own way!) and terminating the recursion. Put another way, the design breaks the symmetry between cases 2 and 3, both of which identify a prime factor and do something with it. We can make that symmetry more obvious by rewriting case 2 as in the following:</p>
<pre>
  def allFactorsCounted(t: Long) = {
    def loop(q: Long, fs: List[PrimePower], d: Long): List[PrimePower] =
      if (q == 1)
        fs
      else if (q &lt; d * d)
        <b><u>loop(1,   countFactor(q, fs), d)</u></b>
      else if (q % d == 0)
        loop(q / d, countFactor(d, fs), d)
      else
        loop(q, fs, d + 1)
    loop(t, Nil, 2)
  }
</pre>
<p>And <b>now</b> each case in the inner loop has exactly one responsibility:</p>
<ol>
<li>Terminates the computation because all factors have been found;</li>
<li>Removes <code>q</code> as a known factor;</li>
<li>Removes <code>d</code> as a known factor;</li>
<li>Moves past an unsuccessful divisor.</li>
</ol>
<p>Mixing concerns in a single part of the code creates these risks:</p>
<ul>
<li>The code can become harder to understand;</li>
<li>Symmetries can be hidden or broken;</li>
<li>Change driven by (only) one concern can have unintended consequences.</li>
</ul>
<p>For me, the moral of this error is this:</p>
<blockquote><p><i>Each part of the code (especially alternatives within a single function) should &#8220;Do one thing, and do it well!&#8221;</i></p></blockquote>
<h4>An object lesson</h4>
<p>In the OO world, <a href="http://jamesshore.com/Blog/PrimitiveObsession.html">primitive</a> <a href="http://grabbagoft.blogspot.com/2007/12/dealing-with-primitive-obsession.html">obsession</a> is regarded as a <a href="http://www.codinghorror.com/blog/archives/000589.html">code smell</a>. Notice that <code>q</code> and <code>fs</code> together represent the current state of our factorization; we have the <a href="http://en.wikipedia.org/wiki/Loop_invariant">invariant</a> that <code>q</code> times the product of <code>fs</code> equals the original number to be factored! Failing to maintain that invariant would likely break the code. The clue to watch for is that the (tail-)recursive calls of the inner <code>loop</code> function either alter <b>both</b> of those parameters or <b>neither</b> of them. This is telling us that they are related aspects of a single concept.</p>
<p>OO gives us a technique for managing related data: put them in an object as private fields, expose the minimum methods required by the object&#8217;s client, and ensure that those methods maintain the invariants. We can <a href="http://www.refactoring.com/catalog/replaceDataValueWithObject.html">refactor</a> the quotient and factor list into the following class:</p>
<pre>
  class Factorization(val n: Long, val fs: List[PrimePower]) {
    def isComplete = n == 1
    def move(d: Long): Factorization = {
      def remove(i: Int, q: Long, d: Long): Factorization =
        if (q % d == 0)
          remove(i + 1, q / d, d)
        else
          new Factorization(q, (d, i) :: fs)
      if (n % d == 0)
        remove(0, n, d)
      else
        this
    }
  }
</pre>
<p>Each instance of <code>Factorization</code> represents some stage of the factorization of a number by <code>n</code> (the non-factored part) and <code>fs</code> (the factors previously found). An instance can tell whether it is a complete factorization (all factors have been extracted). Finally, an instance can return a <code>Factorization</code> resulting from <code>move</code>-ing all occurrences of a given divisor from the non-factored part to the factor list.</p>
<p>Notice that a <code>Factorization</code> is immutable; the result of a <code>move</code> will be the same instance if the divisor isn&#8217;t a factor, or a <b>new</b> instance resulting from the extraction of that divisor.</p>
<p>With this class defined, our factorization function is even more conceptually streamlined:</p>
<pre>
  def factorize(n: Long): List[PrimePower] = {
    def loop(f: Factorization, d: Long): Factorization = {
      if (f.isComplete)
        f
      else if (f.n &lt; d * d)
        loop(f.move(f.n), d)
      else
        loop(f.move(d), d + 1)
    }
    loop(new Factorization(n, Nil), 2).fs
  }
</pre>
<p>If the factorization is complete, then its factor list is the desired result. Otherwise, ask the factorization to remove a candidate divisor and continue with the result of that request. The inner <code>loop</code> function is only concerned with managing the sequence of divisors until the factorization is complete.</p>
<p>So the second moral of this post is this:</p>
<blockquote><p><i>Whenever part of a function&#8217;s parameter list represents some concept, consider making that explicit by using a class for the concept.</i></p></blockquote>
<p>Doing so will allow that concept to be implemented and tested independently, and will improve the clarity of the remaining code. Although the example in this post is a very small programming task, I think it makes a nice demonstration of the value of Scala&#8217;s hybrid nature.</p>
<br /><img alt="" border="0" src="http://feeds.wordpress.com/1.0/categories/joelneely.wordpress.com/38/" /> <img alt="" border="0" src="http://feeds.wordpress.com/1.0/tags/joelneely.wordpress.com/38/" /> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/joelneely.wordpress.com/38/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/joelneely.wordpress.com/38/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=joelneely.wordpress.com&#038;blog=2876257&#038;post=38&#038;subd=joelneely&#038;ref=&#038;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://joelneely.wordpress.com/2008/04/24/a-composite-function/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/c3ae6a1b8d708b79b6b85ecc365266a4?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">joelneely</media:title>
		</media:content>
	</item>
		<item>
		<title>Prime time programming</title>
		<link>http://joelneely.wordpress.com/2008/04/19/prime-time-programming/</link>
		<comments>http://joelneely.wordpress.com/2008/04/19/prime-time-programming/#comments</comments>
		<pubDate>Sat, 19 Apr 2008 23:32:19 +0000</pubDate>
		<dc:creator>joelneely</dc:creator>
				<category><![CDATA[functional programming]]></category>
		<category><![CDATA[Mathematics]]></category>
		<category><![CDATA[Project Euler]]></category>
		<category><![CDATA[Scala]]></category>

		<guid isPermaLink="false">http://joelneely.wordpress.com/?p=37</guid>
		<description><![CDATA[&#8220;The purpose of computing is insight, not numbers.&#8221; &#8211; Richard Hamming My interest in pursuing this series is not in the numbers, nor the Mathematics, but in the process of constructing reliable solutions. I&#8217;m also learning Scala, and want to understand how its hybrid OO/FP nature may offer fresh perspectives to my pursuit of programming. [&#8230;]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=joelneely.wordpress.com&#038;blog=2876257&#038;post=37&#038;subd=joelneely&#038;ref=&#038;feed=1" width="1" height="1" />]]></description>
				<content:encoded><![CDATA[<p>&#8220;<i>The purpose of computing is insight, not numbers.</i>&#8221; &#8211; <a href="http://en.wikipedia.org/wiki/Richard_Hamming">Richard Hamming</a></p>
<p>My interest in pursuing this series is not in the <a href="http://www.cbs.com/primetime/numb3rs/">numbers</a>, nor the <a href="http://www.dartmouth.edu/~matc/MathDrama/reading/Hamming.html">Mathematics</a>, but in the process of <a href="http://www.cs.utexas.edu/users/EWD/transcriptions/EWD12xx/EWD1255.html">constructing reliable solutions</a>. I&#8217;m also learning Scala, and want to understand how its hybrid OO/FP nature may offer fresh perspectives to my pursuit of programming.</p>
<h4>The largest factor</h4>
<p>The <a href="http://projecteuler.net/index.php?section=problems&amp;id=3">third problem</a> from <a href="http://projecteuler.net/">Project Euler</a> asks for the largest prime factor of a number <i>N</i> = 600,851,475,143. One approach would be produce the prime factors of <i>N</i> and return the <i>max</i> of that set. An obvious way to do <b>that</b> is to generate primes and try dividing each into <i>N</i>, but:</p>
<ol>
<li>Generating (or testing for) primes requires more code than generating divisors of <i>N</i>.
<p>We can find all factors of <i>N</i> by testing divisors <i>2 &#8230; n</i> (where <i>n = &radic; N</i>). The sieve of Eratosthenes yields all primes at most <i>n</i> with effort of <i>O(n log n)</i>, compared with <i>O(n)</i> for simply dividing <i>N</i> by all of the candidate divisors.</p>
</li>
<li>Factoring just one single number doesn&#8217;t appear to provide a return on the investment of building the collection of primes.
<p>Had the problem called for factoring multiple numbers of comparable size, then the cost of constructing a set of primes could have been amortized over multiple uses. I&#8217;ll revisit this later.</p>
</li>
<li>The smallest factor of <i>N</i> must be prime.
<p>The smallest factor of <i>N</i> <b>can&#8217;t</b> have any factors smaller than itself (else it wouldn&#8217;t be the smallest). If it doesn&#8217;t have any factors smaller than itself, it&#8217;s prime.</p>
</li>
</ol>
<p>We can base a simple design on those ideas:</p>
<ul>
<li>Removing all occurrences of the smallest factor of <i>N</i> leaves a quotient. Unless that quotient is 1, its largest prime factor is the largest prime factor of <i>N</i>. If the quotient is 1, the last factor removed is the largest prime factor of <i>N</i>.</li>
<li>We find factors by checking increasingly larger candidate divisors, beginning with 2. We don&#8217;t need to restart the divisors for a new quotient, because all smaller divisors have already been eliminated.</li>
<li>If the square of the current candidate divisor exceeds the current quotient then that quotient itself is prime (because all of its other possible divisors have already been eliminated).</li>
</ul>
<h4>First version</h4>
<p>It&#8217;s more trouble to write out those bullet points in English than it is to write the code:</p>
<pre>
  def lastFactor(t: Long) = {
    def loop(q: Long, f: Long, d: Long): Long =
      if (q == 1)
        f
      else if (q &lt; d * d)
        q
      else if (q % d == 0)
        loop(q / d, d, d)
      else
        loop(q, f, d + 1L)
    loop(t, 1L, 2L)
  }
</pre>
<p>As an aside, let me mention an issue of style. I&#8217;ve noticed that published functional programs tend to be written using short (some would say &#8220;cryptic&#8221;) variable names. Here&#8217;s the same definition, using words instead of initials:</p>
<pre>
  def lastFactor(target: Long) = {
    def loop(quotient: Long, factor: Long, divisor: Long): Long =
      if (quotient == 1)
        factor
      else if (quotient &lt; divisor * divisor)
        quotient
      else if (quotient % divisor == 0)
        loop(quotient / divisor, divisor, divisor)
      else
        loop(quotient, factor, divisor + 1)
    loop(target, 1, 2)
  }
</pre>
<p>My speculation is that the functional style tends to emphasize the <b>structure</b> of the function itself; longer names seem to put the emphasis on the variables. A &#8220;meatier&#8221; style makes it harder to see the &#8220;bones&#8221;. As I experiment with various approaches to a problem, I find myself using shorter names in an attempt to highlight the structural differences. I&#8217;ll stay with that style here (with apologies to anyone who finds it harder to read).</p>
<p>Back on the main topic, notice that the inner function <code>loop</code> deals with two different issues in the two tail-recursive calls:</p>
<ol>
<li><code>loop(q / d, d, d)</code> ensures that all occurrences of the current trial divisor are factored out (retaining the current divisor as the new largest factor), and</li>
<li><code>loop(q, f, d + 1L)</code> proceeds to the next trial divisor (with the current quotient and factor).</li>
</ol>
<p>As I mentioned in <a href="http://joelneely.wordpress.com/2008/04/09/the-burden-of-fp-part-3/">an earlier post</a>, Scala compiles direct tail recursion into tight, fast bytecode that doesn&#8217;t grow the activation stack. On my laptop, it finds the largest prime factor of 600,851,475,143 in about 66&micro;s. (If you don&#8217;t want to waste a few microseconds running the code yourself, the answer is 6,857.)</p>
<p>By way of contrast, an equivalent function using a pre-computed list of primes requires only about 15&micro;s. However, producing that list (all primes from 2 to 775,147) via a simple sieve takes about 61ms (yes, that&#8217;s 61,000&micro;s). Clearly we&#8217;d need to use that list quite a few times to recover the investment.</p>
<h4>A factor saved&#8230;</h4>
<p>Even if I didn&#8217;t know that future Project Euler problems will revisit factoring (my experiments are ahead of my writing), I would prefer not to throw information away. How much would the solution change if we decided to keep all factors instead of just the largest? Not much; just a few adjustements to the inner <code>loop</code> function:</p>
<ul>
<li>Parameter <code>f: Long</code> (the most recent factor) becomes <code>fs: List[Long]</code> (a list of all factors).</li>
<li>The initial value for <code>fs</code> is <code>Nil</code> (the empty list).</li>
<li>Everywhere <code>f</code> gets a new value, <code>fs</code> gets a value consed onto the front.
</ul>
<p>The changes are highlighted in the new function below:</p>
<pre>
  def <b><u>allFactors</u></b>(t: Long) = {
    def loop(q: Long, <b><u>fs: List[Long]</u></b>, d: Long): <b><u>List[Long]</u></b> =
      if (q == 1)
        <b><u>fs</u></b>
      else if (q &lt; d * d)
        <b><u>q :: fs</u></b>
      else if (q % d == 0)
        loop(q / d, <b><u>d :: fs</u></b>, d)
      else
        loop(q, <b><u>fs</u></b>, d + 1)
    loop(t, <b><u>Nil</u></b>, 2)
  }
</pre>
<p>Running that version with the specified value of <i>N</i> returns the complete list of factors&#8230;</p>
<pre>
scala&gt; allFactors(600851475143L)
res19: List[Long] = List(6857, 1471, 839, 71)
</pre>
<p>&#8230;and does so almost for free, taking about 67&micro;s instead of 66&micro;s on my laptop. (I&#8217;ve only run a few million tests, so that small a difference is almost statistical noise.) That&#8217;s not really surprising, as the only extra overhead is a call to <code>::</code> as each factor is saved. Even if our target had been a power of two (producing the most factors) there would have been only about 40 factors on the list.</p>
<h4>&#8230;is a factor folded</h4>
<p>&#8220;Cut-and-paste&#8221; is regarded as bad practice in OO. The DRY principle says that if we find ourselves repeating the same code, or pattern of code, we should extract a reusable form of the common logic. The same principle applies in FP.</p>
<p>Notice that <code>lastFactor</code> and <code>allFactors</code> have exactly the same higher-level structure; the differences are summarized in the following table, which also suggests a general case for some unknown type <code>T</code>.</p>
<table cellpadding="2" cellspacing="0" border="1" align="center">
<tr>
<td>&nbsp;</td>
<th align="center"><code>lastFactor</code></th>
<th align="center"><code>allFactors</th>
<th>general case</th>
</tr>
<tr>
<th>factor<br />type</th>
<td align="center"><code>Long</code></td>
<td align="center"><code>Long</code></td>
<td align="center"><code>Long</code></td>
</tr>
<tr>
<th>accumulator<br />type</th>
<td align="center"><code>Long</code></td>
<td align="center"><code>List[Long]</code></td>
<td align="center"><code>T</code></td>
</tr>
<tr>
<th>"zero"<br />value</th>
<td align="center"><code>1</code></td>
<td align="center"><code>Nil</code></td>
<td align="center">?</td>
</tr>
<tr>
<th>composition<br />type</th>
<td align="center"><code>Long</code> &rarr; <code>Long</code> &rarr; <code>Long</code></td>
<td align="center"><code>Long</code> &rarr; <code>List[Long]</code> &rarr; <code>List[Long]</code></td>
<td align="center"><code>Long</code> &rarr; <code>T</code> &rarr; <code>T</code></td>
</tr>
<tr>
<th>composition<br />function</th>
<td align="center">replacement<br />(<code>a</code>, <code>b</code>) &rarr; <code>a</code></td>
<td align="center">cons<br />(<code>f</code>, <code>fs</code>) &rarr; <code>f :: fs</code></td>
<td align="center">?</tr>
</table>
<p>So, just for fun here is a generic Scala function that processes the prime factors of an argument, using a caller-suppllied "zero" and composition function, with the differences highlighted:</p>
<pre>
  def foldFactors<b><u>[T]</u></b>(t: Long)<b><u>(z: T)</u></b><b><u>(f: (Long, T) =&gt; T)</u></b> = {
    def loop(q: Long, <b><u>acc: T</u></b>, d: Long): <b><u>T</u></b> =
      if (q == 1)
        <b><u>acc</u></b>
      else if (q &lt; d * d)
        <b><u>f(q, acc)</u></b>
      else if (q % d == 0)
        loop(q / d, <b><u>f(d, acc)</u></b>, d)
      else
        loop(q, <b><u>acc</u></b>, d + 1)
    loop(t, <b><u>z</u></b>, 2)
  }
</pre>
<p>We can get the "last" factor and the complete list of factors by providing the appropriate zero and composition function for each.</p>
<pre>
  scala&gt; foldFactors[Long](n)(1)((a,b) =&gt; a)       
  res32: Long = 6857
</pre>
<pre>
  scala&gt; foldFactors[List[Long]](n)(Nil)(_ :: _)
  res33: List[Long] = List(6857, 1471, 839, 71)
</pre>
<p>To be realistic, <code>allFactors</code> is really our best solution. It returns the factors as <code>List[Long]]</code>, which means that we get <code>foldLeft</code> for free, along with everything else that <code>List</code> provides. But this was an irresistible opportunity to point out that higher-order functions and type parameterization address the DRY principle that we already know from OO.</p>
<h4>To be continued</h4>
<p>I think that's enough to digest for now. There's another punch line that resulted from exploring this problem, but it deserves its own write-up. If you want a head-start on it, think about the fact that the result of <code>allFactors</code> is a bit inconvenient for some purposes, especially when the argument has many factors, as in:</p>
<pre>
  scala&gt; allFactors(86400)
  res35: List[Long] = List(5, 5, 3, 3, 3, 2, 2, 2, 2, 2, 2, 2)
</pre>
<p>Contrast that with the "normal" Mathematical representation of <i>5<sup>2</sup> &times; 3<sup>3</sup> &times; 2<sup>7</sup></i> for a hint. That's where I found myself reaching for the hybrid nature of Scala.</p>
<p>I noticed that <a href="http://basildoncoder.com/blog/2008/04/07/project-euler-problem-3/">Basildon Coder</a> had a post on this same problem. I held off reading it until after working through my own approach, so that I could look at the similarities and differences in two independently-created solutions. Perhaps you'll find that interesting as well.</p>
<br /><img alt="" border="0" src="http://feeds.wordpress.com/1.0/categories/joelneely.wordpress.com/37/" /> <img alt="" border="0" src="http://feeds.wordpress.com/1.0/tags/joelneely.wordpress.com/37/" /> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/joelneely.wordpress.com/37/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/joelneely.wordpress.com/37/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=joelneely.wordpress.com&#038;blog=2876257&#038;post=37&#038;subd=joelneely&#038;ref=&#038;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://joelneely.wordpress.com/2008/04/19/prime-time-programming/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/c3ae6a1b8d708b79b6b85ecc365266a4?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">joelneely</media:title>
		</media:content>
	</item>
		<item>
		<title>Go with the flow</title>
		<link>http://joelneely.wordpress.com/2008/04/12/go-with-the-flow/</link>
		<comments>http://joelneely.wordpress.com/2008/04/12/go-with-the-flow/#comments</comments>
		<pubDate>Sun, 13 Apr 2008 03:06:25 +0000</pubDate>
		<dc:creator>joelneely</dc:creator>
				<category><![CDATA[algorithms]]></category>
		<category><![CDATA[Mathematics]]></category>
		<category><![CDATA[Project Euler]]></category>
		<category><![CDATA[Scala]]></category>

		<guid isPermaLink="false">http://joelneely.wordpress.com/?p=35</guid>
		<description><![CDATA[The second problem from Project Euler asks for the sum of the even Fibonacci numbers which are at most 4,000,000. An aside on the numbers The problem&#8217;s description of the Fibonacci sequence is flawed (or at least non-standard); the problem statement begins the sequence with 1 and 2, showing the first 10 terms as: 1, [&#8230;]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=joelneely.wordpress.com&#038;blog=2876257&#038;post=35&#038;subd=joelneely&#038;ref=&#038;feed=1" width="1" height="1" />]]></description>
				<content:encoded><![CDATA[<p>The second problem from Project Euler asks for the sum of the even Fibonacci numbers which are at most 4,000,000.</p>
<h4>An aside on the numbers</h4>
<p>The problem&#8217;s description of the Fibonacci sequence is flawed (or at least non-standard); the problem statement begins the sequence with 1 and 2, showing the first 10 terms as:</p>
<blockquote><p>1, 2, 3, 5, 8, 13, 21, 34, 55, 89</p></blockquote>
<p>It is common to see the definition given as:</p>
<blockquote><p>fib<sub>1</sub> = 1, fib<sub>2</sub> = 1, fib<sub>n</sub> = fib<sub>n-1</sub> + fib<sub>n-2</sub></p></blockquote>
<p>I&#8217;m persuaded by <a href="http://www.cs.utexas.edu/users/EWD/transcriptions/EWD08xx/EWD831.html">Dijkstra&#8217;s line of reasoning</a>, and prefer to use the definition&#8230;</p>
<blockquote><p>fib<sub>0</sub> = 0, fib<sub>1</sub> = 1, fib<sub>n</sub> = fib<sub>n-1</sub> + fib<sub>n-2</sub></p></blockquote>
<p>&#8230;not only for the benefit of a zero origin, but also because it invites the mind to consider completing the story. The equations&#8230;</p>
<blockquote><p>fib<sub>n</sub> = fib<sub>n-1</sub> + fib<sub>n-2</sub></p></blockquote>
<p>&#8230;and&#8230;</p>
<blockquote><p>fib<sub>n</sub> &#8211; fib<sub>n-1</sub> = fib<sub>n-2</sub></p></blockquote>
<p>&#8230;are clearly equivalent, but the second one may help us realize that we can extend the conventional list to be infinite in <i>both</i> directions&#8230;</p>
<table border="1" cellpadding="2" cellspacing="0" align="center">
<tr align="right">
<th>n</th>
<td>&#8230;</td>
<td>-7</td>
<td>-6</td>
<td>-5</td>
<td>-4</td>
<td>-3</td>
<td>-2</td>
<td>-1</td>
<td>0</td>
<td>&nbsp;1</td>
<td>&nbsp;2</td>
<td>&nbsp;3</td>
<td>&nbsp;4</td>
<td>&nbsp;5</td>
<td>&nbsp;6</td>
<td>7</td>
<td>&#8230;</td>
</tr>
<tr align="right">
<th>fib<sub>n</sub></th>
<td>&#8230;</td>
<td>13</td>
<td>-8</td>
<td>5</td>
<td>-3</td>
<td>2</td>
<td>-1</td>
<td>1</td>
</td>
<td>0</td>
<td>1</td>
<td>1</td>
<td>2</td>
<td>3</td>
<td>5</td>
<td>8</td>
<td>13</td>
<td>&#8230;</td>
</tr>
</table>
<p>&#8230;making fib a total function over the integers. I&#8217;ll put off discussing that interesting option until another time, and for the rest of this post use only natural numbers.</p>
<h4>Basic solutions</h4>
<p>The naive recursive function for the n<sup>th</sup> Fibonacci number&#8230;</p>
<pre>
  def fibR(n: Int): Int = {
    if (n == 0)
      0
    else if (n == 1)
      1
    else
      fibR(n - 1) + fibR(n - 2)
  }
</pre>
<p>&#8230;requires O(exp n) time to evaluate. We could go for a tail-recursive (iterative) version&#8230;</p>
<pre>
  def fibI(n: Int): Int = {
    def fib0(i: Int, a: Int, b: Int): Int =
      if (i == n) a else fib0(i + 1, b, a + b)
    fib0(0, 0, 1)
  }
</pre>
<p>&#8230;which executes in O(n) time. That&#8217;s an improvement, but still leaves us dealing with the Fibonacci sequence one number at a time.</p>
<h4>Gently down the stream</h4>
<p>The problem calls for a sum across multiple values from the Fibonacci sequence, and both of the above functions calculate &#8220;upwards&#8221; to reach the specified value. There&#8217;s no point in going through the sequence more than once (regardless of how efficiently we can do that), so let&#8217;s think of the sequence as a <code>Stream[Int]</code>.</p>
<p>Element-wise addition of streams can be done as:</p>
<pre>
  def add(s1: Stream[Int], s2: Stream[Int]): Stream[Int] =
       Stream.cons(s1.head + s2.head, plus(s1.tail, s2.tail))
</pre>
<p>A stream of the Fibonacci numbers is then:</p>
<pre>
  val fibS: Stream[Int] = Stream.cons(0, Stream.cons(1, add(fibS, fibS tail)))
</pre>
<p>And now we&#8217;re back to familiar territory from the first problem. We simply filter for the even values, apply the limit, and sum the results:</p>
<pre>
  scala&gt; fibS.filter(_ % 2 == 0).takeWhile(_ &lt;= 4000000).foldLeft(0)(_ + _)
  res17: Int = 4613732
</pre>
<p>We could stop with that solution, but there are a couple of additional techniques worth a mention.</p>
<h4>&#8220;Go back, Jack, and do it again&#8221;</h4>
<p>First, we could replace the stream with a simple <code>Iterator[Int]</code> that holds a pair of consecutive Fibonacci numbers:</p>
<pre>
  class Fibs extends Iterator[Int] {
    var state = (0, 1)
    def hasNext = true
    def next = {
      val (a, b) = state
      state = (b, a + b)
      a
    }
  }
</pre>
<p>Thanks to the <code>Iterator</code> trait, when we implement <code>hasNext</code> (is there another value?) and <code>next</code> (return the next value), we get everything needed to complete the solution:</p>
<pre>
  scala&gt; new Fibs().filter(_ % 2 == 0).takeWhile(_ &lt;= 4000000).foldLeft(0)(_ + _)
  res20: Int = 4613732
</pre>
<p>However, this still generates three times as many values as needed, because only every third Fibonacci number is even:</p>
<blockquote><p><b>0</b>, <i>1</i>, <i>1</i>, <b>2</b>, <i>3</i>, <i>5</i>, <b>8</b>, <i>13</i>, <i>21</i>, <b>34</b>, <i>55</i>, <i>89</i>, <b>144</b>&#8230;</p></blockquote>
<p>How could we generate only the <b>even</b> Fibonacci numbers? Notice this progression in the numbers above:</p>
<blockquote><p>
fib<sub>0</sub> = 0<br />
fib<sub>3</sub> = 2<br />
fib<sub>6</sub> = 8<br />
fib<sub>9</sub> = 34<br />
fib<sub>12</sub> = 144<br />
&#8230;
</p></blockquote>
<p>So we&#8217;re interested in producing the sequence fib<sub>3n</sub> rather than fib<sub>n</sub> if we want to obtain the even values. In our Fib class above, a and b are consecutive values, fib<sub>n</sub> and fib<sub>n+1</sub>. From the original definition, we can apply just a little algebra:</p>
<blockquote><p>
fib<sub>n+2</sub> = b + a<br />
fib<sub>n+3</sub> = fib<sub>n+2</sub> + fib<sub>n+1</sub> = (b + a) + b = 2 &times; b + a<br />
fib<sub>n+4</sub> = fib<sub>n+3</sub> + fib<sub>n+2</sub> = (2 &times; b + a) + (b + a) = 3 &times; b + 2 &times; a
</p></blockquote>
<p>If n is a multiple of 3, then (n + 3) is the next multiple of 3. So the above formulas for fib<sub>n+3</sub> and fib<sub>n+4</sub> give us a way to write an iterator that produces only <b>even</b> Fibonacci numbers:</p>
<pre>
  class EvenFibs extends Iterator[Int] {
    var state = (0, 1)
    def hasNext = true
    def next = {
      val (a, b) = state
      state = (2 * b + a, 3 * b + 2 * a)
      a
    }
  }
</pre>
<p>This new iterator eliminates the need for the filter, reducing the solution to:</p>
<pre>
  scala&gt; new EvenFibs().takeWhile(_ &lt;= 4000000).foldLeft(0)(_ + _)              
  res30: Int = 4613732
</pre>
<p>This calculates exactly the values of interest, then uses standard methods to provide the sum. These last three versions retain the ability to re-use the parts that generate the Fibonacci numbers (or even Fibonacci numbers) for purposes other than the sum.</p>
<p>For sake of completeness, here&#8217;s the completely optimized version&#8230;</p>
<pre>
  def sumEvenFibs(n: Int) = {
    def iter(a: Int, b: Int, s: Int): Int =
      if (a &gt; n) s else iter(2 * b + a, 3 * b + 2 * a, a + s)
    iter(0, 1, 0)
  }
</pre>
<p>&#8230;which buys performance by giving up that reusability.</p>
<br /><img alt="" border="0" src="http://feeds.wordpress.com/1.0/categories/joelneely.wordpress.com/35/" /> <img alt="" border="0" src="http://feeds.wordpress.com/1.0/tags/joelneely.wordpress.com/35/" /> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/joelneely.wordpress.com/35/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/joelneely.wordpress.com/35/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=joelneely.wordpress.com&#038;blog=2876257&#038;post=35&#038;subd=joelneely&#038;ref=&#038;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://joelneely.wordpress.com/2008/04/12/go-with-the-flow/feed/</wfw:commentRss>
		<slash:comments>5</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/c3ae6a1b8d708b79b6b85ecc365266a4?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">joelneely</media:title>
		</media:content>
	</item>
		<item>
		<title>The burden of FP, part 3</title>
		<link>http://joelneely.wordpress.com/2008/04/09/the-burden-of-fp-part-3/</link>
		<comments>http://joelneely.wordpress.com/2008/04/09/the-burden-of-fp-part-3/#comments</comments>
		<pubDate>Thu, 10 Apr 2008 02:11:11 +0000</pubDate>
		<dc:creator>joelneely</dc:creator>
				<category><![CDATA[functional programming]]></category>
		<category><![CDATA[Project Euler]]></category>
		<category><![CDATA[Scala]]></category>

		<guid isPermaLink="false">http://joelneely.wordpress.com/?p=33</guid>
		<description><![CDATA[Inside out This series has used the first problem from Project Euler to look at different programming styles; Part 1 asked questions about the obvious imperative solution, and Part 2 used higher-order functions in a functional approach. This part considers performance to take us in a different direction. Despite their differences in style, all of [&#8230;]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=joelneely.wordpress.com&#038;blog=2876257&#038;post=33&#038;subd=joelneely&#038;ref=&#038;feed=1" width="1" height="1" />]]></description>
				<content:encoded><![CDATA[<h4>Inside out</h4>
<p>This series has used the <a href="http://projecteuler.net/index.php?section=problems&amp;id=1">first problem</a> from <a href="http://projecteuler.net/">Project Euler</a> to look at different programming styles; <a href="http://joelneely.wordpress.com/2008/04/06/the-burden-of-fp/">Part 1</a> asked questions about the obvious imperative solution, and <a href="http://joelneely.wordpress.com/2008/04/08/the-burden-of-fp-part-2/">Part 2</a> used higher-order functions in a functional approach. This part considers performance to take us in a different direction.</p>
<p>Despite their differences in style, all of the previous solutions had the following scheme in common:</p>
<div style="text-align:center;"><img src="http://joelneely.files.wordpress.com/2008/04/projecteuler-1-a.jpg?w=292&#038;h=123" alt="ProjectEuler-1-a.jpg" border="0" width="292" height="123" /></div>
<p>Beginning with the positive integers below a given limit, select those that are multiples of two given values, and compute the sum of the selected set. The higher-order function approach allowed us to think about each of the components individually, composing them into a solution. However, this basic generate-select-process pipeline may hide some wasted effort.</p>
<h4>There and back again</h4>
<p>First, notice that problem specified <em>multiples</em> of 3 and 5 but the filtering used division, in the disguise of remainder calculation. This works only because the multiple-of property has an easy-to-compute inverse.</p>
<p>Second, just under half of all positive integers (7/15 to be exact) actually fall into the selected set. The generate-and-test scheme becomes more wasteful as the yield becomes smaller. For example, if the problem had been to sum multiples of 97 and 113, then most of the generated numbers would be discarded.</p>
<p>Thinking along these lines suggests another scheme, illustrated below:</p>
<div style="text-align:center;"><img src="http://joelneely.files.wordpress.com/2008/04/projecteuler-1-b1.jpg?w=417&#038;h=159" alt="ProjectEuler-1-b.jpg" border="0" width="417" height="159" /></div>
<p>Instead of generating and discarding failed candidates, this approach directly generates the two sets of multiples (e.g., of 3 and 5). Merging those two sets will ensure that duplicates (e.g. 15) are only included once. The upper limit is applied to the merged values, and the results are summed.</p>
<p>I want to maintain separation of concerns here, so I&#8217;m going to pretend that we don&#8217;t know how to limit the sets of multiples (i.e., that we can&#8217;t easily compute the largest multiple of 3 less than 1000). In other words, I&#8217;m going to take this opportunity to model the multiples as unbounded sequences, using Scala&#8217;s <code>Stream</code> type, which provides a lazy list.</p>
<p>Given integer expressions <i>init</i> and <i>incr</i>, evaluating <code>Stream.from(<i>init</i>, <i>incr</i>)</code> returns the stream of values beginning with <i>init</i> and stepping by <i>incr</i>. For example:</p>
<pre>
  scala&gt; val odds = Stream.from(1, 2)
  odds: Stream[Int] = Stream(1, ?)
</pre>
<pre>
  scala&gt; odds take 20 print
  1, 3, 5, 7, 9, 11, 13, 15, 17, 19, 21, 23, 25, 27, 29, 31, 33, 35, 37, 39, Stream.empty
</pre>
<p>So the stream of multiples of a given value are easy to produce:</p>
<pre>
  scala&gt; val threes = Stream.from(3, 3)
  threes: Stream[Int] = Stream(3, ?)
</pre>
<pre>
  scala&gt; threes take 20 print
  3, 6, 9, 12, 15, 18, 21, 24, 27, 30, 33, 36, 39, 42, 45, 48, 51, 54, 57, 60, Stream.empty
</pre>
<p>So much for the first part of this design!</p>
<h4>&#8220;<i>Don&#8217;t merge the streams!</i>&#8220;</h4>
<p>Ignoring <a href="http://www.amazon.com/gp/product/B000E33W1W?ie=UTF8&amp;tag=slidiuptheban-20&amp;linkCode=as2&amp;camp=1789&amp;creative=9325&amp;creativeASIN=B000E33W1W">the above advice</a><img src="http://www.assoc-amazon.com/e/ir?t=slidiuptheban-20&amp;l=as2&amp;o=1&amp;a=B000E33W1W" width="1" height="1" border="0" alt="" style="border:none !important;margin:0 !important;" />, here&#8217;s a simple recursive function to merge two streams of increasing integers:</p>
<pre>
  def merge(as: Stream[Int], bs: Stream[Int]): Stream[Int] = {
    val h = as.head min bs.head
    Stream.cons(h, merge(as dropWhile {_ == h}, bs dropWhile {_ == h})
    )
  }
</pre>
<p>At any point, the merged stream contains the minimum of the input streams followed by merging whatever follows that minimum in both of the original streams.</p>
<p>That kind of terse, recursive definition is fairly common in FP, and is sufficiently unfamiliar to some that it may be a bit off-putting. At the risk of using a tired analogy, it&#8217;s like bike-riding; once you can stay on long enough to get down the driveway, you&#8217;ve got it made. (And it&#8217;s worth the effort, because you can outrun the kids that are still on foot! <img src='http://s1.wp.com/wp-includes/images/smilies/icon_wink.gif' alt=';-)' class='wp-smiley' /> </p>
<p>As proof of that point, we now have everything we need for the solution to problem one:</p>
<pre>
  def sumStream(a: Int, b: Int)(n: Int) =
    (merge(Stream.from(a, a), Stream.from(b, b)).takeWhile{_ &lt; n}.foldLeft (0)) {_ + _}
</pre>
<p>As in part 2, the key is being able to string together the components with minimum fuss. We can easily test the construction of the streams, the merge function, and the limiting via <code>takeWhile</code> (we&#8217;ve exercised <code>foldLeft</code> in the previous post). Because there is no shared state, composing them does not alter their behavior.</p>
<h4>Twice-told tales</h4>
<p>A persistent myth is that high-level languages require more resources than lower-level languages. Although the stream-based solution uses objects to manage future state, that was an explicit tradeoff to avoid producing unsuccessful candidate values. If we are <i>really</i> concerned with performance, functional programming will <i>still</i> support us as we manually optimize our solution.</p>
<p>A stream of multiples can be represented simply by the head of the virtual stream (the next multiple) and the increment. Iterating through the stream is accomplished by adding the increment to the head, so <code>dropWhile</code> amounts to deciding whether the next head of a stream should be the incremented head or the current head.</p>
<p>Applying those special-case representations to our merging strategy, we get this solution:</p>
<pre>
  def sumRec(a: Int, b: Int)(n: Int) = {
    def iter(ma: Int, mb: Int, t: Int): Int = {
      val m = ma min mb
      def next(mx: Int, x: Int) =
        if (mx == m) mx + x else mx
      if (m &lt; n)
        iter(next(ma, a), next(mb, b), t + m)
      else
        t
    }
    iter(a, b, 0)
  }
</pre>
<p>The local variable <code>m</code> is the head of the merged streams, the inner <code>next</code> function accomplishes the equivalent of <code>dropWhile</code>, and the <code>iter</code> function simultaneously merges the streams (represented by <code>ma</code> and <code>mb</code>) and accumulates the total (in <code>t</code>).</p>
<p>The <code>iter</code> function is directly tail-recursive; it either terminates with the result or recursively invokes itself with adjusted arguments. Because of this, the Scala compiler actually compiles <code>iter</code> into a tight loop occupying only a handful of JVM bytecodes. It is by far the fastest of all the solutions we&#8217;ve examined!</p>
<h4>Take my code, please!</h4>
<p>For me, there&#8217;s a punch line to this series. As implied above, I thought of this last version only <b>after</b> writing <code>sumStream</code>; I created <code>sumRec</code> by rethinking the code to take advantage of the special cases in the problem. I find it interesting that the fastest function was created by first completely ignoring performance and thinking about making the design as clean and modular as possible.</p>
<p>As I&#8217;ve believed for years, it&#8217;s easier to make correct code faster than to make fast (but buggy) code correct.</p>
<br /><img alt="" border="0" src="http://feeds.wordpress.com/1.0/categories/joelneely.wordpress.com/33/" /> <img alt="" border="0" src="http://feeds.wordpress.com/1.0/tags/joelneely.wordpress.com/33/" /> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/joelneely.wordpress.com/33/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/joelneely.wordpress.com/33/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=joelneely.wordpress.com&#038;blog=2876257&#038;post=33&#038;subd=joelneely&#038;ref=&#038;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://joelneely.wordpress.com/2008/04/09/the-burden-of-fp-part-3/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/c3ae6a1b8d708b79b6b85ecc365266a4?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">joelneely</media:title>
		</media:content>

		<media:content url="http://joelneely.files.wordpress.com/2008/04/projecteuler-1-a.jpg" medium="image">
			<media:title type="html">ProjectEuler-1-a.jpg</media:title>
		</media:content>

		<media:content url="http://joelneely.files.wordpress.com/2008/04/projecteuler-1-b1.jpg" medium="image">
			<media:title type="html">ProjectEuler-1-b.jpg</media:title>
		</media:content>

		<media:content url="http://www.assoc-amazon.com/e/ir?t=slidiuptheban-20&#38;l=as2&#38;o=1&#38;a=B000E33W1W" medium="image" />
	</item>
		<item>
		<title>The burden of FP, part 2</title>
		<link>http://joelneely.wordpress.com/2008/04/08/the-burden-of-fp-part-2/</link>
		<comments>http://joelneely.wordpress.com/2008/04/08/the-burden-of-fp-part-2/#comments</comments>
		<pubDate>Tue, 08 Apr 2008 19:22:25 +0000</pubDate>
		<dc:creator>joelneely</dc:creator>
				<category><![CDATA[functional programming]]></category>
		<category><![CDATA[Project Euler]]></category>
		<category><![CDATA[Scala]]></category>

		<guid isPermaLink="false">http://joelneely.wordpress.com/?p=29</guid>
		<description><![CDATA[Do you have anything to declare? Part 1 looked critically an imperative-style solution to the first problem from Project Euler. This part of the discussion introduces a more functional style, using higher-order functions. The goal is to think more declaratively, familiar territory to any programmer who has used SQL. In the solution from last time&#8230; [&#8230;]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=joelneely.wordpress.com&#038;blog=2876257&#038;post=29&#038;subd=joelneely&#038;ref=&#038;feed=1" width="1" height="1" />]]></description>
				<content:encoded><![CDATA[<h4>Do you have anything to declare?</h4>
<p><a href="http://joelneely.wordpress.com/2008/04/06/the-burden-of-fp/">Part 1</a> looked critically an imperative-style solution to the <a href="http://projecteuler.net/index.php?section=problems&amp;id=1">first problem</a> from <a href="http://projecteuler.net/">Project Euler</a>. This part of the discussion introduces a more functional style, using higher-order functions. The goal is to think more declaratively, familiar territory to any programmer who has used SQL.</p>
<p>In the solution from last time&#8230;</p>
<pre>
  def sumi(n: Int) = {
    var s = 0
    <b><u>for (i &lt;- 1 until n)</u></b> {
      if (i % 3 == 0 || i % 5 == 0)
        s += i
    }
    s
  }
</pre>
<p>&#8230;it&#8217;s useful to think of the <code>for</code> expression as a <i>query</i>, instead of an imperative control structure. The subexpression <code>1 until n</code> isn&#8217;t hardwired syntax of the <code>for</code> statement, but an expression for a set of values. Just as a program written against a database can be made simpler by enhancing the query, we can simplify the body of the <code>for</code> expression by moving the filter, as follows:</p>
<pre>
  def sumiq(n: Int) = {
    var s = 0
    <b><u>for {</u></b>
      <b><u>i &lt;- 1 until n</u></b>
      <b><u>if i % 3 == 0 || i % 5 == 0</u></b>
    <b><u>}</u></b> s += i
    s
  }
</pre>
<p>That change is bigger than it might seem at first glance; it applies a filter to a set of values instead of applying a control structure to a single value. We can see this even more clearly by going to the Scala interpreter.</p>
<pre>
  scala&gt; 1 until 10
  res0: Range = Range(1, 2, 3, 4, 5, 6, 7, 8, 9)
</pre>
<p>The input expression evaluates to an instance of <code>Range</code>; its values are subsequently pulled out and displayed by the interpreter. A sequence of values can be further filtered by a criterion, either written in-line (anonymously)&#8230;</p>
<pre>
  scala&gt; (1 until 10).filter(i =&gt; i % 3 == 0 || i % 5 == 0)
  res1: Seq.Projection[Int] = RangeF(3, 5, 6, 9)
</pre>
<p>&#8230;or defined explicitly:</p>
<pre>
  scala&gt; val divisibleBy3or5 = (i: Int) =&gt; i % 3 == 0 || i % 5 == 0
  divisibleBy3or5: (Int) =&gt; Boolean = &lt;function&gt;
</pre>
<pre>
  scala&gt; (1 until 10).filter(divisibleBy3or5)
  res2: Seq.Projection[Int] = RangeF(3, 5, 6, 9)
</pre>
<p>Scala allows us to write single-argument methods as if they were operators, so the last input above can be simplified to:</p>
<pre>
  scala&gt; 1 until 10 filter divisibleBy3or5
  res3: Seq.Projection[Int] = RangeF(3, 5, 6, 9)
</pre>
<p>So we now have a variety of ways to get the sequence of &#8220;interesting&#8221; values; for example, we could expose the &#8220;multiples of&#8221; concept as curried parameters to get something resembling this&#8230;</p>
<pre>
  def sumMultiples(a: Int, b: Int)(n: Int) = {
    val multiples = (i: Int) =&gt; i % a == 0 || i % b == 0
    val candidates = 1 until n filter multiples
    var s = 0
    for (i &lt;- candidates) s += i
    s
  }
</pre>
<p>&#8230;but we still have in-line, imperative-looking code accumulating the sum.</p>
<h4>Folding the result</h4>
<p>We can extract the sum calculation by defining our own sum-of-sequence-of-integers function&#8230;</p>
<pre>
  def sumSeqInt(ns: Seq[Int]) = {
    var s = 0
    for (n &lt;- ns) s += n
    s
  }
</pre>
<p>&#8230;but why reinvent the wheel? The function <code>sumSeqInt</code> is just a specific example of a more general pattern. Calculating a product or <code>List[Int]</code> has exactly the same structure;  we only need to provide the appropriate initial value and operation.</p>
<table align="center" cellpadding="3" border="1">
<tr align="center">
<th rowspan="2">Required<br />result
<th colspan="2">Parameters</th>
</td>
<tr align="center">
<th>Initial value</th>
<th>Operation</th>
</tr>
<tr align="center">
<th>Sum</th>
<td>0</td>
<td>+</td>
</tr>
<tr align="center">
<th>Product</th>
<td>1</td>
<td>*</td>
</tr>
<tr align="center">
<th>List</th>
<td>Nil</td>
<td>::</td>
</tr>
</table>
<p>That higher-order pattern is a <i>fold</i>, and comes in two flavors, depending on whether the accumulation begins at the left- or right-hand end of the sequence. As shown below, the symbolic notations (<code>/:</code> for <code>foldLeft</code> and <code>:\</code> for <code>foldRight</code>) are visual mnemonics for the expression trees they represent, with the initial value of <code>z</code> (for &#8220;zero&#8221;) at the bottom left or the bottom right of the tree.</p>
<div style="text-align:center;"><img src="http://joelneely.files.wordpress.com/2008/04/foldlfoldr1.jpg?w=398&#038;h=200" alt="foldLfoldR.jpg" border="0" width="398" height="200" align="center" /></div>
<p>Using a fold, we can now express a complete solution, including parameters for the multipliers, in the form below&#8230;</p>
<pre>
  def sumfl(a: Int, b: Int)(n: Int) =
    (0 /: (1 until n filter(i =&gt; i % a == 0 || i % b == 0))) {_ + _}
</pre>
<p>&#8230;which is fairly close to the specification: &#8220;the sum of positive integers below <code>n</code> which are divisible by <code>a</code> or <code>b</code>&#8220;.</p>
<h4>&#8220;The soul of wit&#8221;</h4>
<p>That last version certainly looks very different from typical imperative code written in C or Java. The point is not to be cryptic, but to be concise. Improving the &#8220;signal-to-boilerplate ratio&#8221; brings two benefits:</p>
<ol>
<li>We lower the risk of error (typos or otherwise), which are usually proportional to the quantity of code, and</li>
<li>If (when!) the specification changes, we can be more efficient about finding and making the required code changes.
</ol>
<p>From one perspective, higher-order functions allow us to <a href="http://www.removingalldoubt.com/permalink.aspx/6080a8a8-bb63-4492-acd2-1398f086fca0">eliminate explicit control structures</a>, simplifying the organization of the code. From a different angle, they allow us to think in terms of whole data structure, rather than individual data elements (avoiding the functional analogue of <a href="http://www.cs.uni.edu/~wallingf/blog/archives/monthly/2005-05.html#e2005-05-31T17_50_20.htm">primitive obsession</a>.)</p>
<p>In the <a href="http://joelneely.wordpress.com/2008/04/09/the-burden-of-fp-part-3/">final pos</a>t in this series, we&#8217;ll come at the problem from a different angle, which allows us to address performance.</p>
<br /><img alt="" border="0" src="http://feeds.wordpress.com/1.0/categories/joelneely.wordpress.com/29/" /> <img alt="" border="0" src="http://feeds.wordpress.com/1.0/tags/joelneely.wordpress.com/29/" /> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/joelneely.wordpress.com/29/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/joelneely.wordpress.com/29/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=joelneely.wordpress.com&#038;blog=2876257&#038;post=29&#038;subd=joelneely&#038;ref=&#038;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://joelneely.wordpress.com/2008/04/08/the-burden-of-fp-part-2/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/c3ae6a1b8d708b79b6b85ecc365266a4?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">joelneely</media:title>
		</media:content>

		<media:content url="http://joelneely.files.wordpress.com/2008/04/foldlfoldr1.jpg" medium="image">
			<media:title type="html">foldLfoldR.jpg</media:title>
		</media:content>
	</item>
		<item>
		<title>The burden of FP</title>
		<link>http://joelneely.wordpress.com/2008/04/06/the-burden-of-fp/</link>
		<comments>http://joelneely.wordpress.com/2008/04/06/the-burden-of-fp/#comments</comments>
		<pubDate>Sun, 06 Apr 2008 16:58:24 +0000</pubDate>
		<dc:creator>joelneely</dc:creator>
				<category><![CDATA[functional programming]]></category>
		<category><![CDATA[Mathematics]]></category>
		<category><![CDATA[Project Euler]]></category>
		<category><![CDATA[Scala]]></category>

		<guid isPermaLink="false">http://joelneely.wordpress.com/?p=26</guid>
		<description><![CDATA[A rude awakening&#8230; When the fire alarm sounded at about 2:00 AM, I didn&#8217;t want to think about electrical engineering, hydrology, or locksmithing. I wanted a quick fix. The tiniest of pinhole leaks in the attic water heater drain line had released a fine mist, some of which escaped the footprint of the catch pan. [&#8230;]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=joelneely.wordpress.com&#038;blog=2876257&#038;post=26&#038;subd=joelneely&#038;ref=&#038;feed=1" width="1" height="1" />]]></description>
				<content:encoded><![CDATA[<h4>A rude awakening&#8230;</h4>
<p>When the fire alarm sounded at about 2:00 AM, I didn&#8217;t want to think about electrical engineering, hydrology, or locksmithing. I wanted a quick fix.</p>
<p>The tiniest of pinhole leaks in the attic water heater drain line had released a fine mist, some of which escaped the footprint of the catch pan. Condensing on the attic floor, it accumulated to the point of dripping through the crack between boards, trickling down to the upstairs hall ceiling and through the hole where the wiring ran from the smoke detecter to the alarm system. Smoke detectors don&#8217;t like water.</p>
<p>(Of course, that little exercise in house debugging, with no advance warning and severe time pressure, it totally unlike anything experienced by a professional software developer. <img src='http://s1.wp.com/wp-includes/images/smilies/icon_wink.gif' alt=';-)' class='wp-smiley' />  ) And <i><b>that</b></i> (believe it or not) brings me to <a href="http://projecteuler.net/">Project Euler</a> and the title of this post. I had heard of Project Euler before, but <a href="http://basildoncoder.com/blog/2008/03/22/project-euler-problems-1-and-2/">this post</a> enticed me to visit the site. One look and I was hooked.</p>
<p>The site offers a series of little mathematical problems of gradually increasing difficulty. The result of each task is a number, which you submit for verification that you completed the task. The point, of course, is to think beyond the obvious <a href="http://en.wikipedia.org/wiki/Brute_force_attack">brute force</a> solution to produce one which continues to be feasible as the task scales.</p>
<p>All in all, the site is a nice collection of progressively larger <a href="http://joelneely.wordpress.com/2008/03/22/currying-without-lab-rats#labrats/">lab rats</a>. I know that <a href="http://www.youtube.com/watch?v=h_mDjbWIMso">some folks</a> don&#8217;t care for such problems, but the very first one rewarded my attention.</p>
<h4>Problem 1</h4>
<p>My paraphrase: &#8220;Sum the positive integers below 1000 that are multiples of 3 or 5.&#8221;  Simple (to the point of triviality) for any practicing programmer. So there must be more to it than the obvious (and very procedural) Scala implementation&#8230;</p>
<pre>
  def sumi(n: Int) = {
    var s = 0
    for (i &lt;- 1 until n) {
      if (i % 3 == 0 || i % 5 == 0)
        s += i
    }
    s
  }
</pre>
<p>&#8230;and there is. (The &#8216;<code>i</code>&#8216; on the end of <code>sumi</code> stands for &#8220;imperative&#8221;.)</p>
<h4>Mathematics and programming</h4>
<p>Student programmers are often guided to look for general solutions, especially by their more mathematically-inclined teachers. But generalizing requires thinking about what <i>kinds</i> of generality may be needed, thinking about what is likely to change. OOP&#8217;s polymorphism and inheritance encourage us to think about kinds of generality that are harder to express in procedural programming. FP allows easy exploration of even more kinds of change. But having more options means having to make more choices. I found it interesting to take a hard look at the above code to see how many issues were hard-wired into its structure. FP makes it easier to break those issues apart, but at the cost of thinking more <i>abstractly</i> (math-speak for &#8220;more generally&#8221;).</p>
<h4>Highlighting the issues</h4>
<p>At the risk of consuming a fair bit of virtual ink, I want to identify some aspects of the task, highlighting the parts of the code that deal with each aspect.</p>
<ol>
<li><i>Sum the positive integers below <strong><u>1000</u></strong> that are multiples of 3 or 5.</i>
<pre>
  def sumi(<b><u>n</u></b>: Int) = {
    var s = 0
    for (i &lt;- 1 until <b><u>n</u></b>) {
      if (i % 3 == 0 || i % 5 == 0)
        s += i
    }
    s
  }
</pre>
<p>I&#8217;ve already cheated a little; the parameter <code><b><u>n</u></b></code> allows us to replace the <b><u>1000</u></b> with a different limit.
</li>
<li><i>Add <strong><u>all the positive integers below 1000</u></strong> that are multiples of 3 or 5.</i>
<pre>
  def sumi(<b><u>n</u></b>: Int) = {
    var s = 0
    for (i &lt;- <b><u>1 until n</u></b>) {
      if (i % 3 == 0 || i % 5 == 0)
        s += i
    }
    s
  }
</pre>
<p>The generator <code>1 until n</code> produces exactly the values one up to (but not including) <code>n</code>.
</li>
<li><i>Sum the positive integers below 1000 that are multiples of <strong><u>3</u></strong> or <strong><u>5</u></strong>.</i>
<pre>
  def sumi(n: Int) = {
    var s = 0
    for (i &lt;- 1 until n) {
      if (i % <b><u>3</u></b> == 0 || i % <b><u>5</u></b> == 0)
        s += i
    }
    s
  }
</pre>
<p>Confession time: obviously I made the subconscious assumption that the <b>1000</b> was more likely to change than the <b>3</b> or <b>5</b>.
</li>
<li><i>Sum the positive integers below 1000 <strong><u>that are multiples of 3 or 5</u></strong>.</i>
<pre>
  def sumi(n: Int) = {
    var s = 0
    for (i &lt;- 1 until n) {
      <b><u>if (i % 3 == 0 || i % 5 == 0)</u></b>
        s += i
    }
    s
  }
</pre>
<p>I unconsciously represented the concept of &#8220;being a multiple of&#8221; with &#8220;has a remainder of zero when divided by&#8221;. It makes me ponder how often our programs completely replace a <i>problem domain concept</i> with an <i>implementation choice</i> without even noticing that we&#8217;ve done so.
</li>
<li><i><strong><u>Sum</u></strong> the positive integers below 1000 that are multiples of 3 or 5.</i>
<pre>
  def sumi(n: Int) = {
    <b><u>var s = 0</u></b>
    for (i &lt;- 1 until n) {
      if (i % 3 == 0 || i % 5 == 0)
        <b><u>s += i</u></b>
    }
    <b><u>s</u></b>
  }
</pre>
<p>The (single!) idea of producing a sum has become multiple steps: initializing and updating a variable, and retrieving its value as the answer.
</li>
</ol>
<h4>Functions and patterns</h4>
<p>While I wholeheartedly appreciate the <a href="http://www.amazon.com/gp/product/0321213351?ie=UTF8&amp;tag=slidiuptheban-20&amp;linkCode=as2&amp;camp=1789&amp;creative=9325&amp;creativeASIN=0321213351">contributions</a><img src="http://www.assoc-amazon.com/e/ir?t=slidiuptheban-20&amp;l=as2&amp;o=1&amp;a=0321213351" width="1" height="1" border="0" alt="" style="border:none !important;margin:0 !important;" /> of <a href="http://www.amazon.com/gp/product/0596007124?ie=UTF8&amp;tag=slidiuptheban-20&amp;linkCode=as2&amp;camp=1789&amp;creative=9325&amp;creativeASIN=0596007124">the</a><img src="http://www.assoc-amazon.com/e/ir?t=slidiuptheban-20&amp;l=as2&amp;o=1&amp;a=0596007124" width="1" height="1" border="0" alt="" style="border:none !important;margin:0 !important;" /> <a href="http://www.amazon.com/gp/product/0201633612?ie=UTF8&amp;tag=slidiuptheban-20&amp;linkCode=as2&amp;camp=1789&amp;creative=9325&amp;creativeASIN=0201633612"> pattern</a><img src="http://www.assoc-amazon.com/e/ir?t=slidiuptheban-20&amp;l=as2&amp;o=1&amp;a=0201633612" width="1" height="1" border="0" alt="" style="border:none !important;margin:0 !important;" /> <a href="http://www.hillside.net/patterns/">movement</a> to OO, the approach is evolutionary, not revolutionary. A few decades ago even the humble <a href="http://en.wikipedia.org/wiki/For_loop">for-loop</a> had to be recognized as expressing a standard solution to a recurring need. In the FP world, higher-order functions often provide the same sort of &#8220;glue&#8221; expressed in some patterns. For example <a href="http://www.enterpriseintegrationpatterns.com/PipesAndFilters.html">pipes-and-filters</a> are function composition in OOP clothing.</p>
<p>The little <code>sumi</code> method above is certainly a function from its argument <code>n</code> to the corresponding sum. But the &#8220;function-like&#8221; quality stops at the outer most curly braces, because <code>sumi</code> is almost entirely conceived in terms of imperative commands acting on mutable state (i.e. side effects). That has some subtle consequences when compared with an approach that tries to &#8220;be functional&#8221; all the way down, in the same way that OO changed our perspective when we began to design in terms of <a href="http://www.squeak.org/">objects</a> <a href="http://people.csail.mit.edu/torralba/tinyimages/">all</a> <a href="http://www.the-funneled-web.com/Hawking.htm">the</a> <a href="http://blogs.msdn.com/mattwar/archive/2007/06/21/linq-to-sql-objects-all-the-way-down.aspx">way</a> <a href="http://jamesshore.com/Blog/PrimitiveObsession.html">down</a>.</p>
<p>I believe that most of us would recognize <code>sumi</code> as belonging to this general design:</p>
<ul>
<li>generate a set of values,</li>
<li>test those values to select the desired subset, and</li>
<li>perform a specified action on that subset,</li>
</ul>
<p>but those aspects of the design are not cleanly, independently represented in the code. Functional programming offers us a way to do that.</p>
<p>The <a href="http://joelneely.wordpress.com/2008/04/08/the-burden-of-fp-part-2/">next post</a> will offer some examples as justification of that claim. Meanwhile, I need to catch up on the sleep interrupted by the fire alarm!</p>
<h4>The life of a programmer</h4>
<p>Before I end this post, let me close the fire-alarm connection. It&#8217;s easy to slip into fire-fighting (or fire-alarm-fighting) mode in day-to-day programming. And when doing so, it&#8217;s easy to become impatient with anything that doesn&#8217;t lead in a straight line to working code. I recall a collegue&#8217;s remark in a discussion about resolving a problem with a production system. Different participants offered a series of suggestions, all beginning with, &#8220;Well, you could&#8230;&#8221;, until he finally blurted out, &#8220;I don&#8217;t need <b>more</b> options; I need <b>fewer</b> options!&#8221;</p>
<p>Sometimes fixing the immediate problem quickly is the right thing to do, in the near term. I unplugged the shorted smoke detector, put a piece of plastic in place to collect the mist and deposit it into the catch pan, and went back to bed. But the second step is to go beyond the symptoms to the root cause and fix <b>that</b>. The plumber has replaced the failed pipe, and the technician with a replacement smoke detector is on the way.</p>
<p>But the third step is to prevent the problem from happening in the first place. Or, as the agile guys say, &#8220;Deliver tested working code quickly. But leave yourself set up properly to do the same thing on the next cycle!&#8221;</p>
<p>Maybe plastic pipe isn&#8217;t the best choice for difficult-to-reach applications, especially when elevated temperatures are involved.</p>
<br /><img alt="" border="0" src="http://feeds.wordpress.com/1.0/categories/joelneely.wordpress.com/26/" /> <img alt="" border="0" src="http://feeds.wordpress.com/1.0/tags/joelneely.wordpress.com/26/" /> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/joelneely.wordpress.com/26/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/joelneely.wordpress.com/26/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=joelneely.wordpress.com&#038;blog=2876257&#038;post=26&#038;subd=joelneely&#038;ref=&#038;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://joelneely.wordpress.com/2008/04/06/the-burden-of-fp/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/c3ae6a1b8d708b79b6b85ecc365266a4?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">joelneely</media:title>
		</media:content>

		<media:content url="http://www.assoc-amazon.com/e/ir?t=slidiuptheban-20&#38;l=as2&#38;o=1&#38;a=0321213351" medium="image" />

		<media:content url="http://www.assoc-amazon.com/e/ir?t=slidiuptheban-20&#38;l=as2&#38;o=1&#38;a=0596007124" medium="image" />

		<media:content url="http://www.assoc-amazon.com/e/ir?t=slidiuptheban-20&#38;l=as2&#38;o=1&#38;a=0201633612" medium="image" />
	</item>
	</channel>
</rss>