<?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet type="text/xsl" media="screen" href="/~d/styles/rss2full.xsl"?><?xml-stylesheet type="text/css" media="screen" href="http://feeds.feedburner.com/~d/styles/itemcontent.css"?><rss xmlns:geo="http://www.w3.org/2003/01/geo/wgs84_pos#" xmlns:feedburner="http://rssnamespace.org/feedburner/ext/1.0" version="2.0">
  <channel>
    <title>PaulBarry.com</title>
    <link>http://paulbarry.com/</link>
    <language>en-us</language>
    <ttl>40</ttl>
    <description>My thoughts, ideas, questions and concerns on technology, sports, music and life</description>
    <geo:lat>39.273841</geo:lat><geo:long>-76.610201</geo:long><image><link>http://www.gravatar.com/avatar/6661ef9d747db3af8896cd94959d717d?s=80</link><url>http://www.feedburner.com/fb/images/pub/fb_pwrd.gif</url><title>Paul Barry</title></image><atom10:link xmlns:atom10="http://www.w3.org/2005/Atom" rel="self" href="http://feeds.feedburner.com/paulbarry" type="application/rss+xml" /><feedburner:emailServiceId>paulbarry</feedburner:emailServiceId><feedburner:feedburnerHostname>http://feedburner.google.com</feedburner:feedburnerHostname><atom10:link xmlns:atom10="http://www.w3.org/2005/Atom" rel="hub" href="http://pubsubhubbub.appspot.com" /><item>
      <title>Performance Testing with Httperf</title>
      <description>&lt;p&gt;If you need to do some performance testing of your web app, one tool that is pretty easy to use is &lt;a href="http://www.hpl.hp.com/research/linux/httperf/"&gt;httperf&lt;/a&gt;.  I recommend watching the &lt;a href="http://peepcode.com/products/benchmarking-with-httperf"&gt;Peepcode screencast on httperf&lt;/a&gt; to get some good tips on how to doing performance testing.  There is also some &lt;a href="http://httperf.comlore.com/"&gt;reading material on httperf created by Ted Bullock&lt;/a&gt; available.  These are great resources, but here's the quick and dirty on how to get httperf going.&lt;/p&gt;

&lt;p&gt;First, to install httperf, if you are using &lt;a href="http://www.macports.org"&gt;Macports&lt;/a&gt;, you can simply do &lt;code&gt;sudo port install httperf&lt;/code&gt;, which is what I did.  Alternatively, you can get httperf from the &lt;a href="http://www.hpl.hp.com/research/linux/httperf/download.php"&gt;httperf download page&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;Once you've got it installed, make sure the site you are testing on is running with all the production settings turned on.  The Peepcode screencast goes into detail about how to do that for a Rails app.  Then, if you are trying to test the &lt;code&gt;/profile&lt;/code&gt; page on &lt;code&gt;myfancysocialnetwork.com&lt;/code&gt;, you would run a command like this:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;httperf --server myfancysocialnetwork.com --port 80 --uri /profile --num-conns 100
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;This will hit the profile page 100 times and report back with statistics like the minimum response time, maximum response time and the average response time, including standard deviation.  You will certainly want to adjust the &lt;code&gt;--num-conns&lt;/code&gt; option based on the page you are testing.  If it's a pretty slow page with response times over a second or two, then 100 is probably ok.  If it's a more well behaved page that renders in a few hundred milliseconds, then a large number like 10000 might be better.  The goal is to make sure that it runs long enough to generate enough samples to make the results statistically relevant.  You'll also want to read the documentation/watch the screencast to get info on other options like &lt;code&gt;rate&lt;/code&gt; to create different kinds of test scenarios.&lt;/p&gt;&lt;div class="feedflare"&gt;
&lt;a href="http://feeds.feedburner.com/~ff/paulbarry?a=NVpNsLNVIyc:zLduvRBrlZ0:yIl2AUoC8zA"&gt;&lt;img src="http://feeds.feedburner.com/~ff/paulbarry?d=yIl2AUoC8zA" border="0"&gt;&lt;/img&gt;&lt;/a&gt; &lt;a href="http://feeds.feedburner.com/~ff/paulbarry?a=NVpNsLNVIyc:zLduvRBrlZ0:V_sGLiPBpWU"&gt;&lt;img src="http://feeds.feedburner.com/~ff/paulbarry?i=NVpNsLNVIyc:zLduvRBrlZ0:V_sGLiPBpWU" border="0"&gt;&lt;/img&gt;&lt;/a&gt; &lt;a href="http://feeds.feedburner.com/~ff/paulbarry?a=NVpNsLNVIyc:zLduvRBrlZ0:F7zBnMyn0Lo"&gt;&lt;img src="http://feeds.feedburner.com/~ff/paulbarry?i=NVpNsLNVIyc:zLduvRBrlZ0:F7zBnMyn0Lo" border="0"&gt;&lt;/img&gt;&lt;/a&gt; &lt;a href="http://feeds.feedburner.com/~ff/paulbarry?a=NVpNsLNVIyc:zLduvRBrlZ0:cGdyc7Q-1BI"&gt;&lt;img src="http://feeds.feedburner.com/~ff/paulbarry?d=cGdyc7Q-1BI" border="0"&gt;&lt;/img&gt;&lt;/a&gt;
&lt;/div&gt;</description>
      <pubDate>Tue, 10 Nov 2009 11:56:27 -0500</pubDate>
      <guid isPermaLink="false">urn:uuid:0d0e71ea-c0ce-401a-a661-72048f44eda2</guid>
      <author>mail@paulbarry.com (Paul Barry)</author>
      <link>http://feedproxy.google.com/~r/paulbarry/~3/NVpNsLNVIyc/performance-testing-with-httperf</link>
      <category>Technology</category>
            <category>Httperf</category>
          <feedburner:origLink>http://paulbarry.com/articles/2009/11/10/performance-testing-with-httperf</feedburner:origLink></item>
    <item>
      <title>How To Write A Spelling Corrector In Ruby</title>
      <description>&lt;p&gt;If you haven't seen it before, Peter Norvig has a &lt;a href="http://norvig.com/spell-correct.html"&gt;spelling corrector&lt;/a&gt; that is written
in just 21 lines of Python code (not counting blank lines and the import).  He also lists a few other implementations in other languages,
include &lt;a href="http://lojic.com/blog/2008/09/04/how-to-write-a-spelling-corrector-in-ruby/"&gt;one in Ruby&lt;/a&gt;.  The Ruby one was listed as 34 lines.  I was surprised that
it was that many lines more in Ruby, so I wanted to give it a try.  I didn't look at the 
Ruby solution first and here's what I came up with:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;require 'set'

def words(text)
  text.downcase.scan /[a-z]+/ 
end

def train(features)
  features.inject(Hash.new(1)){|model, f| model[f] += 1; model }
end

NWORDS = train(words(File.open('big.txt').read))

ALPHABET = 'abcdefghijklmnopqrstuvwxyz'.split //

def edits1(word)
  s = (0..word.size).map{|i| [word[0,i], word[i,word.size]]}
  deletes    = s.map{|a,b| !b.empty? ? a + b[1..-1] : nil}.compact
  transposes = s.map{|a,b| b.size &amp;gt; 1 ? a + b[1].chr + b[0].chr + b[2..-1] : nil}.compact
  replaces   = s.map{|a,b| !b.empty? ? ALPHABET.map{|c| a + c + b[1..-1]} : nil}.flatten.compact
  inserts    = s.map{|a,b| ALPHABET.map{|c| a + c + b}}.flatten
  Set.new(deletes + transposes + replaces + inserts)
end

def known_edits2(word)
  s = edits1(word).map do |e1| 
    edits1(e1).map{|e2| NWORDS.include?(e2) ? e2 : nil}.compact
  end.flatten
  s.empty? ? nil : Set.new(s)
end

def known(words)
  s = Set.new(words.find{|w| NWORDS.include?(w)})
  s.empty? ? nil : s
end

def correct(word)
  candidates = known([word]) || known(edits1(word)) || known_edits2(word) || [word]
  candidates.max{|a,b| NWORDS[a] &amp;lt;=&amp;gt; NWORDS[b] }
end
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;To run this, download the data file, put the code in a file called &lt;code&gt;spelling.rb&lt;/code&gt;, then start up IRB:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;$ wget http://norvig.com/big.txt
$ irb -r spelling -f --simple-prompt
&amp;gt;&amp;gt; correct "speling"
=&amp;gt; "spelling"
&amp;gt;&amp;gt; correct "korrecter"
=&amp;gt; "corrected"
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;This one weighs in at 30 lines.  I tried to do this as close to the Python implementation
as possible.  I also tried to use idiomatic Ruby.  You could shave the number of lines down
below 21, but it wouldn't meet any reasonable Ruby style guidelines.  I'm still probably 
cheating a little as a few of those lines are approaching 100 characters, but it's at least
reasonable, in my opinion.
Here are some things I noticed that caused the Ruby version to be longer or less clear:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;&lt;p&gt;end vs. significant indentation&lt;/p&gt;

&lt;p&gt;6 of the lines are just an end statement.  Python uses indentation to end methods, 
so the end statements aren't needed in Python.  This adds more lines, but has trade offs.
I actually really like the idea of significant indentation, it's one of the reasons
that I'm such a big fan of &lt;a href="http://haml-lang.com/"&gt;Haml&lt;/a&gt;.  But it falls down in certain places.
For example, Ruby has &lt;a href="http://ruby-doc.org/stdlib/libdoc/erb/rdoc/classes/ERB.html"&gt;Embedded Ruby&lt;/a&gt;, which looks similar to &lt;a href="http://java.sun.com/products/jsp/"&gt;JSP&lt;/a&gt; or &lt;a href="http://php.net"&gt;PHP&lt;/a&gt;, but it's actually trivial to implement the basic cases.  It truly is embedded Ruby, because the code between the &lt;code&gt;&amp;lt;% %&amp;gt;&lt;/code&gt; and &lt;code&gt;&amp;lt;%= %&amp;gt;&lt;/code&gt; tags is just ruby code.  You commonly see things like this:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;&amp;lt;% if logged_in? %&amp;gt;
  Welcome, &amp;lt;%= current_user.login %&amp;gt;
&amp;lt;% else %&amp;gt;
  Howdy Stranger!
&amp;lt;% end &amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;You can't do this in Python because of the lack of the end statement.  This is why
I'm surprised Haml was invented in Ruby and not Python.  In Python, it fits with the
language and is actually necessary, whereas in Ruby, significant indentation isn't
part of the language and ERB is actually pretty good.  There is a &lt;a href="http://github.com/braddunbar/pyhaml"&gt;Python port of HAML&lt;/a&gt;,
but I'm not sure how well that works or how widely it is used in the Python community.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;List Comprehensions vs. Blocks&lt;/p&gt;

&lt;p&gt;Python and Ruby, compared to C, Java, etc., have very powerful, concise syntax for
iterating through and transforming collections, but they are very different.
Python uses list comprehensions and Ruby uses blocks.  As you can see above, 
there are certain cases where list comprehensions are very compact.  List comprehensions
can have a guard, which is a little cleaner than the Ruby equivalent where you have to
return nil if the guard doesn't match and then compact that result.  Also,
when you want to iterate over two lists, you can do so with mutliple for statements,
whereas in Ruby you do nested blocks and then flatten the result.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Collection Slicing&lt;/p&gt;

&lt;p&gt;Python has a little cleaner, more consistent syntax for breaking up collections
into sub collections.  It also treats strings as a collection of characters more
consistently.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Truthiness&lt;/p&gt;

&lt;p&gt;In Python, many things are considered false.  I'm not sure what the entire list is,
but it seems to include empty collections (and therefore empty strings) as empty.
Since Ruby only treats &lt;code&gt;nil&lt;/code&gt; and &lt;code&gt;false&lt;/code&gt; as false, we have to return nil instead
of an empty set from the &lt;code&gt;known&lt;/code&gt; and &lt;code&gt;known_edits2&lt;/code&gt; methods, so that the series
of statements in the first line of the &lt;code&gt;correct&lt;/code&gt; method will work correctly.&lt;/p&gt;&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;In summary, in this case, the Python code is shorter and clearer, but it's pretty close.
I'm sure there are other code examples where the Ruby code would be a little shorter,
but I do think in general, Ruby and Python are going to be pretty close in terms of 
code clarity and number of lines of code.&lt;/p&gt;&lt;div class="feedflare"&gt;
&lt;a href="http://feeds.feedburner.com/~ff/paulbarry?a=LNcVj7_NMxQ:vqURVYUGri0:yIl2AUoC8zA"&gt;&lt;img src="http://feeds.feedburner.com/~ff/paulbarry?d=yIl2AUoC8zA" border="0"&gt;&lt;/img&gt;&lt;/a&gt; &lt;a href="http://feeds.feedburner.com/~ff/paulbarry?a=LNcVj7_NMxQ:vqURVYUGri0:V_sGLiPBpWU"&gt;&lt;img src="http://feeds.feedburner.com/~ff/paulbarry?i=LNcVj7_NMxQ:vqURVYUGri0:V_sGLiPBpWU" border="0"&gt;&lt;/img&gt;&lt;/a&gt; &lt;a href="http://feeds.feedburner.com/~ff/paulbarry?a=LNcVj7_NMxQ:vqURVYUGri0:F7zBnMyn0Lo"&gt;&lt;img src="http://feeds.feedburner.com/~ff/paulbarry?i=LNcVj7_NMxQ:vqURVYUGri0:F7zBnMyn0Lo" border="0"&gt;&lt;/img&gt;&lt;/a&gt; &lt;a href="http://feeds.feedburner.com/~ff/paulbarry?a=LNcVj7_NMxQ:vqURVYUGri0:cGdyc7Q-1BI"&gt;&lt;img src="http://feeds.feedburner.com/~ff/paulbarry?d=cGdyc7Q-1BI" border="0"&gt;&lt;/img&gt;&lt;/a&gt;
&lt;/div&gt;</description>
      <pubDate>Thu, 05 Nov 2009 02:06:58 -0500</pubDate>
      <guid isPermaLink="false">urn:uuid:d6ea3476-d4f5-47b8-b6a6-84bf45ffa850</guid>
      <author>mail@paulbarry.com (Paul Barry)</author>
      <link>http://feedproxy.google.com/~r/paulbarry/~3/LNcVj7_NMxQ/how-to-write-a-spelling-corrector-in-ruby</link>
      <category>Technology</category>
            <category>Python</category>
      <category>Ruby</category>
          <feedburner:origLink>http://paulbarry.com/articles/2009/11/05/how-to-write-a-spelling-corrector-in-ruby</feedburner:origLink></item>
    <item>
      <title>Ain't Nothing But A G Thang</title>
      <description>&lt;p&gt;You've probably seen more than a few articles on the web showing how to build a &lt;a href="http://rack.rubyforge.org"&gt;Rack&lt;/a&gt; app.  If not, here's &lt;a href="http://m.onkey.org/2008/11/17/ruby-on-rack-1"&gt;a good one to start with&lt;/a&gt;.  You'll quickly see that building a Rack app is really simple, which is why Rack is awesome, because it's simple.  But what about writing a Rack-compliant server?  Well it turns out that is pretty easy as well.&lt;/p&gt;

&lt;p&gt;I just pushed &lt;a href="http://github.com/pjb3/g_thang"&gt;a little Rack-compliant HTTP Server&lt;/a&gt; that I wrote using &lt;a href="http://www.ruby-doc.org/stdlib/libdoc/gserver/rdoc/classes/GServer.html"&gt;GServer&lt;/a&gt; to github.  The whole thing is less than 200 lines of code.  The core of it is short enough that I can explain how it works here.&lt;/p&gt;

&lt;p&gt;First, GServer.  GServer, which is short for "Generic Server" makes it pretty simple to create a multithreaded TCP Server.  Taking out some error handling code, here's what the GServer looks like for our Rack HTTP Server:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;module GThang
  class HttpServer &amp;lt; GServer

    attr_reader :port, :rack_app

    def initialize(options={})
      @port = options[:Port] || 8080
      @rack_app = options[:rack_app]
      super(@port)
    end

    def serve(socket)
      RackHandler.new(socket, rack_app, port).handle_request
    end

  end
end
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;So all there is to a GServer is basically a &lt;code&gt;serve&lt;/code&gt; method.  This will be called each time a client connects to the server.  The argument to the method is the client socket connection.  You read and write data from the socket as you see fit for your application.  As you can see here, we just pass the socket, along with the rack app and the port to the RackHandler initializer and then call &lt;code&gt;handle_request&lt;/code&gt; on that.  We'll look at how you setup the rack app in a minute, but first let's take a look at the meat of what the RackHandler does.  The &lt;code&gt;handle_request&lt;/code&gt; method looks like this:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;def handle_request
  return unless add_rack_variables_to_env
  return unless add_connection_info_to_env
  return unless add_request_line_info_to_env
  return unless add_headers_to_env
  send_response(app.call(env))
end
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;So what happens is the various &lt;code&gt;add_&lt;/code&gt; methods build up the &lt;a href="http://rack.rubyforge.org/doc/SPEC.html"&gt;rack environment&lt;/a&gt;.  Once the environment is ready, we call the rack app.  The rack app responds with the standard 3 element array, which we pass off to the send_response method, which writes the actual http response to the client.  Take a look at the full code for this on github for the details.&lt;/p&gt;

&lt;p&gt;Now the fun part is that we now have a fully functional HTTP server that is capable of acting as a file server or serving a Rails app.  All we have to do is give the &lt;code&gt;HttpServer&lt;/code&gt; the correct Rails app.  If you look in the examples, you see this for the file server:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;GThang::HttpServer.run(
  Rack::CommonLogger.new(
    Rack::Lint.new(
      Rack::Directory.new(root, Rack::File.new(root)))),
  :Port =&amp;gt; 8080)
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Now I choose to write it this way to make it clear what is actually happening.  You will normally see the builder DSL used to configure a rack app, which would look like this:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;use Rack::CommonLogger.new
use Rack::Lint.new
use Rack::Directory.new(root)
run Rack::File.new(root)
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;This is obviously a lot cleaner, but to understand how Rack works, you have to realize that all this is doing is what we see in the first example.  A Rack app with Rack middleware is simple a chain of apps that call the next app in the chain, possibly modifying the environment or response before or after the rest of the chain is called. &lt;/p&gt;

&lt;p&gt;So there you have it, beauty in simplicity.&lt;/p&gt;&lt;div class="feedflare"&gt;
&lt;a href="http://feeds.feedburner.com/~ff/paulbarry?a=O7WS7ar9h0Q:QQKmM7beOvo:yIl2AUoC8zA"&gt;&lt;img src="http://feeds.feedburner.com/~ff/paulbarry?d=yIl2AUoC8zA" border="0"&gt;&lt;/img&gt;&lt;/a&gt; &lt;a href="http://feeds.feedburner.com/~ff/paulbarry?a=O7WS7ar9h0Q:QQKmM7beOvo:V_sGLiPBpWU"&gt;&lt;img src="http://feeds.feedburner.com/~ff/paulbarry?i=O7WS7ar9h0Q:QQKmM7beOvo:V_sGLiPBpWU" border="0"&gt;&lt;/img&gt;&lt;/a&gt; &lt;a href="http://feeds.feedburner.com/~ff/paulbarry?a=O7WS7ar9h0Q:QQKmM7beOvo:F7zBnMyn0Lo"&gt;&lt;img src="http://feeds.feedburner.com/~ff/paulbarry?i=O7WS7ar9h0Q:QQKmM7beOvo:F7zBnMyn0Lo" border="0"&gt;&lt;/img&gt;&lt;/a&gt; &lt;a href="http://feeds.feedburner.com/~ff/paulbarry?a=O7WS7ar9h0Q:QQKmM7beOvo:cGdyc7Q-1BI"&gt;&lt;img src="http://feeds.feedburner.com/~ff/paulbarry?d=cGdyc7Q-1BI" border="0"&gt;&lt;/img&gt;&lt;/a&gt;
&lt;/div&gt;</description>
      <pubDate>Fri, 09 Oct 2009 01:05:52 -0400</pubDate>
      <guid isPermaLink="false">urn:uuid:0e87f392-abef-4844-8067-c2deb55c0408</guid>
      <author>mail@paulbarry.com (Paul Barry)</author>
      <link>http://feedproxy.google.com/~r/paulbarry/~3/O7WS7ar9h0Q/aint-nothing-but-a-g-thang</link>
      <category>Technology</category>
            <category>Rails</category>
      <category>Ruby</category>
      <category>Rack</category>
          <feedburner:origLink>http://paulbarry.com/articles/2009/10/09/aint-nothing-but-a-g-thang</feedburner:origLink></item>
    <item>
      <title>ExtJS On Rails</title>
      <description>&lt;p&gt;If you are looking to give &lt;a href="http://extjs.com"&gt;ExtJS&lt;/a&gt; a spin, I've created a &lt;a href="http://railscasts.com/episodes/148-app-templates-in-rails-2-3"&gt;Rails Application Template&lt;/a&gt; to setup a &lt;a href="http://rubyonrails.org"&gt;Rails&lt;/a&gt; app with ExtJS installed.  To use it, just do:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;rails -m http://tinyurl.com/extjs-rb my-extjs-app
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;To see a sample of this in use, take a look at this &lt;a href="http://github.com/pjb3/extjs_in_action_rails_chapter_1"&gt;Rails app&lt;/a&gt;.  It is a port of Chapter 1 of &lt;a href="http://manning.com/garcia/"&gt;ExtJS In Action&lt;/a&gt; to Rails.  Assuming you have Rails 2.3.2 installed, you should be able to download the Rails app from that git repo, run &lt;code&gt;script/server&lt;/code&gt; and then try out the app at http://localhost:3000.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;UPDATE:&lt;/strong&gt; This code actually refers to the code in the sample chapter on the &lt;a href="http://manning.com/garcia/"&gt;Manning website&lt;/a&gt;.  Chapter 1 in the latest version of the book has actually been completely re-written, so I've included the &lt;a href="http://github.com/pjb3/extjs_in_action_rails_chapter_1/raw/master/ExtJSinActionCh01.pdf"&gt;sample chapter in the git repo&lt;/a&gt;.  Also be sure to check out the author's blog which covers the development of the book.&lt;/p&gt;&lt;div class="feedflare"&gt;
&lt;a href="http://feeds.feedburner.com/~ff/paulbarry?a=6pnpIOTmfSQ:dOtuIY_wq3E:yIl2AUoC8zA"&gt;&lt;img src="http://feeds.feedburner.com/~ff/paulbarry?d=yIl2AUoC8zA" border="0"&gt;&lt;/img&gt;&lt;/a&gt; &lt;a href="http://feeds.feedburner.com/~ff/paulbarry?a=6pnpIOTmfSQ:dOtuIY_wq3E:V_sGLiPBpWU"&gt;&lt;img src="http://feeds.feedburner.com/~ff/paulbarry?i=6pnpIOTmfSQ:dOtuIY_wq3E:V_sGLiPBpWU" border="0"&gt;&lt;/img&gt;&lt;/a&gt; &lt;a href="http://feeds.feedburner.com/~ff/paulbarry?a=6pnpIOTmfSQ:dOtuIY_wq3E:F7zBnMyn0Lo"&gt;&lt;img src="http://feeds.feedburner.com/~ff/paulbarry?i=6pnpIOTmfSQ:dOtuIY_wq3E:F7zBnMyn0Lo" border="0"&gt;&lt;/img&gt;&lt;/a&gt; &lt;a href="http://feeds.feedburner.com/~ff/paulbarry?a=6pnpIOTmfSQ:dOtuIY_wq3E:cGdyc7Q-1BI"&gt;&lt;img src="http://feeds.feedburner.com/~ff/paulbarry?d=cGdyc7Q-1BI" border="0"&gt;&lt;/img&gt;&lt;/a&gt;
&lt;/div&gt;</description>
      <pubDate>Wed, 23 Sep 2009 23:09:41 -0400</pubDate>
      <guid isPermaLink="false">urn:uuid:de4b6e57-b7bd-47b6-9812-4a6bddd9da33</guid>
      <author>mail@paulbarry.com (Paul Barry)</author>
      <link>http://feedproxy.google.com/~r/paulbarry/~3/6pnpIOTmfSQ/extjs-on-rails</link>
      <category>Technology</category>
            <category>Rails</category>
      <category>Javascript</category>
      <category>ExtJS</category>
          <feedburner:origLink>http://paulbarry.com/articles/2009/09/23/extjs-on-rails</feedburner:origLink></item>
    <item>
      <title>Why Rails 3 Will Require Ruby 1.8.7</title>
      <description>&lt;p&gt;This past weekend I attended the &lt;a href="http://windycityrails.org"&gt;Windy City Rails&lt;/a&gt; conference.  It was in a great location in the heart of downtown Chicago and seemed to have a pretty good turn out.  There were many great talks but this blog post will be focusing on a specific talk, and more precisely, part of a talk.  &lt;a href="http://yehudakatz.com"&gt;Yehuda Katz&lt;/a&gt; gave a talk on the status of Rails 3.  One of the things that he mentioned, which you may have already heard, is that Rails 3 will require Ruby 1.8.7 or higher, dropping support for Ruby 1.8.6.  He also mentioned why they are doing this and I found the reason to be interesting.  It's not that the Rails core team wants to try to take advantage of any specific new features, it's that Ruby 1.8.6 has a bug which has been fixed in 1.8.7.&lt;/p&gt;

&lt;p&gt;To see the bug in action, I recommend that you install &lt;a href="http://rvm.beginrescueend.com"&gt;Ruby Version Manager (rvm)&lt;/a&gt;.  Once you have installed rvm, install Ruby 1.8.6 and Ruby 1.8.7.  &lt;/p&gt;

&lt;p&gt;The bug is that in Ruby 1.8.6, the &lt;code&gt;hash&lt;/code&gt; method for &lt;code&gt;Hash&lt;/code&gt; doesn't generate the same hash code for different hashes with the same values:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;$ rvm use 1.8.6
$ irb
ruby-1.8.6-p383 &amp;gt; {:x =&amp;gt; 1}.hash
 =&amp;gt; 1313270 
ruby-1.8.6-p383 &amp;gt; {:x =&amp;gt; 1}.hash
 =&amp;gt; 1307060 
ruby-1.8.6-p383 &amp;gt; {:x =&amp;gt; 1}.hash
 =&amp;gt; 1296440 
ruby-1.8.6-p383 &amp;gt; {:x =&amp;gt; 1} == {:x =&amp;gt; 1}
 =&amp;gt; true
ruby-1.8.6-p383 &amp;gt; h = {{:x =&amp;gt; 1} =&amp;gt; "foo"}
 =&amp;gt; {{:x=&amp;gt;1}=&amp;gt;"foo"} 
ruby-1.8.6-p383 &amp;gt; h[{:x =&amp;gt; 1}]
 =&amp;gt; nil
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;So despite the fact that two hashes have the same values and are equal, you can't use a hash as a key in a hash, because that depends on the hash codes of the values being equal, which they aren't.  This is fixed in Ruby 1.8.7:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;$ rvm use 1.8.7
$ irb
ruby-1.8.7-p174 &amp;gt; {:x =&amp;gt; 1}.hash
 =&amp;gt; 327875 
ruby-1.8.7-p174 &amp;gt; {:x =&amp;gt; 1}.hash
 =&amp;gt; 327875 
ruby-1.8.7-p174 &amp;gt; {:x =&amp;gt; 1}.hash
 =&amp;gt; 327875 
ruby-1.8.7-p174 &amp;gt; {:x =&amp;gt; 1} == {:x =&amp;gt; 1}
 =&amp;gt; true 
ruby-1.8.7-p174 &amp;gt; h = {{:x =&amp;gt; 1} =&amp;gt; "foo"}
 =&amp;gt; {{:x=&amp;gt;1}=&amp;gt;"foo"} 
ruby-1.8.7-p174 &amp;gt; h[{:x =&amp;gt; 1}]
 =&amp;gt; "foo"
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;This is important because you could use a hash cache calls to a method that expects a hash, but only if you can use a hash as the key.  This is one of the main reasons Rails 3 is going to require 1.8.7.  They could make it worth for both 1.8.6 and 1.8.7 and higher, but why?  It simplifies things to just require that you upgrade to Ruby 1.8.7 to use Rails 3.  If you are using 1.8.6, this is probably a gotcha that you should be aware of.&lt;/p&gt;&lt;div class="feedflare"&gt;
&lt;a href="http://feeds.feedburner.com/~ff/paulbarry?a=7nZBBTtHpiI:YRRaIkTLanQ:yIl2AUoC8zA"&gt;&lt;img src="http://feeds.feedburner.com/~ff/paulbarry?d=yIl2AUoC8zA" border="0"&gt;&lt;/img&gt;&lt;/a&gt; &lt;a href="http://feeds.feedburner.com/~ff/paulbarry?a=7nZBBTtHpiI:YRRaIkTLanQ:V_sGLiPBpWU"&gt;&lt;img src="http://feeds.feedburner.com/~ff/paulbarry?i=7nZBBTtHpiI:YRRaIkTLanQ:V_sGLiPBpWU" border="0"&gt;&lt;/img&gt;&lt;/a&gt; &lt;a href="http://feeds.feedburner.com/~ff/paulbarry?a=7nZBBTtHpiI:YRRaIkTLanQ:F7zBnMyn0Lo"&gt;&lt;img src="http://feeds.feedburner.com/~ff/paulbarry?i=7nZBBTtHpiI:YRRaIkTLanQ:F7zBnMyn0Lo" border="0"&gt;&lt;/img&gt;&lt;/a&gt; &lt;a href="http://feeds.feedburner.com/~ff/paulbarry?a=7nZBBTtHpiI:YRRaIkTLanQ:cGdyc7Q-1BI"&gt;&lt;img src="http://feeds.feedburner.com/~ff/paulbarry?d=cGdyc7Q-1BI" border="0"&gt;&lt;/img&gt;&lt;/a&gt;
&lt;/div&gt;</description>
      <pubDate>Mon, 14 Sep 2009 19:50:21 -0400</pubDate>
      <guid isPermaLink="false">urn:uuid:82a3a695-8c2f-45ea-8332-a65b8dcc9ea9</guid>
      <author>mail@paulbarry.com (Paul Barry)</author>
      <link>http://feedproxy.google.com/~r/paulbarry/~3/7nZBBTtHpiI/why-rails-3-will-require-ruby-1-8-7</link>
      <category>Technology</category>
            <category>Rails</category>
      <category>Ruby</category>
          <feedburner:origLink>http://paulbarry.com/articles/2009/09/14/why-rails-3-will-require-ruby-1-8-7</feedburner:origLink></item>
    <item>
      <title>Infinite Recursion</title>
      <description>&lt;p&gt;A few days ago I posted an article on &lt;a href="http://paulbarry.com/articles/2009/08/30/tail-call-optimization"&gt;Tail Call Optimization&lt;/a&gt;.  One really quick way to determine if any language/VM/interpreter performs Tail Call Optimization (TCO) is to write a function that calls itself, in other words, creating an infinitely recursive function.  If the function just runs forever and doesn't return, the interpreter is doing TCO, otherwise you will get some sort of stack overflow error.  So I decided to test a variety of languages to see what happens when you write an infinitely recursive function.  First up is ruby:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;def forever
  forever
end

forever
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;It was no surprise to me that running this results in this error:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;run.rb:2:in `forever': stack level too deep (SystemStackError)
    from run.rb:2:in `forever'
    from run.rb:5
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Ruby doesn't have TCO, I knew that.  Next up, Python:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;def forever(): forever()

forever()
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;This has a similar result, but the stack track is a little more revealing:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;Traceback (most recent call last):
  File "run.py", line 3, in &amp;lt;module&amp;gt;
    forever()
  File "run.py", line 1, in forever
    def forever(): forever()
  File "run.py", line 1, in forever
    def forever(): forever()
...
  File "run.py", line 1, in forever
    def forever(): forever()
  File "run.py", line 1, in forever
    def forever(): forever()
RuntimeError: maximum recursion depth exceeded
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;This shows pretty clearly what is going on, the stack frames are pilling up and eventually it gets to the point where the Python interpreter says enough is enough.  Interestingly enough, this &lt;a href="http://mail.python.org/pipermail/python-dev/2004-July/046171.html"&gt;mailing list thread&lt;/a&gt; shows that it's completely feasible to add TCO to Python and Guido just doesn't want to add it.&lt;/p&gt;

&lt;p&gt;JavaScript is no surprise either, but we can write our infinitely recursive function with an interesting little twist:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;(function(){ arguments.callee() })()
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Yes that's right, it's an anonymous recursive function!  Running this with SpiderMonkey results in &lt;code&gt;InternalError: too much recursion&lt;/code&gt;.  So how about Java:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;class Run {
  public static void main(String[] args) {
    Run run = new Run();
    run.forever();
  }

  public void forever() {
    forever();
  }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;The stack trace for this one looks a bit like the Python one, we see a stack frame for each iteration:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;Exception in thread "main" java.lang.StackOverflowError
    at Run.forever(Run.java:8)
    at Run.forever(Run.java:8)
    at Run.forever(Run.java:8)
    at Run.forever(Run.java:8)
...
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;So that means no TCO on the JVM.  So Scala doesn't have TCO, right?&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;def forever : Unit = forever

forever
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Wrong.  This one runs forever.  Scala does TCO with some bytecode tricks which &lt;a href="http://stronglytypedblog.blogspot.com/2009/08/scala-tail-recursion.html"&gt;Nick Wiedenbrueck explains really well in this blog post&lt;/a&gt;.  &lt;/p&gt;

&lt;p&gt;Clojure is a functional Lisp saddled with the problem of no-TCO on the JVM, but it gets around it in a slightly different way than Scala.  If you write a tail recursive function like this:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;(defn forever [] (forever))
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;You will get a &lt;code&gt;java.lang.StackOverflowError&lt;/code&gt; just as you do in Java.  Instead, Clojure provides a language level feature to do recursion:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;(defn forever [] (recur))
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Calling &lt;code&gt;recur&lt;/code&gt; in the function makes it call the function again.  &lt;code&gt;recur&lt;/code&gt; also checks that it is in the tail recursive position, which ends up being an interesting feature because you have to explicitly say "I expect this to do TCO".  In other languages that do it transparently, you might think TCO is happening, but it might not be and you won't find out until you get a stack overflow error.  Also, this construct allows us to have recursive anonymous functions:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;((fn [] (recur)))
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Erlang, being a function language, has TCO as well:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;-module(run).

-compile(export_all).

forever() -&amp;gt;
  forever().
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Now one thing all of these functional languages that have TCO; Scala, Clojure and Erlang, all have in common is that while the infinitely recursive function runs, it essentially does nothing, but it will peg your CPU utilization to nearly 100%.  This next language, Haskell, being the mother of all functional langauges, of course has TCO.  Here's the function:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;forever = forever
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Yes, that's a function.  And if you call it with &lt;code&gt;forever&lt;/code&gt;, it just sits there and runs forever.  But here's the crazy thing, it uses no CPU.  My guess is that it has to do with lazy evaluation, but I'm not sure.  Any ideas?&lt;/p&gt;&lt;div class="feedflare"&gt;
&lt;a href="http://feeds.feedburner.com/~ff/paulbarry?a=2RCfQnZ7zeY:ONfd0xuMRtk:yIl2AUoC8zA"&gt;&lt;img src="http://feeds.feedburner.com/~ff/paulbarry?d=yIl2AUoC8zA" border="0"&gt;&lt;/img&gt;&lt;/a&gt; &lt;a href="http://feeds.feedburner.com/~ff/paulbarry?a=2RCfQnZ7zeY:ONfd0xuMRtk:V_sGLiPBpWU"&gt;&lt;img src="http://feeds.feedburner.com/~ff/paulbarry?i=2RCfQnZ7zeY:ONfd0xuMRtk:V_sGLiPBpWU" border="0"&gt;&lt;/img&gt;&lt;/a&gt; &lt;a href="http://feeds.feedburner.com/~ff/paulbarry?a=2RCfQnZ7zeY:ONfd0xuMRtk:F7zBnMyn0Lo"&gt;&lt;img src="http://feeds.feedburner.com/~ff/paulbarry?i=2RCfQnZ7zeY:ONfd0xuMRtk:F7zBnMyn0Lo" border="0"&gt;&lt;/img&gt;&lt;/a&gt; &lt;a href="http://feeds.feedburner.com/~ff/paulbarry?a=2RCfQnZ7zeY:ONfd0xuMRtk:cGdyc7Q-1BI"&gt;&lt;img src="http://feeds.feedburner.com/~ff/paulbarry?d=cGdyc7Q-1BI" border="0"&gt;&lt;/img&gt;&lt;/a&gt;
&lt;/div&gt;</description>
      <pubDate>Wed, 02 Sep 2009 01:17:31 -0400</pubDate>
      <guid isPermaLink="false">urn:uuid:4e543642-b8d8-4147-a713-a89fa110d181</guid>
      <author>mail@paulbarry.com (Paul Barry)</author>
      <link>http://feedproxy.google.com/~r/paulbarry/~3/2RCfQnZ7zeY/infinite-recursion</link>
      <category>Technology</category>
            <category>Haskell</category>
      <category>TCO</category>
      <category>Erlang</category>
      <category>Python</category>
      <category>Clojure</category>
      <category>Javascript</category>
      <category>Ruby</category>
      <category>FunctionalProgramming</category>
      <category>TailCallOptimization</category>
      <category>Scala</category>
      <category>Java</category>
          <feedburner:origLink>http://paulbarry.com/articles/2009/09/02/infinite-recursion</feedburner:origLink></item>
    <item>
      <title>Active Record Random</title>
      <description>&lt;p&gt;Are you looking for a way to select a random record that plays nice with named scope in your Rails app?  Throw this into &lt;code&gt;config/initializers/active_record_random.rb&lt;/code&gt;:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;class ActiveRecord::Base
  def self.random
    if (c = count) &amp;gt; 0
      first(:offset =&amp;gt; rand(c)) 
    end
  end
end
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Now you can call &lt;code&gt;random&lt;/code&gt; the same way you would call &lt;code&gt;first&lt;/code&gt; or &lt;code&gt;all&lt;/code&gt;.  That means you can do &lt;code&gt;Widget.random&lt;/code&gt; to get a random widget or &lt;code&gt;Widget.fancy.random&lt;/code&gt;, to get a random fancy widget, assuming you have defined the fancy named scope for &lt;code&gt;Widget&lt;/code&gt;.&lt;/p&gt;&lt;div class="feedflare"&gt;
&lt;a href="http://feeds.feedburner.com/~ff/paulbarry?a=KpoICRhvxfM:y_8AV5Pi4zM:yIl2AUoC8zA"&gt;&lt;img src="http://feeds.feedburner.com/~ff/paulbarry?d=yIl2AUoC8zA" border="0"&gt;&lt;/img&gt;&lt;/a&gt; &lt;a href="http://feeds.feedburner.com/~ff/paulbarry?a=KpoICRhvxfM:y_8AV5Pi4zM:V_sGLiPBpWU"&gt;&lt;img src="http://feeds.feedburner.com/~ff/paulbarry?i=KpoICRhvxfM:y_8AV5Pi4zM:V_sGLiPBpWU" border="0"&gt;&lt;/img&gt;&lt;/a&gt; &lt;a href="http://feeds.feedburner.com/~ff/paulbarry?a=KpoICRhvxfM:y_8AV5Pi4zM:F7zBnMyn0Lo"&gt;&lt;img src="http://feeds.feedburner.com/~ff/paulbarry?i=KpoICRhvxfM:y_8AV5Pi4zM:F7zBnMyn0Lo" border="0"&gt;&lt;/img&gt;&lt;/a&gt; &lt;a href="http://feeds.feedburner.com/~ff/paulbarry?a=KpoICRhvxfM:y_8AV5Pi4zM:cGdyc7Q-1BI"&gt;&lt;img src="http://feeds.feedburner.com/~ff/paulbarry?d=cGdyc7Q-1BI" border="0"&gt;&lt;/img&gt;&lt;/a&gt;
&lt;/div&gt;</description>
      <pubDate>Sun, 30 Aug 2009 22:28:21 -0400</pubDate>
      <guid isPermaLink="false">urn:uuid:3bf18d31-98be-4983-b9d2-8cdab1974697</guid>
      <author>mail@paulbarry.com (Paul Barry)</author>
      <link>http://feedproxy.google.com/~r/paulbarry/~3/KpoICRhvxfM/active-record-random</link>
      <category>Technology</category>
            <category>Rails</category>
      <category>NamedScope</category>
      <category>Ruby</category>
      <category>RubyOnRails</category>
          <feedburner:origLink>http://paulbarry.com/articles/2009/08/30/active-record-random</feedburner:origLink></item>
    <item>
      <title>Tail Call Optimization</title>
      <description>&lt;p&gt;Tail-Call Optimization (a.k.a Tail Recursion) is a technique often used in functional programming languages that promotes the use of recursion rather than imperative loops to perform iterative calculations.  When I say imperative loops, I mean using a local variable that you change the value of as you calculate each step of the iteration.  A generic term for this kind of variable is an accumulator, because it accumulates the new value at each step of the iteration.&lt;/p&gt;

&lt;p&gt;Let's say you are hoping to become the &lt;a href="http://megamillions.com/mcenter/pressrelease.asp?newsID=58753620-0362-4344-9E63-8FEA4449CFD6"&gt;next mega millionare&lt;/a&gt; and you want to know your odds of winning.  Most lotteries consist of something like pick 5 numbers between 1 and 50.  Each number can only come up once in the drawing and if you get all 5 numbers right, you win.  The order isn't significant, you just need to get the 5 numbers.&lt;/p&gt;

&lt;p&gt;Here's a JavaScript function written in an imperative style to get your odds:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;function odds(n, p) {
  var acc = 1
  for(var i = 0; i &amp;lt; n; i++) {
    acc *= (n - i) / (p - i)
  }
  return acc
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;The parameters are n, the number of numbers you have to pick and p is the upper limit of all possible numbers to choose from.  So the odds for the "pick 5 of 50" are &lt;code&gt;4.71974173573222e-7&lt;/code&gt;.  That's expressed in decimal in scientific notation.  To get the more traditional looking "1 in whatever" number, you simply take the inverse, &lt;code&gt;1/4.71974173573222e-7&lt;/code&gt;, which is 1 in 2,118,760.&lt;/p&gt;

&lt;p&gt;The mega millions actually has a twist to it with the powerball.  You pick 5 numbers of of 56 and then 1 number out of 46.  A number that comes up in the first 5 can come up as the powerball.  So that means the mega millions odds are &lt;code&gt;1/(odds(5,56) * odds(1,46))&lt;/code&gt;, which is 1 in 175,711,536.&lt;/p&gt;

&lt;p&gt;One problem with our function is that it uses a mutable local variable and &lt;a href="http://www.oreillynet.com/ruby/blog/2006/03/transformation.html"&gt;mutable local variables are evil&lt;/a&gt;.  Some functional languages, such as &lt;a href="http://clojure.org"&gt;Clojure&lt;/a&gt;, &lt;a href="http://haskell.org"&gt;Haskell&lt;/a&gt; and &lt;a href="http://erlang.org"&gt;Erlang&lt;/a&gt;, don't even allow you to use mutable local variables.  So how can we do it without the accumulator?  The answer is recursion:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;function odds(n, p) {
  if(n == 0) {
    return 1
  } else {
    return (n / p) * odds(n - 1, p - 1)
  }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;This is a pretty elegant implementation of the function because it mirrors how you might think of the problem.  This still works great but it breaks down if we try to calculate the odds of much larger numbers.  For example, if you try to calculate the odds of picking 10,000 numbers out of 100,000 numbers with &lt;code&gt;odds(10000, 100000)&lt;/code&gt;, you will some kind of stack overflow / too much recursion error, depending on your interpreter.&lt;/p&gt;

&lt;p&gt;The reason for this becomes clear when you walk through how the interpreter calculates the value.  When you say &lt;code&gt;odds(5, 56)&lt;/code&gt;, the return value is &lt;code&gt;(5/56) * odds(4, 55)&lt;/code&gt;.  The interpreter cannot evaluate this expression until &lt;code&gt;odds(4, 55)&lt;/code&gt; is calculated.  So the series of expressions that get evaluated are:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;odds(5, 56)
(5/56) * odds(4, 55)
(5/56) * (4/55) * odds(3, 54)
(5/56) * (4/55) * (3/54) * odds(2, 53)
(5/56) * (4/55) * (3/54) * (2/53) * odds(1, 52)
(5/56) * (4/55) * (3/54) * (2/53) * (1/52) * odds(0, 51)
(5/56) * (4/55) * (3/54) * (2/53) * (1/52) * 1
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;As you can see, the lines get wider as the recursive calls build up.  This is representative of how the interpreter works.  As each recursive call is added, memory is temporarily used up.  Once there are no more recursive calls, it can start evaluating the expressions and freeing up the memory.  This works fine, but if you are performing the calculation on a large number that generates more recursive calls than the interpreter can hold in memory, then &lt;a href="http://www.youtube.com/watch?v=W45DRy7M1no"&gt;boom goes the dynamite&lt;/a&gt;.  Most interpreters push each recursive call onto a stack, so when the stack runs out of memory, you get a &lt;a href="http://en.wikipedia.org/wiki/Stack_overflow"&gt;Stack Overflow&lt;/a&gt; error.&lt;/p&gt;

&lt;p&gt;So how can we possibly do calculations like this recursively?  The answer to that is tail-call optimization.  In order to do this, we are going to have to bring back the accumulator, but in this case, it's not going to be a mutable local variable, instead it will be a parameter to the function.  Since we don't want callers of our function to have to pass in the initial value of the accumulator, we will define two functions, one "public" and the other "private":&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;(function(){
  var odds1 = function(n, p, acc) {
    if(n == 0) {
      return acc
    } else {
      return odds1(n - 1, p - 1, (n / p) * acc)
    }
  }

  odds = function(n, p) {
    return odds1(n, p, 1)
  }  
})()
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;JavaScript doesn't really have a public/private mechanism, but we can use closures to accomplish the same thing.  First this is an anonymous function that we create and then call immediately after we create it.  This just gives us a local scope.  If we didn't have this outer wrapping function, all variables would be global.  Then we define a function and assign it to a local variable called &lt;code&gt;odds1&lt;/code&gt;.  Next we define a function and assign it to a global variable &lt;code&gt;odds&lt;/code&gt;.  The function &lt;code&gt;odds&lt;/code&gt; is "closed over" the variable &lt;code&gt;odds1&lt;/code&gt;, which means that it can reference that variable, even when the odds function is called outside the context it is defined in, even though the &lt;code&gt;odds1&lt;/code&gt; variable will not be directly available from that context.  To test this out, simply try to print the value of &lt;code&gt;odds&lt;/code&gt; and then &lt;code&gt;odds1&lt;/code&gt; from outside of this outer function.  The interpreter will say &lt;code&gt;odds&lt;/code&gt; is a function but it will say &lt;code&gt;odds1&lt;/code&gt; is undefined, which means &lt;code&gt;odds1&lt;/code&gt; is effectively private.&lt;/p&gt;

&lt;p&gt;So when someone calls our function &lt;code&gt;odds&lt;/code&gt;, it calls &lt;code&gt;odds1&lt;/code&gt; with an initial value of 1 for the accumulator and then returns that value.  Since JavaScript does not have tail-call optimization, that is what actually happens.  &lt;code&gt;odds&lt;/code&gt; waits for the value of &lt;code&gt;odds1&lt;/code&gt; to be calculated and then returns that value once it gets one.  If you look at &lt;code&gt;odds1&lt;/code&gt;, it does the same thing, returning the value from a recursive call to itself.  And since JavaScript does not have tail-call optimization, this still results in some sort of stack overflow with large enough values for &lt;code&gt;n&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;What a tail-call optimized language does is realize that the statement &lt;code&gt;return odds1(n, p, 1)&lt;/code&gt; is saying call the function &lt;code&gt;odds1&lt;/code&gt; with the arguments &lt;code&gt;n&lt;/code&gt;, &lt;code&gt;p&lt;/code&gt; and 1 and then return value.  What the language can do is have the &lt;code&gt;odds&lt;/code&gt; function return immediately and tell the caller to call &lt;code&gt;odds1&lt;/code&gt; with the arguments &lt;code&gt;n&lt;/code&gt;, &lt;code&gt;p&lt;/code&gt; and 1 in order to get the value.  The important distinction between these two is that the call to &lt;code&gt;odds&lt;/code&gt; is eliminated from the call stack before &lt;code&gt;odds1&lt;/code&gt; is called.  &lt;/p&gt;

&lt;p&gt;The way I think of it is tail-call optimization almost like an HTTP redirect.  The call to &lt;code&gt;odds&lt;/code&gt; is simply redirected to &lt;code&gt;odds1&lt;/code&gt;.  Once &lt;code&gt;odds&lt;/code&gt; has issued a redirect, it's out of the equation.  Without tail-call optimization, the call to &lt;code&gt;odds&lt;/code&gt; has to make a call to &lt;code&gt;odds1&lt;/code&gt;.  While the call it &lt;code&gt;odds1&lt;/code&gt; is being processed, both &lt;code&gt;odds&lt;/code&gt; and the original caller are waiting for the response.  If the chain of calls becomes to long, the call stack overflows.&lt;/p&gt;

&lt;p&gt;This same idea can be applied to the recursive calls within &lt;code&gt;odds1&lt;/code&gt; itself.  When &lt;code&gt;odds(5, 56)&lt;/code&gt; is called, it will in turn call &lt;code&gt;odds1(5, 56, 1)&lt;/code&gt;.  In &lt;code&gt;odds1&lt;/code&gt;, the last thing it will do is call itself recursively, but this time the parameters will be &lt;code&gt;odds1(4, 55, (5/56))&lt;/code&gt;.  A function that returns a recursive call to itself as the last thing it does is said to be &lt;a href="http://en.wikipedia.org/wiki/Tail_recursion"&gt;tail-recursive&lt;/a&gt;.  Our original recursive &lt;code&gt;odds&lt;/code&gt; function was not tail-recursive, because it needed to multiple the value of the recursive call by a value after the recursive call returned.  &lt;/p&gt;

&lt;p&gt;Since &lt;code&gt;odds1&lt;/code&gt; is tail-recursive, the call to &lt;code&gt;odds1(5, 56, 1)&lt;/code&gt; can just say call &lt;code&gt;odds1(4, 55, (5/56))&lt;/code&gt; instead and take itself off the call stack.  The series of calls looks like this:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;odds(5, 56))
odds1(5, 56, 1)
odds1(4, 55, 5/56)
odds1(3, 54, 1/154)
odds1(2, 53, 1/2772)
odds1(1, 52, 1/73458)
odds1(0, 51, 1/3819816)
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;The value of the accumulator in each of these calls is the result of the multiplication of the previous value and the current n divided by the current p.  As you can see here, the width of the expression doesn't increase for each iteration (well, except a little bit for the width of the accumulator value).  If the interpreter actually evaluates the expressions this way there is no way to cause a stack overflow error.  You can evaluate any of these expressions independently from the others, assuming you make &lt;code&gt;odds1&lt;/code&gt; public.&lt;/p&gt;

&lt;p&gt;To see this in action, you will have to use a language with an interpreter that does tail-call optimization.  Erlang is one such language.  First let's write a non-tail-recursive implementation of the odds function:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;-module(lotto).

-compile(export_all).

odds(0, _) -&amp;gt; 1;
odds(N, P) -&amp;gt; (N / P) * odds(N - 1, P - 1).
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Now we can see that our function works using the Erlang interactive shell:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;$ erlc lotto.erl
$ erl
Erlang R13B01 (erts-5.7.2) [source] [smp:2:2] [rq:2] [async-threads:0] [hipe] [kernel-poll:false]

Eshell V5.7.2  (abort with ^G)
1&amp;gt; lotto:odds(5,56).
2.6179271462290333e-7
2&amp;gt; 1/(lotto:odds(5,56) * lotto:odds(1,46)).
175711536.0
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;So it turns out that &lt;a href="http://erl.nfshost.com/2009/02/18/erlang-surprises-me/"&gt;you have to work really hard to get the Erlang VM to blow the stack on a non-tail-recursive call&lt;/a&gt;, but I managed to get an error &lt;code&gt;eheap_alloc: Cannot allocate 1140328500 bytes of memory (of type "old_heap").&lt;/code&gt; by trying to evaluate &lt;code&gt;lotto:odds(100000000, 1000000000).&lt;/code&gt;.  Let's re-write the function to be tail-recursive:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;-module(lotto).

-export([odds/2]).

odds(N, P) -&amp;gt; odds(N, P, 1).

odds(0, _, Acc) -&amp;gt; Acc;
odds(N, P, Acc) -&amp;gt; odds(N - 1, P - 1, (N / P) * Acc).
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;You can see that Erlang gives us a couple of language features to make this a little cleaner than the JavaScript function.  First, functions with different arities are completely different functions.  Arity is the number of arguments to a function.  So here we have two functions, &lt;code&gt;odds/2&lt;/code&gt; and &lt;code&gt;odds/3&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;Also, pattern matching is used to distinguish the two cases.  The &lt;code&gt;odds/3&lt;/code&gt; function has two cases, one where N is 0 and the other to handle all other cases.&lt;/p&gt;

&lt;p&gt;Lastly, the export directive at the top says that we only want the &lt;code&gt;odds/2&lt;/code&gt; function to be public, so the &lt;code&gt;odds/3&lt;/code&gt; function is private to this module.&lt;/p&gt;

&lt;p&gt;With this definition of the odds function, if we try to evaluate &lt;code&gt;lotto:odds(100000000, 1000000000).&lt;/code&gt;, it will complete, although it will take some time.  The original recursive odds function takes &lt;em&gt;O(n)&lt;/em&gt; time and &lt;em&gt;O(n)&lt;/em&gt; space, which means the amount of time and the amount of space it takes to evaluate the function increases linearly for larger values of n.  Due to tail-call optimization, the function still takes &lt;em&gt;O(n)&lt;/em&gt; time, but takes &lt;em&gt;O(1)&lt;/em&gt; space, which means the amount of time it takes to evaluate the function still increases linearly with larger values for n increases, but the function always operates in a constant amount of space, regardless of the size of n.&lt;/p&gt;

&lt;p&gt;So to summarize, tail-call optimization is a technique that is performed by the compiler/interpreter, usually transparently, to make tail-recursive functions operate in constant space.  This is a necessary optimization in order to be able to use recursive functions to perform iterative calculations as opposed to imperative functions that use mutable local variables.&lt;/p&gt;&lt;div class="feedflare"&gt;
&lt;a href="http://feeds.feedburner.com/~ff/paulbarry?a=qKSTBzkVSI4:TKtvPIlQDX0:yIl2AUoC8zA"&gt;&lt;img src="http://feeds.feedburner.com/~ff/paulbarry?d=yIl2AUoC8zA" border="0"&gt;&lt;/img&gt;&lt;/a&gt; &lt;a href="http://feeds.feedburner.com/~ff/paulbarry?a=qKSTBzkVSI4:TKtvPIlQDX0:V_sGLiPBpWU"&gt;&lt;img src="http://feeds.feedburner.com/~ff/paulbarry?i=qKSTBzkVSI4:TKtvPIlQDX0:V_sGLiPBpWU" border="0"&gt;&lt;/img&gt;&lt;/a&gt; &lt;a href="http://feeds.feedburner.com/~ff/paulbarry?a=qKSTBzkVSI4:TKtvPIlQDX0:F7zBnMyn0Lo"&gt;&lt;img src="http://feeds.feedburner.com/~ff/paulbarry?i=qKSTBzkVSI4:TKtvPIlQDX0:F7zBnMyn0Lo" border="0"&gt;&lt;/img&gt;&lt;/a&gt; &lt;a href="http://feeds.feedburner.com/~ff/paulbarry?a=qKSTBzkVSI4:TKtvPIlQDX0:cGdyc7Q-1BI"&gt;&lt;img src="http://feeds.feedburner.com/~ff/paulbarry?d=cGdyc7Q-1BI" border="0"&gt;&lt;/img&gt;&lt;/a&gt;
&lt;/div&gt;</description>
      <pubDate>Sun, 30 Aug 2009 16:20:06 -0400</pubDate>
      <guid isPermaLink="false">urn:uuid:de4af569-9dde-4539-b612-393b1f593cab</guid>
      <author>mail@paulbarry.com (Paul Barry)</author>
      <link>http://feedproxy.google.com/~r/paulbarry/~3/qKSTBzkVSI4/tail-call-optimization</link>
      <category>Technology</category>
            <category>Haskell</category>
      <category>TCO</category>
      <category>Erlang</category>
      <category>Clojure</category>
      <category>Javascript</category>
      <category>FunctionalProgramming</category>
      <category>TailCallOptimization</category>
      <category>Recursion</category>
          <feedburner:origLink>http://paulbarry.com/articles/2009/08/30/tail-call-optimization</feedburner:origLink></item>
    <item>
      <title>Currying and Partial Function Application</title>
      <description>&lt;p&gt;Two related but different concepts that you will run into when doing functional programming are &lt;a href="http://en.wikipedia.org/wiki/Currying"&gt;currying&lt;/a&gt; and partial function application.  People often don't understand the different between the two, I didn't myself until recently, but I think I've got a handle on in now.  Currying and partial function application are two different things, but they go together like peanut butter and jelly. &lt;/p&gt;

&lt;p&gt;First, let's start with currying.  Currying is the process of transforming a function that takes n arguments into a function that takes n-1 arguments and returns a function.  What the hell does that mean?  Let's look at an example in everyone's favorite functional programming language, JavaScript.&lt;/p&gt;

&lt;p&gt;Here's a simple function that returns true if the first argument is greater than the second argument:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;function gt(x,y) {
  return x &amp;gt; y
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Pretty basic.  If we call &lt;code&gt;gt(3,2)&lt;/code&gt;, that will obviously return true.  If we call &lt;code&gt;gt(2)&lt;/code&gt; though, we get false, because it ends up evaluating the expression &lt;code&gt;2 &amp;gt; undefined&lt;/code&gt;, which is false.  So our gt function is pretty useless unless you pass it two arguments.&lt;/p&gt;

&lt;p&gt;Now what if we write it like this:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;function gt(x,y) {
  if(arguments.length &amp;gt; 1) {
    return x &amp;gt; y
  } else {
    return function(z) {
      return z &amp;gt; x
    }
  }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Now there is a lot of crazy lambda calculus going on here.  If you pass two arguments to gt, it works as before, returns true if x is greater than y.  But if you pass just one argument, this function creates a function that takes one argument and returns true if the argument is greater than x.&lt;/p&gt;

&lt;p&gt;This is an example of a closure.  We say the function that is returned "closes over" x, which just means that the function remembers what the value of x was at the time it was created, so when you call it later, it still uses that value.&lt;/p&gt;

&lt;p&gt;So if we call &lt;code&gt;gt(2)&lt;/code&gt;, the result we get back is a function that returns true if the argument to it is greater than 2.  This is called partial function application.  &lt;/p&gt;

&lt;p&gt;In functional programming, the correct term is actually not "call a function", but "apply a function to a set arguments".  That's why in JavaScript when you want call a function with arguments that you have in an array, you use the apply function, like this:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;gt.apply(null,[3,2]))
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;The first argument to apply is the object that the reference &lt;code&gt;this&lt;/code&gt; should point to during the function call, and in this case we just pass null because we don't care about the &lt;code&gt;this&lt;/code&gt; reference.  The next argument is the set of arguments, 3 and 2, which become the first and second arguments to the call to gt.&lt;/p&gt;

&lt;p&gt;So now the term partial function application makes sense, because we are applying a partial list of arguments to the function.  Now it should be clear why currying and partial function application go together hand-in-hand.  When you partially apply a function that is curried, you get something useful back.  Partially applying a function that is not curried isn't usually useful, as we saw in the first example, where calling &lt;code&gt;gt(2)&lt;/code&gt; resulted in evaluating the expression &lt;code&gt;2 &amp;gt; undefined&lt;/code&gt;, which is just silly.&lt;/p&gt;

&lt;p&gt;So in the case of our curried version of gt, is the result of partially applying actually useful?  Sure it is, when we combined it with other functional concepts.  All good functional programming language have some kind of &lt;code&gt;filter&lt;/code&gt; function, and JavaScript (well, &lt;a href="https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Objects/Array/filter"&gt;JavaScript 1.6&lt;/a&gt;.  Better late than never) is no exception.&lt;/p&gt;

&lt;p&gt;Filter is a higher-order function (whew, we are busting out all the fancy functional programming words today, aren't we!).  It is a higher-order function because it takes another function as it's argument.  What filter does is allow you to take an array of elements and produce another array with only the elements than match some condition.  The function that defines what the condition is is typically a predicate function.&lt;/p&gt;

&lt;p&gt;So let's filter an array of number an only get the ones greater than 2.  First we'll do it with an anonymous function as the predicate function:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;[0,1,2,3,4,5].filter(function(e){
  return e &amp;gt; 2
})
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;That will result in an array with 3, 4 and 5 in it.  That's a little wordy though.  Let's use our curried gt as the predicate instead:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;[0,1,2,3,4,5].filter(gt(2))
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Ah, there we go, that's nicer.  That's gives us 3, 4 and 5 as well.  Of course you can just change the value of the argument to gt to filter for values greater than that number.&lt;/p&gt;

&lt;p&gt;Now I should point that technically, our gt function is not in fact partially applied when we pass in less than two arguments, it just makes a new function.  If we define gt like this:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;function gt(x) {
  return function(y) {
    return y &amp;gt; x
  }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;This means that gt always takes two arguments and returns a function that takes one argument.  This still works the same in our filter example, &lt;code&gt;[0,1,2,3,4,5].filter(gt(2))&lt;/code&gt; does the same thing.  But when you want to just call gt directly with two arguments, that doesn't fly.  &lt;code&gt;gt(3,2)&lt;/code&gt; now just ignores the second argument and returns a function the same way &lt;code&gt;gt(3)&lt;/code&gt; would.  If we want to simulate our two argument call, we have to make two function calls, like &lt;code&gt;gt(2)(3)&lt;/code&gt;, which looks hideous.  Not only do we have two sets of parentheses, it is also has to be backwards.  To ask is &lt;code&gt;3 &amp;gt; 2&lt;/code&gt;, we has to pass in 2 first in order to the "greater than 2" function, and then pass 3 to that.&lt;/p&gt;

&lt;p&gt;&lt;a href="http://haskell.org"&gt;Haskell&lt;/a&gt; has built-in syntactic sugar to make this look not hideous.  Haskell is a statically-typed functional programming language.  Being statically-typed means that variables are of a specifc type.  JavaScript is the opposite, dynamically-typed.  In JavaScript, when you have a variable or a function argument that is named &lt;code&gt;x&lt;/code&gt;, &lt;code&gt;x&lt;/code&gt; can hold any type of Object, a String, Number, Function, etc.  In Haskell, when you define a variable or function argument, that must always be the same type.  Haskell is actually pretty clever about it though.  If you just say &lt;code&gt;x = 42&lt;/code&gt;, it knows, ok, x is an Int.  In other, &lt;a href="http://www.java.com"&gt;less sophisticated statically-typed languages&lt;/a&gt;, you would have to say something like &lt;code&gt;int x = 42&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;When you look at the type signature of a function in Haskell, at first, it looks odd.  For example, the type signature for our gt function might look like:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;gt :: Int -&amp;gt; Int -&amp;gt; Bool
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;At first you think, what's with the arrows?  Wouldn't something like this make more sense:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;gt :: (Int, Int) -&amp;gt; Bool
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Yeah, that matches what we are thinking.  gt is a function that takes two Int values and returns a Bool.  Well, even though you might think of it that way, that's not what it does in Haskell.  In Haskell, all functions are curried.  So our gt function is actually much closer to our last definition of gt in JavaScript, which looks like this:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;function gt(x) {
  return function(y) {
    return y &amp;gt; x
  }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;If you look at that for a minute, you'll agree that a type signature like this makes sense.&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;gt :: Int -&amp;gt; Int -&amp;gt; Bool
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;gt takes one argument and returns a function that takes one argument that returns a Bool.  Unlike JavaScript, Haskell's syntax makes calling curried functions clean.  So again, in JavaScript, we would have to do this to call our function:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;gt(2)(3)
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Which is the same as &lt;code&gt;3 &amp;gt; 2&lt;/code&gt;, but in Haskell if we want that, we simply just say &lt;code&gt;3 &amp;gt; 2&lt;/code&gt;.  In Haskell, infix operators are actually function calls.  &lt;code&gt;3 &amp;gt; 2&lt;/code&gt; is syntactic sugar for &lt;code&gt;(&amp;gt;) 3 2&lt;/code&gt;.  Also in Haskell, you don't have to wrap the function call in parentheses to call it.  The parentheses in this snippet are just the way of getting a reference to the infix function without calling it.  If you could name a function &lt;code&gt;&amp;gt;&lt;/code&gt; in JavaScript, the Haskell snippet &lt;code&gt;(&amp;gt;) 3 2&lt;/code&gt;, or even &lt;code&gt;3 &amp;gt; 2&lt;/code&gt;, would be the equivalent of &lt;code&gt;&amp;gt;(3, 2)&lt;/code&gt; in JavaScript.&lt;/p&gt;

&lt;p&gt;So when we want to partially apply this function to get a function that returns true if the value is greater than 2, we just write &lt;code&gt;(&amp;gt; 2)&lt;/code&gt;.  Haskell knows how to "do the right thing" with infix functions like greater than, so we don't have to deal with the problem of the arguments being backwards.  So here's how we do the filter, and we can do it by partially applying the built-in greater than function (this is the advantage of &lt;code&gt;&amp;gt;&lt;/code&gt; being a function, not an operator) to get the "greater than 2 function" to pass to filter:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;filter (&amp;gt; 2) [0..5]
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;This, of course, results in the list &lt;code&gt;[3,4,5]&lt;/code&gt;.  So that's a whirlwind tour of a lot of functional programming concepts, but we can sum it all up with this:  &lt;/p&gt;

&lt;p&gt;A curried function is a function that will return a new function when it is applied to less arguments than it expects and applying a function to less arguments than it expects is called partial function application.  So, stated even more succinctly, a curried function is a function that will return a new function when it is partially applied.&lt;/p&gt;&lt;div class="feedflare"&gt;
&lt;a href="http://feeds.feedburner.com/~ff/paulbarry?a=1x9pkL2PhSo:WWU5NKjjUHQ:yIl2AUoC8zA"&gt;&lt;img src="http://feeds.feedburner.com/~ff/paulbarry?d=yIl2AUoC8zA" border="0"&gt;&lt;/img&gt;&lt;/a&gt; &lt;a href="http://feeds.feedburner.com/~ff/paulbarry?a=1x9pkL2PhSo:WWU5NKjjUHQ:V_sGLiPBpWU"&gt;&lt;img src="http://feeds.feedburner.com/~ff/paulbarry?i=1x9pkL2PhSo:WWU5NKjjUHQ:V_sGLiPBpWU" border="0"&gt;&lt;/img&gt;&lt;/a&gt; &lt;a href="http://feeds.feedburner.com/~ff/paulbarry?a=1x9pkL2PhSo:WWU5NKjjUHQ:F7zBnMyn0Lo"&gt;&lt;img src="http://feeds.feedburner.com/~ff/paulbarry?i=1x9pkL2PhSo:WWU5NKjjUHQ:F7zBnMyn0Lo" border="0"&gt;&lt;/img&gt;&lt;/a&gt; &lt;a href="http://feeds.feedburner.com/~ff/paulbarry?a=1x9pkL2PhSo:WWU5NKjjUHQ:cGdyc7Q-1BI"&gt;&lt;img src="http://feeds.feedburner.com/~ff/paulbarry?d=cGdyc7Q-1BI" border="0"&gt;&lt;/img&gt;&lt;/a&gt;
&lt;/div&gt;</description>
      <pubDate>Fri, 21 Aug 2009 09:26:36 -0400</pubDate>
      <guid isPermaLink="false">urn:uuid:5a4195af-d967-4c3b-ab83-abfe89aadc5e</guid>
      <author>mail@paulbarry.com (Paul Barry)</author>
      <link>http://feedproxy.google.com/~r/paulbarry/~3/1x9pkL2PhSo/currying-and-partial-function-application</link>
      <category>Technology</category>
            <category>Haskell</category>
      <category>Javascript</category>
      <category>PartialFunctionApplication</category>
      <category>FunctionalProgramming</category>
      <category>Currying</category>
      <category>Closures</category>
          <feedburner:origLink>http://paulbarry.com/articles/2009/08/21/currying-and-partial-function-application</feedburner:origLink></item>
    <item>
      <title>In Search Of Sharper Tools</title>
      <description>&lt;p&gt;After reading the comments in my &lt;a href="http://paulbarry.com/articles/2009/07/21/types-and-metaprogramming-can-we-have-both"&gt;last post&lt;/a&gt;, one thing I realized that I neglected to do is define what I mean by metaprogramming.  Rubyists probably already know what I mean, but people coming from other programming languages might have different ideas about what I mean by metaprogramming.&lt;/p&gt;

&lt;p&gt;I've actually mentioned this in a few talks I've given about Ruby.  I don't really like the word Metaprogramming, it's a little bit nebulous.  I think a better term is dynamic code generation.  I like that term because I think most programmers will have a pretty good mental model of what I am talking about when I say that.  There are several features of Ruby that when combined together allow you to do almost anything to bend the language to your will.  To understand how to do that, I recommend reading the book &lt;a href="http://pragprog.com/titles/ppmetr/metaprogramming-ruby"&gt;Metaprogramming Ruby&lt;/a&gt;, which is in beta right now.&lt;/p&gt;

&lt;p&gt;I'll give a short, real world example of what I'm talking about.  I'm working on a Rails app that uses a database that has &lt;a href="http://en.wikipedia.org/wiki/Bit_field"&gt;bit field&lt;/a&gt; columns.  I want to treat the boolean flags in the bit field as though they are regular boolean attributes throughout my code.  So I wrote a Ruby gem &lt;a href="http://github.com/pjb3/has-bit-field"&gt;has-bit-field&lt;/a&gt;, which generates all the methods necessary to work with the bit field columns.  You define what is in the bit field in the most clear, simple, elegant way possible by just stating which column has the bit field and then what attributes should be generated for each bit: &lt;/p&gt;

&lt;pre&gt;&lt;code&gt;class Person &amp;lt; ActiveRecord::Base
  has_bit_field :bit_field, :likes_ice_cream, :plays_golf, :watches_tv, :reads_books
end
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;This is the kind of abstraction that the metaprogramming capabilities of Ruby afford you. I threw this together, with tests, in an hour or so.  Can you imagine the amount of nonsense you would have to go through in Java to create an abstraction equivalent to this?&lt;/p&gt;

&lt;p&gt;This type of abstraction is what I think makes Ruby a great language, but I realize you are definitely walking a fine line with this kind of thing.  It's possible for this sort of thing to go wrong quickly.  The first way these things go wrong is when the abstraction is not intuitive and not documented.  First of all, a good abstraction should be almost intuitive, requiring other programmers to be able to guess what is does.  This is commonly referred to as the &lt;a href="http://en.wikipedia.org/wiki/Principle_of_least_surprise"&gt;Principal of Least Surprise&lt;/a&gt;.  This doesn't mean that you are excused from providing some sort of documentation explaining how it works, especially for more complex abstractions.&lt;/p&gt;

&lt;p&gt;The reason why it's important that the abstraction is clear is that most of the time the code that defines the abstraction is dense at best, and downright ugly at worst.  This isn't a problem specific to Ruby, as anyone who has worked with Lisp macros can attest to.  But in the end I'd rather have a small chunk of code that is tested and documented that I don't really need to look at that enables me to make the code where the business logic is defined as clear as possible.  If other programmers are constantly having to dive into the guts of the definition of these abstractions just to understand how the code works, you have officially created a mess.  And this is no ordinary mess, this is meta-spaghetti, and is a mess on an order of magnitude not possible in statically typed languages.&lt;/p&gt;

&lt;p&gt;So does this mean you shouldn't use Ruby?  Not at all, and I think &lt;a href="http://www.vanderburg.org/Blog/Software/Development/sharp_and_blunt.rdoc"&gt;Glenn Vanderburg sums it up best&lt;/a&gt;:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;Weak developers will move heaven and earth to do the wrong thing. You can't limit the damage they do by locking up the sharp tools. They'll just swing the blunt tools harder. &lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;I think developers often associate "blunt tools" with static typing, because really they associate static typing with Java.  I'm not sure that static typing is in fact a blunt tool.  If static typing means I can't create these kinds of abstractions, then yes, it's a blunt tool.  But can you do this kind of thing with &lt;a href="http://www.scala-lang.org/node/140"&gt;Scala Compiler Plugins&lt;/a&gt;?  How about with &lt;a href="http://www.haskell.org/th/"&gt;Template Haskell&lt;/a&gt;?  What about with &lt;a href="http://www.metaocaml.org/"&gt;MetaOCaml&lt;/a&gt;?  If you can, are those tools then sharper than Ruby?  Or is there a way to define abstractions like these without metaprogramming at all?&lt;/p&gt;&lt;div class="feedflare"&gt;
&lt;a href="http://feeds.feedburner.com/~ff/paulbarry?a=vuD4WsX7_Ls:46lRZo1Ejk4:yIl2AUoC8zA"&gt;&lt;img src="http://feeds.feedburner.com/~ff/paulbarry?d=yIl2AUoC8zA" border="0"&gt;&lt;/img&gt;&lt;/a&gt; &lt;a href="http://feeds.feedburner.com/~ff/paulbarry?a=vuD4WsX7_Ls:46lRZo1Ejk4:V_sGLiPBpWU"&gt;&lt;img src="http://feeds.feedburner.com/~ff/paulbarry?i=vuD4WsX7_Ls:46lRZo1Ejk4:V_sGLiPBpWU" border="0"&gt;&lt;/img&gt;&lt;/a&gt; &lt;a href="http://feeds.feedburner.com/~ff/paulbarry?a=vuD4WsX7_Ls:46lRZo1Ejk4:F7zBnMyn0Lo"&gt;&lt;img src="http://feeds.feedburner.com/~ff/paulbarry?i=vuD4WsX7_Ls:46lRZo1Ejk4:F7zBnMyn0Lo" border="0"&gt;&lt;/img&gt;&lt;/a&gt; &lt;a href="http://feeds.feedburner.com/~ff/paulbarry?a=vuD4WsX7_Ls:46lRZo1Ejk4:cGdyc7Q-1BI"&gt;&lt;img src="http://feeds.feedburner.com/~ff/paulbarry?d=cGdyc7Q-1BI" border="0"&gt;&lt;/img&gt;&lt;/a&gt;
&lt;/div&gt;</description>
      <pubDate>Tue, 21 Jul 2009 23:51:18 -0400</pubDate>
      <guid isPermaLink="false">urn:uuid:ada3b189-049a-419b-838b-6f0ecbb229ed</guid>
      <author>mail@paulbarry.com (Paul Barry)</author>
      <link>http://feedproxy.google.com/~r/paulbarry/~3/vuD4WsX7_Ls/in-search-of-sharper-tools</link>
      <category>Technology</category>
            <category>Haskell</category>
      <category>Metaprogramming</category>
      <category>DynamicTyping</category>
      <category>OCaml</category>
      <category>Ruby</category>
      <category>StaticTyping</category>
      <category>Scala</category>
      <category>Java</category>
      <category>MetaOCaml</category>
          <feedburner:origLink>http://paulbarry.com/articles/2009/07/21/in-search-of-sharper-tools</feedburner:origLink></item>
      </channel>
</rss>
