<?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:media="http://search.yahoo.com/mrss/"
	>

<channel>
	<title>Invisible Blocks</title>
	<atom:link href="http://invisibleblocks.wordpress.com/feed/" rel="self" type="application/rss+xml" />
	<link>http://invisibleblocks.wordpress.com</link>
	<description>for building invisible machines</description>
	<pubDate>Mon, 30 Jun 2008 21:01:48 +0000</pubDate>
	<generator>http://wordpress.org/?v=MU</generator>
	<language>en</language>
			<item>
		<title>Constructor Inheritance in C# and Ruby</title>
		<link>http://invisibleblocks.wordpress.com/2008/06/30/constructor-inheritance-in-c-sharp-and-ruby/</link>
		<comments>http://invisibleblocks.wordpress.com/2008/06/30/constructor-inheritance-in-c-sharp-and-ruby/#comments</comments>
		<pubDate>Mon, 30 Jun 2008 21:01:15 +0000</pubDate>
		<dc:creator>Daniel Bernier</dc:creator>
		
		<category><![CDATA[Programming]]></category>

		<category><![CDATA[inheritance ruby c#]]></category>

		<guid isPermaLink="false">http://invisibleblocks.wordpress.com/?p=85</guid>
		<description><![CDATA[This morning: &#8220;Surprise!  Want to conduct a job interview?&#8221;  I&#8217;ve been here a little over 3 months, but um, sure!  &#8220;Great.  He&#8217;s in the conference room right now.&#8221;  Wow, we move quick.
So, without much time to gather my thoughts for good tech-y interview questions, I printed out the resume, and I winged it.  In the [...]]]></description>
			<content:encoded><![CDATA[<div class='snap_preview'><br /><p>This morning: &#8220;Surprise!  Want to conduct a job interview?&#8221;  I&#8217;ve been here a little over 3 months, but um, sure!  &#8220;Great.  He&#8217;s in the conference room right now.&#8221;  Wow, we move quick.</p>
<p>So, without much time to gather my thoughts for good tech-y interview questions, I printed out the resume, and I winged it.  In the middle of the interview, I flipped over his resume, and scribbled out short-hand C# like this:</p>
<pre name="code" class="c#">

class A {
   public A() {
      Console.WriteLine(&quot;in A&quot;);
   }
}
class B : A {
   public B() {
      Console.WriteLine(&quot;in B&quot;);
   }
}
class C : B {
   public C() {
      Console.WriteLine(&quot;in C&quot;);
   }
}
new C();
</pre>
<p>I asked, &#8220;What does this print out?&#8221;  You know, see if he knows which order constructor inheritance goes in.  I wanted to hear, &#8220;in A, in B, in C&#8221;, but not &#8220;in C, in B, in A&#8221;.</p>
<p>I forget exactly what the candidate&#8217;s answer was, but it stirred up a bit of discussion, because the three of us interviewing him disagreed on the answer:  one of us said it would only print &#8220;in C,&#8221; because you need to stick &#8220;: base()&#8221; on the B and C constructors for the inheritance to work;  I agreed with the third interviewer, who said it would print &#8220;in A, in B, in C&#8221;, because constructor inheritance is automatic (with no-arg constructors).  We fudged around it, laughed a bit, and the interview moved on.</p>
<p>Back at my desk, I had to try it out.  I didn&#8217;t want to bother with a whole Visual Studio .sln and all that nonsense, so I tried it in Ruby:</p>
<pre name="code" class="ruby">

class A
    def initialize
        puts &quot;in A&quot;
    end
end
class B &lt; A
    def initialize
        puts &quot;in B&quot;
    end
end
class C &lt; B
    def initialize
        puts &quot;in C&quot;
    end
end

C.new
</pre>
<p>And the output is&#8230;&#8221;in C&#8221;!  Huh?  That can&#8217;t be right&#8230;I was <em>sure</em> constructors were inherited automatically!  Then I realized, of course!  I&#8217;m working in Ruby, and you have to explicitly call superclass methods, constructors included:</p>
<pre name="code" class="ruby">

class A
    def initialize
        super # &lt;- call the superclass&#039; constructor
        puts &quot;in A&quot;
    end
end
class B &lt; A
    def initialize
        super # &lt;- call the superclass&#039; constructor
        puts &quot;in B&quot;
    end
end
class C &lt; B
    def initialize
        super # &lt;- call the superclass&#039; constructor
        puts &quot;in C&quot;
    end
end

C.new
</pre>
<p>Stupid Ruby!  Did I find a case where C# actually works nicer than Ruby?  But then I realized, this also means Ruby lets you change the order of the constructor inheritance: you can go bottom-up, if you want, or even stranger:</p>
<pre name="code" class="ruby">

class A
    def initialize
        super
        puts &quot;in A&quot;
    end
end
class B &lt; A
    def initialize
        super
        puts &quot;in B&quot;
    end
end
class C &lt; B
    def initialize
        puts &quot;in C&quot;
        super # &lt;- call up the chain AFTER we&#039;re done
    end
end

C.new
</pre>
<p>That one prints out &#8220;in C, in A, in B&#8221;.  The nice thing?  No rule to memorize, and more control.  The down-side?  More to type.  But given how compact Ruby already is, I think the added control is worth it here.  What do you think?</p>
<img alt="" border="0" src="http://feeds.wordpress.com/1.0/categories/invisibleblocks.wordpress.com/85/" /> <img alt="" border="0" src="http://feeds.wordpress.com/1.0/tags/invisibleblocks.wordpress.com/85/" /> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/invisibleblocks.wordpress.com/85/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/invisibleblocks.wordpress.com/85/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/invisibleblocks.wordpress.com/85/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/invisibleblocks.wordpress.com/85/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/invisibleblocks.wordpress.com/85/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/invisibleblocks.wordpress.com/85/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/invisibleblocks.wordpress.com/85/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/invisibleblocks.wordpress.com/85/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/invisibleblocks.wordpress.com/85/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/invisibleblocks.wordpress.com/85/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=invisibleblocks.wordpress.com&blog=290283&post=85&subd=invisibleblocks&ref=&feed=1" /></div>]]></content:encoded>
			<wfw:commentRss>http://invisibleblocks.wordpress.com/2008/06/30/constructor-inheritance-in-c-sharp-and-ruby/feed/</wfw:commentRss>
	
		<media:content url="http://a.wordpress.com/avatar/bonsaigiant-128.jpg" medium="image">
			<media:title type="html">bonsaigiant</media:title>
		</media:content>
	</item>
		<item>
		<title>Why &#8220;Less Code&#8221; Matters</title>
		<link>http://invisibleblocks.wordpress.com/2008/06/23/why-less-code-matters/</link>
		<comments>http://invisibleblocks.wordpress.com/2008/06/23/why-less-code-matters/#comments</comments>
		<pubDate>Tue, 24 Jun 2008 02:22:33 +0000</pubDate>
		<dc:creator>Daniel Bernier</dc:creator>
		
		<category><![CDATA[Programming]]></category>

		<category><![CDATA[Software Thinking]]></category>

		<category><![CDATA[abstraction]]></category>

		<category><![CDATA[refactoring]]></category>

		<category><![CDATA[semantic compression]]></category>

		<guid isPermaLink="false">http://invisibleblocks.wordpress.com/?p=83</guid>
		<description><![CDATA[&#8230;being able to do task X with 50 lines of code is preferable to needing 500 lines of code to do task X. Less code takes longer to write, but the real benefits are around maintenance: less code means less of a chance of bugs, less to keep in your head, less for someone else [...]]]></description>
			<content:encoded><![CDATA[<div class='snap_preview'><br /><blockquote><p>&#8230;being able to do task X with 50 lines of code is preferable to needing 500 lines of code to do task X. Less code takes longer to write, but the real benefits are around maintenance: less code means less of a chance of bugs, less to keep in your head, less for someone else (or yourself 6 months later) to read through and learn, less to test, and less to modify when you change the rest of the system.</p>
<p>- Alan Keefer, <a href="http://guidewiredevelopment.wordpress.com/2008/04/29/syntax-matters/">Syntax Matters</a></p></blockquote>
<p>I&#8217;d like to expand on that.  I don&#8217;t think it&#8217;s clear how important &#8220;less code&#8221; is, or how harmful <em>more</em> code is.  So let&#8217;s take an example written in a <a href="http://www.paulgraham.com/avg.html">Blub-y</a> language, and see how well we can refactor it.</p>
<p>(I know this post is kind of long, but it&#8217;s mostly Blub code, and it should scan quickly.)</p>
<p>Let&#8217;s make a sandwich.</p>
<pre>routine makeSandwich
    look for the peanut butter in the cabinet
    if it's not there, look for it in the other cabinet
    put the peanut butter on the counter

    look for the jelly in the fridge
    if it's not there, look for it in the cabinet
    if it's not there, look for it in the other cabinet
    put the jelly on the counter

    find a napkin
    put the napkin on the counter

    find the bread in the bread drawer
    untie the bread bag
    take two pieces of bread from the bag
    close the bread bag
    put the bread back in the bread drawer
    put the two pieces of bread on the napkin

    find a butter knife
    put the butter knife on the napkin

    open the peanut butter jar
    stick the butter knife into the peanut butter jar
    with the butter knife, scoop out some peanut butter
    spread the peanut butter on one piece of bread
    close the peanut butter jar
    put the peanut butter back in the cabinet

    wipe the butter knife on the other piece of bread

    open the jelly jar
    stick the butter knife into the jelly jar
    with the butter knife, scoop out some jelly
    spread the jelly on one the other piece of bread
    close the jelly jar
    put the jelly back in the fridge

    put the knife in the sink</pre>
<p>So much work!  No wonder I seldom cook.  Can we improve that at all?  Well, the &#8220;looking for in 2 cabinets&#8221; seems to be a pattern, so let&#8217;s Extract Method:</p>
<pre>routine lookForInTwoCabinets (lookFor)
    look for the lookFor in the cabinet
    if it's not there, look in the other cabinet
    return it

routine makeSandwich
    lookForInTwoCabinets (peanut butter)
    put the peanut butter on the counter

    look for the jelly in the fridge
    if it's not there, lookForInTwoCabinets(jelly)
    put the jelly on the counter
    ...</pre>
<p>Can we move the &#8220;put it on the counter&#8221; inside <code>lookForInTwoCabinets</code>?  I don&#8217;t know&#8230;it would work for the peanut butter, but what if we find the jelly in the fridge?  In that case, we wouldn&#8217;t call <code>lookForInTwoCabinets(jelly)</code>, so we might never put the jelly on the counter.   Besides, the name doesn&#8217;t really imply anything about what we do after we find the thing.  We should probably leave it outside.  Yeah, it&#8217;s not so DRY, but let&#8217;s move on.</p>
<p>That big block where we look for bread, we can&#8217;t really compress it at all&#8230;but we <em>can</em> extract it, just to wrap the whole sequence of steps up with a name.</p>
<pre>...
routine getBread
    find the bread in the bread drawer
    untie the bread bag
    take two pieces of bread from the bag
    close the bread bag
    put the bread back in the bread drawer
    put the two pieces of bread on the napkin

routine makeSandwich
    ...
    find a napkin
    put the napkin on the counter

    getBread

    find a butter knife
    put the butter knife on the napkin
    ...</pre>
<p>Ok, we&#8217;re making progress.  What about spreading the peanut butter &amp; jelly on the bread?  Can we extract another method?</p>
<pre>routine spread (topping, breadSlice)
    open the topping jar
    stick the butter knife into the topping jar
    with the butter knife, scoop out some topping
    spread the topping on breadSlice
    close the topping jar
    put the topping back in the cabinet

routine makeSandwich
    ...
    find a butter knife
    put the butter knife on the napkin

    spread (peanut butter, one piece of bread)

    wipe the butter knife on the other piece of bread

    spread (jelly, the other piece of bread)

    put the knife in the sink</pre>
<p>Great!  Except we just introduced a bug: after closing the topping jar,  <code>spread</code> always puts the topping back in the cabinet, and the jelly goes in the fridge (moldy jelly is a Bad Thing).  Introduce Parameter:</p>
<pre>routine spread (topping, breadSlice, returnToppingTo)
    open the topping jar
    stick the butter knife into the topping jar
    with the butter knife, scoop out some topping
    spread the topping on breadSlice
    close the topping jar
    put the topping back in returnToppingTo

routine makeSandwich
    ...
    find a butter knife
    put the butter knife on the napkin

    spread (peanut butter, one piece of bread, the cabinet)

    wipe the butter knife on the other piece of bread

    spread (jelly, the other piece of bread, the fridge)

    put the knife in the sink</pre>
<p>Ok, I think we&#8217;re done.   (Does it make sense to send a &#8220;return topping to&#8221; parameter to a method that&#8217;s just spreading?  Not now, we&#8217;re almost ready to commit&#8230;)  Let&#8217;s step back and admire our craft:</p>
<pre>routine lookForInTwoCabinets (lookFor)
    look for the lookFor in the cabinet
    if it's not there, look in the other cabinet
    return it

routine getBread
    find the bread in the bread drawer
    untie the bread bag
    take two pieces of bread from the bag
    close the bread bag
    put the bread back in the bread drawer
    put the two pieces of bread on the napkin

routine spread (topping, breadSlice, returnToppingTo)
    open the topping jar
    stick the butter knife into the topping jar
    with the butter knife, scoop out some topping
    spread the topping on breadSlice
    close the topping jar
    put the topping back in returnToppingTo

routine makeSandwich
    lookForInTwoCabinets (peanut butter)
    put the peanut butter on the counter

    look for the jelly in the fridge
    if it's not there, lookForInTwoCabinets(jelly)
    put the jelly on the counter

    find a napkin
    put the napkin on the counter

    getBread

    find a butter knife
    put the butter knife on the napkin

    spread (peanut butter, one piece of bread, the cabinet)

    wipe the butter knife on the other piece of bread

    spread (jelly, the other piece of bread, the fridge)

    put the knife in the sink</pre>
<p>31 lines down to&#8230;32 lines.  Ok, well, even if it&#8217;s longer, is it <em>better? </em> <code>makeSandwich</code> is shorter, that&#8217;s good.  But it doesn&#8217;t feel like we&#8217;ve really made the job any easier &#8212; we moved stuff around, but it&#8217;s still all there.  There&#8217;s no <a href="http://people.csail.mit.edu/gregs/ll1-discuss-archive-html/msg01552.html">semantic compression</a>.  It&#8217;s still <a href="http://invisibleblocks.wordpress.com/2008/04/05/why-we-abstract-and-what-to-do-when-we-cant/">3 + 3 + 3 + 3 + 3 + 3, instead of 3 * 6</a>.</p>
<p>What did we think about?   We had to ask ourselves whether to move &#8220;put it on the counter&#8221; into <code>lookForInTwoCabinets</code>.   The value of <code>getBread</code> is questionable.   We had the bug with <code>spread</code> putting the jelly in the cabinet, and we had to wonder about its &#8220;return topping to&#8221; parameter.  Every time we consider refactoring, we risk introducing a crappy abstraction that confuses, when it should clarify.   Every decision point, we have to think about it, and we might get it wrong.   But that&#8217;s why they pay us the big bucks, right?   Software development is hard, after all!</p>
<p>No.   We&#8217;re looking at <a href="http://en.wikipedia.org/wiki/No_Silver_Bullet">accidental complexity, not essential complexity</a>.  Here&#8217;s the same code, in a higher-level language, that removes some of the accidental complexity:</p>
<pre>put peanut butter on a piece of bread
put jelly on another piece of bread
stick the peanut butter to the jelly</pre>
<p>Essential complexity is when you start thinking, why jelly?  Why not cinnamon and raisins with the peanut butter?  Or currants?  What <em>kind</em> of bread?  Let&#8217;s use multigrain.  Would peanut butter with jelly <em>and</em> banana be overkill?  What to drink?  Essential complexity looks at the problem, not the solution.  Accidental complexity is when you say &#8220;I really want to do THIS but dammit, my language just won&#8217;t let me.&#8221;  Or, &#8220;Gosh, we have <em>so much code</em> to move around, I can barely see what it does.&#8221;  Or when you just can&#8217;t figure out where to put that parameter, or method, or class.</p>
<p><strong>So what does this have to do with &#8220;less code&#8221;?</strong></p>
<p>This is why we say <a href="http://c2.com/xp/YouArentGonnaNeedIt.html">YAGNI</a>.  If you add that method on a hunch that it&#8217;ll be helpful, you have more stuff to move around, more accidental complexity, more decisions to make about your housekeeping, all for a <em>speculative</em> benefit.  It&#8217;s like playing lotto - you pay up front, and if you&#8217;re really lucky, you&#8217;ll win.  But if you lose, you&#8217;ve wasted resources, and now you have something you need to throw away.</p>
<p>Each of the possible ways to code and refactor that sandwich code is pretty valid&#8230;any of them could be in our source control repository.  A new hire is going to have to read through whichever one we coded, and try to mentally get from there, to the 3-liner at the end, before he can really be effective.  Why don&#8217;t we just <em>start</em> him there?</p>
<p>Let&#8217;s take that 3 + 3 + 3 + 3 + 3 + 3 example again.  What if we don&#8217;t use multiplication?  We could still refactor it.  The first two threes are kind of together, let&#8217;s group them:  6 + 3 + 3 + 3 + 3.  And the last one looks kind of bulky, so let&#8217;s decompose it:  6 + 3 + 3 + 3 + 1 + 1 + 1.  Could we move some of the numericality from the middle 3 to an earlier one?  6 + 3 + 4 + 2 + 1 + 1 + 1.  Oh, and let&#8217;s sort, so it&#8217;s easier to find the numbers you want:  1 + 1 + 1 + 2 + 3 + 4 + 6.  There!  Is it immediately obvious to you that this is the same as 3 * 6?  Of course not.  Ralph Johnson calls refactoring &#8220;<a href="http://www.amazon.com/Refactoring-Improving-Existing-Addison-Wesley-Technology/dp/0201485672">wiping dirt off a window</a>,&#8221; and you just put more dirt on.</p>
<img alt="" border="0" src="http://feeds.wordpress.com/1.0/categories/invisibleblocks.wordpress.com/83/" /> <img alt="" border="0" src="http://feeds.wordpress.com/1.0/tags/invisibleblocks.wordpress.com/83/" /> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/invisibleblocks.wordpress.com/83/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/invisibleblocks.wordpress.com/83/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/invisibleblocks.wordpress.com/83/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/invisibleblocks.wordpress.com/83/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/invisibleblocks.wordpress.com/83/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/invisibleblocks.wordpress.com/83/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/invisibleblocks.wordpress.com/83/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/invisibleblocks.wordpress.com/83/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/invisibleblocks.wordpress.com/83/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/invisibleblocks.wordpress.com/83/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=invisibleblocks.wordpress.com&blog=290283&post=83&subd=invisibleblocks&ref=&feed=1" /></div>]]></content:encoded>
			<wfw:commentRss>http://invisibleblocks.wordpress.com/2008/06/23/why-less-code-matters/feed/</wfw:commentRss>
	
		<media:content url="http://a.wordpress.com/avatar/bonsaigiant-128.jpg" medium="image">
			<media:title type="html">bonsaigiant</media:title>
		</media:content>
	</item>
		<item>
		<title>Passing by reference, and dog leashes</title>
		<link>http://invisibleblocks.wordpress.com/2008/04/29/passing-by-reference-and-dog-leashes/</link>
		<comments>http://invisibleblocks.wordpress.com/2008/04/29/passing-by-reference-and-dog-leashes/#comments</comments>
		<pubDate>Tue, 29 Apr 2008 17:38:56 +0000</pubDate>
		<dc:creator>Daniel Bernier</dc:creator>
		
		<category><![CDATA[Learning]]></category>

		<category><![CDATA[Programming]]></category>

		<category><![CDATA[Software Thinking]]></category>

		<guid isPermaLink="false">http://invisibleblocks.wordpress.com/?p=82</guid>
		<description><![CDATA[Pass-by-reference and pass-by-value are pretty confusing when you start learning to code.  When I first saw them, I know I ignored the distinction (until I got tired of my code not doing what I expected).  Throwing collections into the mix just makes it worse.
Today, though, we stumbled on a pretty decent analogy for [...]]]></description>
			<content:encoded><![CDATA[<div class='snap_preview'><br /><p>Pass-by-reference and pass-by-value are pretty confusing when you start learning to code.  When I first saw them, I know I ignored the distinction (until I got tired of my code not doing what I expected).  Throwing collections into the mix just makes it worse.</p>
<p>Today, though, we stumbled on a pretty decent analogy for passing-by-reference: a reference to an object is like a leash to a dog.  Let&#8217;s take our dog Dagwood for a walk.</p>
<pre name="code" class="c#">

Dog dagwood = new Dog(&quot;Dagwood&quot;);
</pre>
<p><code>new Dog()</code> creates, of course, a new Dog object.  <code>Dog dagwood</code> creates a reference that can point to any Dog object &#8212; it&#8217;s really the leash, but we name our references for what they point to, rather than what they are: a reference, a handle, a leash.  The equals sign takes the leash, and hooks it to Dagwood&#8217;s collar.  Now we can take Dagwood for a walk.</p>
<pre name="code" class="c#">

dagwood.walk();
</pre>
<p>To tell Dagwood it&#8217;s time to walk, we tug on the leash.  He feels the tug, and gets the message, so he starts following us.  We come to a busy road, and wait for the crossing signal, but Dagwood&#8217;s oblivious, and tries to cross anyway.</p>
<pre name="code" class="c#">

dagwood.halt();
</pre>
<p>Since we&#8217;re stopped, he feels the tug of the leash again, gets the message, and stops.  We&#8217;re sending messages to Dagwood through his leash.  In OO terms, sending a message to an object means calling one of its methods.  We&#8217;re calling methods on our Dagwood <strong>through</strong> our reference to him, through the leash.</p>
<p><strong>Storing a reference in an array</strong></p>
<p>In the park, we find a snack shop.  We&#8217;re getting hungry, but the snack shop doesn&#8217;t let dogs inside.  Luckily, there&#8217;s a chain link fence, and in our eyes, a chain link fence is nothing but a big row of places for us to attach a dog leash.  We tie a spare leash to the end of the fence, and attach it to Dagwood&#8217;s collar.</p>
<pre name="code" class="c#">

Dog[] fence = new Dog[10]; // only room for 10 dogs
fence[0] = dagwood;
</pre>
<p>What&#8217;s happening here in OO terms is that our reference to Dagwood, our leash, is <strong>copied</strong> into the zeroth slot on the fence.  It&#8217;s not our leash, but it&#8217;s one just like it.  So now there are two leashes on Dagwood: one in our hand, and one on the fence.  We&#8217;ll take our leash off Dagwood, since we can&#8217;t very well hold it while we&#8217;re in the store.</p>
<pre>
<pre name="code" class="c#">

dagwood = null;
</pre>
</pre>
<p>Don&#8217;t worry, he&#8217;s fine&#8230;he&#8217;s still tied to the fence, by that other leash.  Let&#8217;s go buy cashews.</p>
<p>When we come out of the store, we want to re-attach our leash to Dagwood.</p>
<pre name="code" class="c#">

dagwood = fence[0];
</pre>
<p>Now let&#8217;s untie him from the fence, and head over to the lake.</p>
<pre name="code" class="c#">

fence[0] = null;
</pre>
<p><strong>Passing by reference</strong></p>
<p>Passing references to methods works in much the same way.  Dagwood got kind of stinky, swimming in the lake, so let&#8217;s bring him to the groomer for a bath.</p>
<pre name="code" class="c#">

DogGroomer.shampoo(dagwood);
</pre>
<p>When you pass a reference to a method, your reference is copied into that method.  Again, it&#8217;s like a new leash, one just like ours, springs into the groomer&#8217;s hand &#8212; now Dagwood&#8217;s attached to us, and the groomer.  He gets fidgety when he&#8217;s getting bathed, so it&#8217;s just as well.</p>
<p>From the groomer&#8217;s perspective, it might look like this:</p>
<pre name="code" class="c#">

void shampoo(Dog doggie) {
    wet(doggie);
    apply(shampoo, doggie);
    rinse(doggie);
    towelDry(doggie);
}
</pre>
<p>The groomer doesn&#8217;t care what Dagwood&#8217;s name is, she just keeps calling him &#8220;doggie.&#8221;  That&#8217;s ok, she must see a lot of dogs during the day&#8230;names aren&#8217;t that important to her.  The interesting thing is, even though it&#8217;s the groomer who&#8217;s shampooing our dog, since we still have a leash on him, we can observe him getting cleaner.</p>
<p>When she&#8217;s done, the procedure ends, the method returns, and her leash to Dagwood disappears.  Which is fine, because he&#8217;s stopped fidgeting, now that he&#8217;s dry.</p>
<p><strong>Garbage collection</strong></p>
<p>We head back home through the park.  Dagwood&#8217;s itching to run around, but we&#8217;re tired, so we just unleash him.  Hopefully we can find him before it gets dark&#8230;</p>
<pre>
<pre name="code" class="c#">

dagwood = null;
</pre>
</pre>
<p>Unfortunately, the dog catcher spots him running around without a leash, which is illegal in these parts &#8212; a stray dog will hang around forever, eating up resources.  The dog catcher carries off our poor Dagwood, and destroys him.  We take it in stride, and try to keep the whole circle of <span style="text-decoration:line-through;">life</span> allocation-deallocation in mind.</p>
<p><strong>So&#8230;</strong></p>
<p>So that&#8217;s how references work.  It&#8217;s why code like this (C#) will ensure the balloon bouquet has at least one balloon that says &#8220;Happy Birthday!&#8221;:</p>
<pre name="code" class="c#">

List&lt;Balloon&gt; balloons = GetBalloons();
Balloon printed = balloons.Find(Balloon.IsPrinted);
if (printed == null) {
   printed = new Balloon();
   printed.PrintMessage(&quot;Happy Birthday!&quot;);
   balloons.Add(printed);
}
return balloons;
</pre>
<img alt="" border="0" src="http://feeds.wordpress.com/1.0/categories/invisibleblocks.wordpress.com/82/" /> <img alt="" border="0" src="http://feeds.wordpress.com/1.0/tags/invisibleblocks.wordpress.com/82/" /> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/invisibleblocks.wordpress.com/82/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/invisibleblocks.wordpress.com/82/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/invisibleblocks.wordpress.com/82/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/invisibleblocks.wordpress.com/82/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/invisibleblocks.wordpress.com/82/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/invisibleblocks.wordpress.com/82/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/invisibleblocks.wordpress.com/82/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/invisibleblocks.wordpress.com/82/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/invisibleblocks.wordpress.com/82/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/invisibleblocks.wordpress.com/82/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=invisibleblocks.wordpress.com&blog=290283&post=82&subd=invisibleblocks&ref=&feed=1" /></div>]]></content:encoded>
			<wfw:commentRss>http://invisibleblocks.wordpress.com/2008/04/29/passing-by-reference-and-dog-leashes/feed/</wfw:commentRss>
	
		<media:content url="http://a.wordpress.com/avatar/bonsaigiant-128.jpg" medium="image">
			<media:title type="html">bonsaigiant</media:title>
		</media:content>
	</item>
		<item>
		<title>My GoRuCo 2008 highlights</title>
		<link>http://invisibleblocks.wordpress.com/2008/04/28/my-goruco-2008-highlights/</link>
		<comments>http://invisibleblocks.wordpress.com/2008/04/28/my-goruco-2008-highlights/#comments</comments>
		<pubDate>Mon, 28 Apr 2008 22:36:27 +0000</pubDate>
		<dc:creator>Daniel Bernier</dc:creator>
		
		<category><![CDATA[Uncategorized]]></category>

		<category><![CDATA[Add new tag]]></category>

		<category><![CDATA[goruco2008 ruby]]></category>

		<guid isPermaLink="false">http://invisibleblocks.wordpress.com/?p=81</guid>
		<description><![CDATA[Aaron and I had a great time at GoRuCo 2008 last Saturday.  Here are my highlights.
Bryan Helmkamp, Story-Driven Development
Bryan Helmkamp&#8217;s talk on SDD (slides, 1.6 MB PDF) reminded me of what Scott Hanselman calls &#8220;spec documents with teeth.&#8221;  If I get it right, as you develop user stories, you use a standard format, [...]]]></description>
			<content:encoded><![CDATA[<div class='snap_preview'><br /><p><a href="http://rubydoes.net/">Aaron</a> and I had a great time at <a href="http://2008.goruco.com/">GoRuCo 2008</a> last Saturday.  Here are my highlights.</p>
<p><strong>Bryan Helmkamp, Story-Driven Development</strong></p>
<p><a href="http://www.brynary.com/">Bryan Helmkamp&#8217;s</a> talk on SDD (<a href="http://www.brynary.com/uploads/Story_Driven_Development.pdf">slides</a>, 1.6 MB PDF) reminded me of what <a href="http://www.hanselman.com">Scott Hanselman</a> calls &#8220;spec documents with teeth.&#8221;  If I get it right, as you develop user stories, you use a standard format, and code parses your story file, and ties the text directly to functional tests you write.  The stories aren&#8217;t executable themselves, but it brings them closer together.</p>
<p>Each story has a name, a description, and scenarios; the descriptions follow the format &#8220;As a &#8230;, I want to &#8230;, so that &#8230;&#8221;:</p>
<pre>As a headhunter looking for Rails developers
I want to search for CVs with 8 years experience
So that I can make an exorbitant commission</pre>
<p>The scenarios are different ways that story might play out.  Each scenario has a description, which follows the format &#8220;Given &#8230; When &#8230; Then &#8230;&#8221;:</p>
<pre>Scenario: Enough experience.
<em>Given</em> <strong>a CV with 9 years of Rails experience</strong>
<em>When</em> <strong>I search for qualified Rails candidates</strong>
<em>Then</em> <strong>I should find the CV</strong>
<em>And</em> <strong>I should realize the candidate is full of shit</strong></pre>
<p>Then code reads your story files, and uses the text following the keywords to connect to executable functional tests you write:</p>
<pre name="code" class="ruby">

steps_for :cvs do
  Given &quot;a CV with 3 years of Rails experience&quot; do
    @cv = Developer.create!(:first_name =&gt; &quot;Joe&quot;,
      :last_name =&gt; &quot;Developer&quot;, :rails_exp =&gt; 3,
      :gender =&gt; &quot;Male&quot;)
  end
end

steps_for :cvs do
  When &quot;I search for qualified Rails candidates&quot; do
    @results = Developer.find_qualified(8)
  end
end
</pre>
<p>The code that actually performs the test is just ActiveRecord.  If you want to test the UI, there&#8217;s a DSL called Webrat that simulates the browser.  It seems to live halfway between Watir and mechanize, and it doesn&#8217;t do javascript.  It looks like this:</p>
<pre name="code" class="ruby">

steps_for :cvs_with_ui do
  Given &quot;a CV with 3 years of Rails experience&quot; do
    visits new_developer_path
    fills_in &quot;First name&quot;, :with =&gt; &quot;Joe&quot;
    fills_in &quot;Last name&quot;, :with =&gt; &quot;Developer&quot;
    selects &quot;4&quot;, :from =&gt; &quot;Rails Experience&quot;
    chooses &quot;Male&quot;
    clicks_button &quot;Create&quot;
  end
end
</pre>
<p>I&#8217;m curious about <code>chooses "Male"</code> &#8212; I don&#8217;t see how it connects that text with the drop-down it&#8217;s supposed to change, unless it looks at values for all drop-downs on the page.  He gave a nice breakdown of the differences between Webrat and Selenium, and how SDD fits into an Agile team.</p>
<p><strong>Giles Bowkett, Archaeopteryx</strong></p>
<p>That&#8217;s ARK-ee-OP-ter-ix, or Arcx for short.  Made by Giles (soft &#8216;g&#8217;) BOH-ket, or boh-KET, I wasn&#8217;t exactly sure which.  It is, in <a href="http://gilesbowkett.blogspot.com/2008/02/archaeopteryx-ruby-midi-generator.html">his words</a>, &#8220;a Ruby MIDI generator,&#8221; and &#8220;a system for auto-generating, self-modifying music.&#8221;</p>
<p>Giles had hands-down the most entertaining talk of the day.  Instead of poring through each token of the code, he compared taking VC money (or &#8220;weasel-brained muppet fucker&#8221; money) to being an artist with a patron &#8212; as the programmer/artist, your job is to make stuff that makes your VC/patron look good.  He showed some of Leonardo da Vinci&#8217;s <a href="http://www.vebjorn-sand.com/thebridge.htm">designs</a> that weren&#8217;t constructed until recently; that it took this long, he said, was a failure of da Vinci&#8217;s time.  Similarly, staying within a VC&#8217;s idea of what&#8217;s possible is a failure of wasted passion and energy. Start-ups are so cheap now, you can ignore VCs &#8212; so follow your passion, create an open-source-enriched ecosystem around it, and make money by servicing the niche market you made.  If your startup is great, you can say &#8220;my career is this thing&#8221;; if it&#8217;s mediocre, you can say &#8220;my career <em>includes</em> this thing&#8221;.  Just remember that good artists ship.</p>
<p>Which brings us to Arcx, Giles&#8217; idea for a crowd-interfacing, automatic music machine.  Someone asked whether it was wise to name a new project after an extinct species, and Giles got all clever: archaeopteryx was either the last dinosaur or the first bird, and the project could be either the last DJ tool, or the first automatic music machine, played by the crowd.  He played us some samples, and talked through the code just a bit, dropping hits about the <a href="http://en.wikipedia.org/wiki/CLOS">CLOS</a>-like structure of his code.  As fun as his talk was, I would&#8217;ve liked to hear more music, and more about the lambda-passing and CLOS stuff.</p>
<p>He also pointed out the most interesting ruby book I&#8217;d never heard <span class="asinTitle">of, <a href="http://www.amazon.com/Practical-Ruby-Projects-Programmer-Professionals/dp/159059911X/"><span>Practical Ruby Projects: Ideas for the Eclectic Programmer</span></a></span>.</p>
<p><strong>Chris Wanstrath, ParseTree</strong></p>
<p>Out of all the talks, Chris&#8217; was the one I&#8217;ll be using first.  Lispers say &#8220;code is data,&#8221; and I can see why that&#8217;s so powerful &#8212; but I haven&#8217;t really tried it yet.  ParseTree brings some of that coolness to ruby:</p>
<pre name="code" class="ruby">

require &#039;ruby2ruby&#039;

def to_ruby(&amp;blk)
   blk.to_ruby
end

puts to_ruby { 1 + 1 }
puts to_ruby { |i| i == 42 }

def to_sexp(&amp;blk)
   blk.to_sexp
end

puts to_sexp { 1 + 1 }
puts to_sexp { |i| i == 42 }
</pre>
<p>&#8230;which produces:</p>
<pre name="code" class="ruby">

proc {
  (1 + 1)
}
proc { |i|
  (i == 42)
}
[:proc, nil, [:call,
   [:lit, 1], :+, [:array, [:lit, 1]]]]
[:proc, [:dasgn_curr, :i], [:call,
   [:dvar, :i], :==, [:array, [:lit, 42]]]]
</pre>
<p>Most of the examples he gave generated query syntax in a ruby-idiomatic way: say you have an ORM, and you want users to search for users like this:</p>
<pre name="code" class="ruby">

old_cat_people = Users.select do |u|
   u.favorite_pet == &quot;cat&quot; &amp;&amp; u.age &gt; 100
end
</pre>
<p>How could you turn that into SQL?  Call <code>to_sexp</code> on the query block (that&#8217;s &#8220;to <a href="http://en.wikipedia.org/wiki/S-expression">S-expression</a>&#8220;), and evaluate the <a href="http://en.wikipedia.org/wiki/Abstract_syntax_tree">abstract syntax tree</a> it returns. Like this:</p>
<pre name="code" class="ruby">

class Users
   def self.select(&amp;query)
      query = query.to_sexp

      # Now, query looks like this:
      # [:proc,
      #    [:dasgn_curr, :u],
      #       [:and,
      #          [:call,
      #             [:call, [:dvar, :u], :favorite_pet],
      #             :==,
      #             [:array, [:str, &quot;cat&quot;]]],
      #          [:call,
      #             [:call, [:dvar, :u], :age],
      #             :&gt;,
      #             [:array, [:lit, 100]]]]]

      # Time to evaluate the AST.
   end
end
</pre>
<p>Admittedly, it&#8217;s not <em>that</em> trivial, but that&#8217;s the gist of it &#8212; and I think the gem helps you with this.  (Cue the smug Lispers: this stuff is natural in Lisp, the way passing <a href="http://eli.thegreenplace.net/2006/04/18/understanding-ruby-blocks-procs-and-methods/"><span style="text-decoration:line-through;">anonymous functions</span> blocks</a> is in ruby.)</p>
<p>But here&#8217;s the interesting thing: we&#8217;re on our way to building .Net&#8217;s LINQ right into ruby.  Remember, it stands for <strong>L</strong>anguage <strong>In</strong>tegrated <strong>Q</strong>uery.  LINQ is a big deal for .Net folks, because it&#8217;s handy.  Microsoft put a lot of work into it, and it still needs its own new syntax.  I think that&#8217;s a pretty clear example of the power of being able to see your own AST, and code off it.</p>
<p><strong>Ryan Davis, Hurting Code for Fun and Profit</strong></p>
<p><a href="http://blog.zenspider.com/">Ryan</a>&#8217;s talk was nominally about using tools like <a href="http://ruby.sadi.st/Heckle.html">Heckle</a> and <a href="http://ruby.sadi.st/Flog.html">Flog</a> to beat the evil out of code, but my favorite part was his introspection-driven development.  I <em>know</em> I&#8217;ll want to refer others to his slides and audio throughout my career.</p>
<p>Some of his tips for improving as a programmer:</p>
<ul>
<li>Read.  1 technical book a month.  Sites like c2.com &#8212; get close to the experts.</li>
<li>Focus.  Only a few smart blogs: not zillions, not flame-prone.  (Flame-retardant blogs?)</li>
<li>Grow.  Learn 1 new language a year.  Learn things outside of programming.</li>
<li>Learn from the <a href="http://c2.com/cgi/wiki?PotteryChallenge">pottery challenge story</a> in <a href="http://c2.com/cgi/wiki?ArtAndFear">Art &amp; Fear</a>: practice, a lot.</li>
</ul>
<p>Ryan is also a fellow Dvorak typist, and pretty emphatic about it.</p>
<p><strong>Johnson</strong></p>
<p><a href="http://tenderlovemaking.com/2008/04/23/take-it-to-the-limit-one-more-time/">Johnson</a> is a ruby gem that executes JavaScript code.  (It&#8217;s a successor to <a href="http://rubyforge.org/projects/rkelly/">RKelly</a>, which did the same thing.)  I don&#8217;t know why I think this is so cool.  Most people agreed the main use case for something like this is testing, but it seems to me there might be neater tricks to play.  We&#8217;ll see how I feel after playing with it for a while.</p>
<p><strong>GoRuCo 2009?</strong></p>
<p>I&#8217;m definitely going next year &#8212; see you there.</p>
<img alt="" border="0" src="http://feeds.wordpress.com/1.0/categories/invisibleblocks.wordpress.com/81/" /> <img alt="" border="0" src="http://feeds.wordpress.com/1.0/tags/invisibleblocks.wordpress.com/81/" /> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/invisibleblocks.wordpress.com/81/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/invisibleblocks.wordpress.com/81/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/invisibleblocks.wordpress.com/81/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/invisibleblocks.wordpress.com/81/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/invisibleblocks.wordpress.com/81/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/invisibleblocks.wordpress.com/81/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/invisibleblocks.wordpress.com/81/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/invisibleblocks.wordpress.com/81/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/invisibleblocks.wordpress.com/81/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/invisibleblocks.wordpress.com/81/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=invisibleblocks.wordpress.com&blog=290283&post=81&subd=invisibleblocks&ref=&feed=1" /></div>]]></content:encoded>
			<wfw:commentRss>http://invisibleblocks.wordpress.com/2008/04/28/my-goruco-2008-highlights/feed/</wfw:commentRss>
	
		<media:content url="http://a.wordpress.com/avatar/bonsaigiant-128.jpg" medium="image">
			<media:title type="html">bonsaigiant</media:title>
		</media:content>
	</item>
		<item>
		<title>Trading Space for Speed: Memoizing with Ruby Facets</title>
		<link>http://invisibleblocks.wordpress.com/2008/04/14/trading-space-for-speed-memoizing-with-ruby-facets/</link>
		<comments>http://invisibleblocks.wordpress.com/2008/04/14/trading-space-for-speed-memoizing-with-ruby-facets/#comments</comments>
		<pubDate>Mon, 14 Apr 2008 11:37:26 +0000</pubDate>
		<dc:creator>Daniel Bernier</dc:creator>
		
		<category><![CDATA[Functional Programming]]></category>

		<category><![CDATA[Programming]]></category>

		<category><![CDATA[ruby RubyFacets FacetsTour]]></category>

		<guid isPermaLink="false">http://invisibleblocks.wordpress.com/?p=78</guid>
		<description><![CDATA[Recently, I talked about a faster, cheaper way to calculate Fibonacci numbers.  One of the optimizations I made was to remember the value of each Fibonacci number:  since F(7) is always 13, instead of recalculating it each time N=7, we can stuff 7 -&#62; 13 into a look-up table for future reference. The [...]]]></description>
			<content:encoded><![CDATA[<div class='snap_preview'><br /><p>Recently, I talked about a <a href="http://invisibleblocks.wordpress.com/2008/03/22/a-faster-cheaper-fibonacci-definition/">faster, cheaper way</a> to calculate <a href="http://en.wikipedia.org/wiki/Fibonacci_number">Fibonacci</a> numbers.  One of the optimizations I made was to remember the value of each Fibonacci number:  since F(7) is always 13, instead of recalculating it each time N=7, we can stuff <em>7 -&gt; 13</em> into a look-up table for future reference. The function builds up a cheat-sheet, to avoid doing the re-work.  It remembers.</p>
<p>This is called <a href="http://en.wikipedia.org/wiki/Memoization">memoization</a>, and it&#8217;s a nice way to trade memory for performance.  But it only works when the function always returns the same answer for a given set of arguments &#8212; otherwise it&#8217;s first-in wins, forever.  This property of a function, returning the same answer for the same args, is called <a href="http://en.wikipedia.org/wiki/Referential_transparency_%28computer_science%29">referential transparency</a>.</p>
<h4>A Sample Implementation</h4>
<p>There are lots of ways you could memoize a function.  Hash tables are a natural choice, since they map a key to a value, just like functions map arguments to a value.  Even if you implement it differently, a hash table is a good working model for memoization.</p>
<p>Let&#8217;s briefly consider factorials.  The regular version:</p>
<pre name="code" class="ruby">

class Unmemoized
    def factorial(n)
        puts n
        if n &lt; 1
            1
        else
            n * factorial(n-1)
        end
    end
end

unmemoized = Unmemoized.new

5.downto(1) { |i| puts &quot;\t#{unmemoized.factorial(i)}&quot; }
</pre>
<p>&#8230;and the memoized version:</p>
<pre name="code" class="ruby">

class Memoized
    attr_reader :factorial_memo
    def initialize
        @factorial_memo = {}
    end

    def factorial(n)
        puts n
        unless @factorial_memo.has_key? n
            if n &lt; 1
                @factorial_memo[n] = 1
            else
                @factorial_memo[n] = n * factorial(n-1)
            end
        end

        @factorial_memo[n]
    end
end

memoized = Memoized.new

5.downto(1) { |i| puts &quot;\t#{memoized.factorial(i)}&quot; }

puts memoized.factorial_memo.inspect
</pre>
<p>Printing the hashtable is especially telling:  <code>{5=&gt;120, 0=&gt;1, 1=&gt;1, 2=&gt;2, 3=&gt;6, 4=&gt;24}</code> It reads like a look-up table for factorials.</p>
<h4>Memoization in Facets</h4>
<p>As relatively easy as that example is, it has its drawbacks: we need to track our previous results in a separate variable, the memoization code is mixed up with the actual calculation (the part we care about), we can&#8217;t easily use it with other functions, and the pattern only works for functions of one argument.  <a href="http://facets.rubyforge.org/">Facets</a> makes memoization trivial, and removes all these issues.</p>
<pre name="code" class="ruby">

require &#039;facets/memoize&#039;

class FacetsMemoized
    def factorial(n)
        puts n
        if n &lt; 1
            1
        else
            n * factorial(n-1)
        end
    end

    memoize :factorial # &lt;= HINT
end

facets_memoized = FacetsMemoized.new

5.downto(1) { |i| puts &quot;\t#{facets_memoized.factorial(i)}&quot; }
</pre>
<p>In case you missed it, this is just like <code>Unmemoized</code> above, except we added line 13, <code>memoize :factorial</code>&#8230;that&#8217;s it.  Just like <code>attr_reader</code> and friends, you can pass a list of symbols to <code>memoize</code>, and it&#8217;ll work on functions with any number of arguments:</p>
<pre name="code" class="ruby">

require &#039;facets/memoize&#039;

class MemoizedMath
    def add(n, m)
        n + m
    end
    def mult(n, m)
        n * m
    end
    memoize :add, :mult
end
</pre>
<h4>When You Might Use Memoization, and What to Avoid</h4>
<p>There are a number of places where this is useful: calculating a value by <a href="http://mitpress.mit.edu/sicp/full-text/sicp/book/node12.html">successive approximation</a>, finding the path to the root node in an immutable tree structure, finding the <em>N</em>th number in a recursively-defined series, even simple derived values (like &#8216;abc&#8217;.upcase).  In general, a function is a good candidate if it only looks at its arguments (no global, class, or member variables, no files or databases) &#8212; especially if those arguments are immutable.</p>
<p>Relying on side-effects (printing to standard out, writing to a database or file, or updating a variable) in memoized methods is a bad idea: they&#8217;ll only happen the first time your method is called with those arguments, which is probably not what you intend. (Unless you&#8217;re printing the arguments to illustrate how memoizing works.) On the other hand, relying on side-effects <a href="http://www.google.com/search?q=favor+immutability">is generally a bad idea</a> anyway. Even if you don&#8217;t use a functional programming language, you can still benefit from minimizing state changes.</p>
<h4>Further Reading</h4>
<p>If memoization sounds interesting to you, you might like Oliver Steele&#8217;s article about <a href="http://osteele.com/archives/2006/04/javascript-memoization">memoizing JavaScript functions</a>.  If you&#8217;re curious about immutability, you might like this <a href="http://www.artima.com/intv/blochP.html">Joshua Bloch interview</a>.  If you&#8217;re interested in functional programming, there are worse places to start than the excellent <a href="http://mitpress.mit.edu/sicp/full-text/book/book.html">Structure and Interpretation of Computer Programs</a>.  And of course, there&#8217;s more where that came from, in <a href="http://facets.rubyforge.org/">Ruby Facets</a>.</p>
<img alt="" border="0" src="http://feeds.wordpress.com/1.0/categories/invisibleblocks.wordpress.com/78/" /> <img alt="" border="0" src="http://feeds.wordpress.com/1.0/tags/invisibleblocks.wordpress.com/78/" /> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/invisibleblocks.wordpress.com/78/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/invisibleblocks.wordpress.com/78/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/invisibleblocks.wordpress.com/78/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/invisibleblocks.wordpress.com/78/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/invisibleblocks.wordpress.com/78/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/invisibleblocks.wordpress.com/78/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/invisibleblocks.wordpress.com/78/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/invisibleblocks.wordpress.com/78/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/invisibleblocks.wordpress.com/78/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/invisibleblocks.wordpress.com/78/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=invisibleblocks.wordpress.com&blog=290283&post=78&subd=invisibleblocks&ref=&feed=1" /></div>]]></content:encoded>
			<wfw:commentRss>http://invisibleblocks.wordpress.com/2008/04/14/trading-space-for-speed-memoizing-with-ruby-facets/feed/</wfw:commentRss>
	
		<media:content url="http://a.wordpress.com/avatar/bonsaigiant-128.jpg" medium="image">
			<media:title type="html">bonsaigiant</media:title>
		</media:content>
	</item>
		<item>
		<title>Why We Abstract, and What To Do When We Can&#8217;t</title>
		<link>http://invisibleblocks.wordpress.com/2008/04/05/why-we-abstract-and-what-to-do-when-we-cant/</link>
		<comments>http://invisibleblocks.wordpress.com/2008/04/05/why-we-abstract-and-what-to-do-when-we-cant/#comments</comments>
		<pubDate>Sat, 05 Apr 2008 22:34:40 +0000</pubDate>
		<dc:creator>Daniel Bernier</dc:creator>
		
		<category><![CDATA[Learning]]></category>

		<category><![CDATA[Programming]]></category>

		<category><![CDATA[Software Thinking]]></category>

		<category><![CDATA[abstraction]]></category>

		<category><![CDATA[djikstra]]></category>

		<category><![CDATA[refactoring]]></category>

		<category><![CDATA[sicp]]></category>

		<guid isPermaLink="false">http://invisibleblocks.wordpress.com/?p=74</guid>
		<description><![CDATA[Whenever you see yourself writing the same thing down more than once, there&#8217;s something wrong and you shouldn&#8217;t be doing it, and the reason is not because it&#8217;s a waste of time to write something down more than once.  It&#8217;s because there&#8217;s some idea here, a very simple idea, which has to do with [...]]]></description>
			<content:encoded><![CDATA[<div class='snap_preview'><br /><blockquote><p>Whenever you see yourself writing the same thing down more than once, there&#8217;s something wrong and you shouldn&#8217;t be doing it, and the reason is not because it&#8217;s a waste of time to write something down more than once.  It&#8217;s <strong>because there&#8217;s some idea here</strong>, a very simple idea, which has to do with the Sigma notation&#8230;not depending upon what it is I&#8217;m adding up.  And I would like to be able to always&#8230;<strong>divide the things up</strong> into as many pieces as I can, <strong>each of which I understand separately</strong>.  I would like to understand the way of adding things up, independently of what it is I&#8217;m adding up.</p>
<p><em>- Gerald Sussman, <a href="http://swiss.csail.mit.edu/classes/6.001/abelson-sussman-lectures/">SICP Lecture</a> 2a, &#8220;Higher-order Procedures&#8221; (emphasis added)</em></p></blockquote>
<blockquote><p>The purpose of abstracting is not to be vague, but to create a new semantic level in which one can be absolutely precise.</p>
<p><em>- Edsger W. Dijkstra, <a href="http://www.cs.utexas.edu/~EWD/transcriptions/EWD03xx/EWD340.html">The Humble Programmer</a></em></p></blockquote>
<blockquote><p>What Larry Wall said about Perl holds true: &#8220;When you say something in a small language, it comes out big.  When you say something in a big language, it comes out small.&#8221; The same is true for English.  The reason that biologist Ernst Haeckel could say &#8220;Ontogeny recapitulates phylogeny&#8221; in only three words was that he had these powerful words with highly specific meanings at his disposal.  We allow inner complexity of the language because it enables us to <strong>shift the complexity away </strong>from the individual utterance.</p>
<p><em>- Hal Fulton, <a href="http://www.amazon.com/Ruby-Way-Second-Addison-Wesley-Professional/dp/0672328844">The Ruby Way</a>, Introduction (emphasis added)</em></p></blockquote>
<p>Programming is our thoughts, and with better ways to express them, we can spend more time <em>thinking</em> them, and less time expressing them.</p>
<p>3 + 3 + 3 + 3 + 3 + 3 is hard&#8230;hard to read (how many threes?), hard to get right (I lost count!), hard to reason about (piles of operations!).  3 x 6 is easy, once you learn multiplication.  This is a good trade-off.  We should look for ways to add abstractions, <em>new semantic levels</em>, to our programs.</p>
<p><strong>If you&#8217;re doing the same thing twice, stop, and look for the common idea.</strong> Peel the idea away from the context, from the details.  Grasp the idea, and then use it over and over.  As a bonus, you&#8217;ll type less, re-use code, and debug less.</p>
<p>&#8220;But I can&#8217;t find ways to do that!&#8221;</p>
<p>When you look at similar bits of code, and can&#8217;t find a good way to remove the duplication, you&#8217;re hitting the limits of either your language, or your knowledge.</p>
<p>Programming languages put up very real walls, they force you down their paths, often by leaving out features.  A language without recursion puts up a wall in front of recursive solutions;  a language without first-class functions makes it tough to write higher-order functions.  Language limitations are the cause of <a href="http://en.wikipedia.org/wiki/Greenspun's_Tenth_Rule">Greenspun&#8217;s Tenth Rule</a>.</p>
<p>Sometimes, the language is not the problem.  Sometimes you just can&#8217;t find your way through.  This is why you read <a href="http://www.amazon.com/Refactoring-Improving-Design-Existing-Code/dp/0201485672">Refactoring</a>, and <a href="http://www.amazon.com/Design-Patterns-Object-Oriented-Addison-Wesley-Professional/dp/0201633612">Design Patterns</a>, but really, this is why you <a href="http://steve.yegge.googlepages.com/choosing-languages">learn other programming languages</a>.  Think about the <a href="http://weblog.raganwald.com/2007/03/why-why-functional-programming-matters.html">right way to factor the problem</a>.</p>
<p><strong>If you can&#8217;t remove the duplication, you need to work around your language, or learn some new tricks.</strong></p>
<img alt="" border="0" src="http://feeds.wordpress.com/1.0/categories/invisibleblocks.wordpress.com/74/" /> <img alt="" border="0" src="http://feeds.wordpress.com/1.0/tags/invisibleblocks.wordpress.com/74/" /> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/invisibleblocks.wordpress.com/74/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/invisibleblocks.wordpress.com/74/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/invisibleblocks.wordpress.com/74/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/invisibleblocks.wordpress.com/74/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/invisibleblocks.wordpress.com/74/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/invisibleblocks.wordpress.com/74/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/invisibleblocks.wordpress.com/74/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/invisibleblocks.wordpress.com/74/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/invisibleblocks.wordpress.com/74/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/invisibleblocks.wordpress.com/74/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=invisibleblocks.wordpress.com&blog=290283&post=74&subd=invisibleblocks&ref=&feed=1" /></div>]]></content:encoded>
			<wfw:commentRss>http://invisibleblocks.wordpress.com/2008/04/05/why-we-abstract-and-what-to-do-when-we-cant/feed/</wfw:commentRss>
	
		<media:content url="http://a.wordpress.com/avatar/bonsaigiant-128.jpg" medium="image">
			<media:title type="html">bonsaigiant</media:title>
		</media:content>
	</item>
		<item>
		<title>Ruby Facets: Symbol.to_proc, Class.to_proc</title>
		<link>http://invisibleblocks.wordpress.com/2008/03/28/ruby-facets-symbolto_proc-classto_proc/</link>
		<comments>http://invisibleblocks.wordpress.com/2008/03/28/ruby-facets-symbolto_proc-classto_proc/#comments</comments>
		<pubDate>Fri, 28 Mar 2008 16:52:57 +0000</pubDate>
		<dc:creator>Daniel Bernier</dc:creator>
		
		<category><![CDATA[Functional Programming]]></category>

		<category><![CDATA[Programming]]></category>

		<category><![CDATA[Ruby Facets Tour]]></category>

		<category><![CDATA[FacetsTour]]></category>

		<category><![CDATA[Ruby]]></category>

		<category><![CDATA[RubyFacets]]></category>

		<guid isPermaLink="false">http://invisibleblocks.wordpress.com/?p=77</guid>
		<description><![CDATA[One pretty well-know idiom in Ruby, and Facets, is Symbol.to_proc.  It lets you turn these:


[1, 2, 3].map { &#124;num&#124; num.next }  #=&#62; [2, 3, 4]

%w[alpha beta gamma].map { &#124;word&#124; word.upcase }
#=&#62; [&#34;ALPHA&#34;, &#34;BETA&#34;, &#34;GAMMA&#34;]

&#8230;into these:


[1, 2, 3].map(&#38;:next)
%w[alpha beta gamma].map(&#38;:upcase)

It&#8217;s a nice little trick, though it&#8217;s not to everyone&#8217;s taste.  If you&#8217;re already [...]]]></description>
			<content:encoded><![CDATA[<div class='snap_preview'><br /><p>One pretty well-know idiom in Ruby, and <a href="http://facets.rubyforge.org/">Facets</a>, is <code>Symbol.to_proc</code>.  It lets you turn these:</p>
<pre name="code" class="ruby">

[1, 2, 3].map { |num| num.next }  #=&gt; [2, 3, 4]

%w[alpha beta gamma].map { |word| word.upcase }
#=&gt; [&quot;ALPHA&quot;, &quot;BETA&quot;, &quot;GAMMA&quot;]
</pre>
<p>&#8230;into these:</p>
<pre name="code" class="ruby">

[1, 2, 3].map(&amp;:next)
%w[alpha beta gamma].map(&amp;:upcase)
</pre>
<p>It&#8217;s a nice little trick, though it&#8217;s not to everyone&#8217;s taste.  If you&#8217;re already comfortable with <code>Symbol.to_proc</code>, you can skip down to the <code>Class.to_proc</code> section.  But if you&#8217;re not, it&#8217;s worth a minute of your attention to learn it.  Read on&#8230;</p>
<h4>How it&#8217;s done</h4>
<p>When a method takes a block, you can call yield, to run the block.</p>
<pre name="code" class="ruby">

def with_a_block(a_param)
    yield
end
with_a_block(&#039;param&#039;) {
    puts &#039;in the block&#039;
}
</pre>
<p>Or, you can name the block as the last parameter to the method, and put an ampersand in front of it.  The ampersand makes ruby convert the block to a procedure, by calling <code>to_proc</code> on it.  (So any object with a <code>to_proc</code> method can work this way, if you want.)  This example works just like the last one:</p>
<pre name="code" class="ruby">

def named_block(a_param, &amp;blk)
    blk.call
end
named_block(&#039;my_param&#039;) {
    puts &#039;in the named block&#039;
}
</pre>
<p>Symbol&#8217;s <code>to_proc</code> method creates a procedure that takes one argument, and sends the symbol to it.  Sending a symbol to an object is the same as calling a method on it:  <code>object.send(:method)</code> works the same as <code>object.method</code>.  In the earlier <code>upcase</code> example, each word is passed to a procedure that calls <code>upcase</code> on it, giving us a list of uppercased strings.</p>
<pre name="code" class="ruby">

&amp;:upcase
# becomes...
lambda { |obj|
    obj.send(:upcase)
}
# or...
lambda { |obj|
    obj.upcase
}
</pre>
<h4>Class.to_proc</h4>
<p>So <code>Symbol.to_proc</code> creates a function that takes an argument, and calls that method on it.  <code>Class.to_proc</code> creates a function that passes its argument to its constructor, yielding an instance of itself.  This is a welcome addition to the <code>to_proc</code> family.</p>
<pre name="code" class="ruby">

require &#039;facets&#039;

class Person
    def initialize(name)
        @name = name
    end
end
names = %w[mickey minney goofy]
characters = names.map(&amp;Person)

puts characters.inspect

&amp;Person
# becomes&#8230;
lambda { |obj|
    Person.new(obj)
}
</pre>
<p><b>Why it&#8217;s nice</b></p>
<ul>
<li>It&#8217;s fewer characters &#8212; it <a href="http://people.csail.mit.edu/gregs/ll1-discuss-archive-html/msg01552.html">semantically compresses</a> your code.</li>
<li>It lets you think, <i>makes</i> you think, on a higher level.  You think about operations on your data, rather than handling one item at a time.  It raises your level of thinking.</li>
<li>It works with <a href="http://weblog.raganwald.com/2007/01/closures-and-higher-order-functions.html">first-class functions</a>, which are worth understanding.  They give you <a href="http://blog.grayproductions.net/categories/higherorder_ruby">new ways to elegantly solve some problems</a> (well, new to some audiences).  They&#8217;re not fringe anymore &#8212; they&#8217;ve been in C# since v2.0.</li>
</ul>
<img alt="" border="0" src="http://feeds.wordpress.com/1.0/categories/invisibleblocks.wordpress.com/77/" /> <img alt="" border="0" src="http://feeds.wordpress.com/1.0/tags/invisibleblocks.wordpress.com/77/" /> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/invisibleblocks.wordpress.com/77/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/invisibleblocks.wordpress.com/77/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/invisibleblocks.wordpress.com/77/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/invisibleblocks.wordpress.com/77/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/invisibleblocks.wordpress.com/77/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/invisibleblocks.wordpress.com/77/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/invisibleblocks.wordpress.com/77/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/invisibleblocks.wordpress.com/77/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/invisibleblocks.wordpress.com/77/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/invisibleblocks.wordpress.com/77/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=invisibleblocks.wordpress.com&blog=290283&post=77&subd=invisibleblocks&ref=&feed=1" /></div>]]></content:encoded>
			<wfw:commentRss>http://invisibleblocks.wordpress.com/2008/03/28/ruby-facets-symbolto_proc-classto_proc/feed/</wfw:commentRss>
	
		<media:content url="http://a.wordpress.com/avatar/bonsaigiant-128.jpg" medium="image">
			<media:title type="html">bonsaigiant</media:title>
		</media:content>
	</item>
		<item>
		<title>A Faster, Cheaper Fibonacci Definition</title>
		<link>http://invisibleblocks.wordpress.com/2008/03/22/a-faster-cheaper-fibonacci-definition/</link>
		<comments>http://invisibleblocks.wordpress.com/2008/03/22/a-faster-cheaper-fibonacci-definition/#comments</comments>
		<pubDate>Sat, 22 Mar 2008 13:43:47 +0000</pubDate>
		<dc:creator>Daniel Bernier</dc:creator>
		
		<category><![CDATA[Programming]]></category>

		<category><![CDATA[fibonacci ruby]]></category>

		<guid isPermaLink="false">http://invisibleblocks.wordpress.com/?p=75</guid>
		<description><![CDATA[The Fibonacci sequence is one of the best-known number sequences:

1
1
2
3
5
8
13
21&#8230;

Each Fibonacci number above 1 is defined as the sum of the previous two Fibonacci numbers:
F(0) = 0
F(1) = 1
F(n) = F(n-1) + F(n-2)
Just for fun, here&#8217;s another way to specify the Fibonacci sequence.  It takes fewer calculations, especially for large numbers.  The math [...]]]></description>
			<content:encoded><![CDATA[<div class='snap_preview'><br /><p>The <a href="http://en.wikipedia.org/wiki/Fibonacci_number">Fibonacci sequence</a> is one of the best-known number sequences:</p>
<ol>
<li>1</li>
<li>1</li>
<li>2</li>
<li>3</li>
<li>5</li>
<li>8</li>
<li>13</li>
<li>21&#8230;</li>
</ol>
<p>Each Fibonacci number above 1 is defined as the sum of the previous two Fibonacci numbers:</p>
<blockquote><p>F(0) = 0<br />
F(1) = 1<br />
F(n) = F(n-1) + F(n-2)</p></blockquote>
<p>Just for fun, here&#8217;s another way to specify the Fibonacci sequence.  It takes fewer calculations, especially for large numbers.  The math is basic algebra substitutions.  This could be old news &#8212; if you&#8217;ve seen this before, I&#8217;d love to hear from you.</p>
<h4>Deriving the new Fibonacci definition</h4>
<p>Before we begin, let&#8217;s notate F(n) as Fn, and F(n-1) as Fn<sub>1</sub> &#8212; it&#8217;ll make everything tidier.</p>
<p>That Fn<sub>1</sub> + Fn<sub>2</sub> part, to me, always begged for substitution.  Fn<sub>1</sub> should equal Fn<sub>2</sub> + Fn<sub>3</sub>, right?  What if we re-write Fn in terms of Fn<sub>1</sub>&#8217;s definition?  What might that lead to?</p>
<p>Fn = Fn<sub>1</sub> + Fn<sub>2</sub><br />
Fn<sub>1</sub> = Fn<sub>2</sub> + Fn<sub>3</sub><br />
Fn = Fn<sub>2</sub> + Fn<sub>2</sub> + Fn<sub>3</sub><br />
Fn = 2Fn<sub>2</sub> + Fn<sub>3</sub>, as long as n &gt; 2.</p>
<p>Pretty basic: substitute the definition for Fn<sub>1</sub> back into the definition for Fn, and simplify.  We can keep going:</p>
<p>Fn<sub>2</sub> = Fn<sub>3</sub> + Fn<sub>4</sub><br />
Fn = 2Fn<sub>2</sub> + Fn<sub>3</sub>, from above<br />
Fn = (2Fn<sub>3</sub> + 2Fn<sub>4</sub>) + Fn<sub>3</sub><br />
Fn = 3Fn<sub>3</sub> + 2Fn<sub>4</sub>, for n &gt; 3</p>
<p>&#8230;and then:</p>
<p>Fn<sub>3</sub> = Fn<sub>4</sub> + Fn<sub>5</sub><br />
Fn = (3Fn<sub>4</sub> + 3Fn<sub>5</sub>) + 2Fn<sub>4</sub><br />
Fn = 5Fn<sub>4</sub> + 3Fn<sub>5</sub>, for n &gt; 4</p>
<p>&#8230;and again:</p>
<p>Fn<sub>4</sub> = Fn<sub>5</sub> + Fn<sub>6</sub><br />
Fn = (5Fn<sub>5</sub> + 5Fn<sub>6</sub>) + 3Fn<sub>5</sub><br />
Fn = 8Fn<sub>5</sub> + 5Fn<sub>6</sub>, for n &gt; 5</p>
<p>&#8230;just one more time:</p>
<p>Fn<sub>5</sub> = Fn<sub>6</sub> + Fn<sub>7</sub><br />
Fn = 8Fn<sub>6</sub> + 8Fn<sub>7</sub> + 5Fn<sub>6</sub><br />
Fn = 13Fn<sub>6</sub> + 8Fn<sub>7</sub>, for n &gt; 6</p>
<p>See the pattern?  Look at the coefficients:</p>
<p>Fn =  <b>2</b>Fn<sub>2</sub> + <b>1</b>Fn<sub>3</sub>, for n &gt; <b>2</b><br />
Fn =  <b>3</b>Fn<sub>3</sub> + <b>2</b>Fn<sub>4</sub>, for n &gt; <b>3</b><br />
Fn =  <b>5</b>Fn<sub>4</sub> + <b>3</b>Fn<sub>5</sub>, for n &gt; <b>4</b><br />
Fn =  <b>8</b>Fn<sub>5</sub> + <b>5</b>Fn<sub>6</sub>, for n &gt; <b>5</b><br />
Fn = <b>13</b>Fn<sub>6</sub> + <b>8</b>Fn<sub>7</sub>, for n &gt; <b>6</b></p>
<p>They&#8217;re the Fibonacci sequence starting up.  Do the math, and you&#8217;ll see that the next few steps follow along.  What if we replace the coefficients with their Fibonacci indexes?  If F(6) = 8 and F(7) = 13, we can rewrite 13Fn<sub>6</sub> + 8Fn<sub>7</sub> as F(7) Fn<sub>6</sub> + F(6) Fn<sub>7</sub>.  Let&#8217;s carry that out:</p>
<p>Fn = F(3) Fn<sub>2</sub> + F(2) Fn<sub>3</sub>, for n &gt; 2<br />
Fn = F(4) Fn<sub>3</sub> + F(3) Fn<sub>4</sub>, for n &gt; 3<br />
Fn = F(5) Fn<sub>4</sub> + F(4) Fn<sub>5</sub>, for n &gt; 4<br />
Fn = F(6) Fn<sub>5</sub> + F(5) Fn<sub>6</sub>, for n &gt; 5<br />
Fn = F(7) Fn<sub>6</sub> + F(6) Fn<sub>7</sub>, for n &gt; 6</p>
<p>Let&#8217;s quickly verify this.  We know from the original definition that F(10) = 55, so let&#8217;s see whether these new versions agree.  (I&#8217;ll only test the first and last versions, to save space, but you can verify as many as you like.)</p>
<p>F(10) = 55 = F(3) Fn<sub>2</sub> + F(2) Fn<sub>3</sub><br />
F(10) = 55 = F(3) F(8) + F(2) F(7)<br />
F(10) = 55 = 2 * 21 + 1 * 13</p>
<p>F(10) = 55 = F(7) Fn<sub>6</sub> + F(6) Fn<sub>7</sub><br />
F(10) = 55 = F(7) F(4) + F(6) F(3)<br />
F(10) = 55 = 13 * 3 + 8 * 2</p>
<p>They both pass.  More generally:</p>
<p>Fn = F(x) Fn<sub>y</sub> + F(y) Fn<sub>x</sub>, for n &gt; x, and y = x - 1</p>
<p>It&#8217;s not terribly wordier than the original definition, Fn = Fn<sub>1</sub> + Fn<sub>2</sub>, for n &gt; 2.</p>
<h4>Putting this to use</h4>
<p>A nice property of this new version is that it lets us skip some steps.  If we&#8217;re calculating F(1000) with the traditional definition, we have to calculate each Fibonacci along the way; but now, we can set x = 500, and skip down to the neighborhood of F(500):</p>
<p>F(1000) = F(500) * F(501) + F(499) * F(500)</p>
<p>We can continue to skip down to about n/2, decreasing the amount of calculations we need to do.</p>
<p>Just for fun, I implemented both <code>fib_orig</code> and <code>fib_new</code> in ruby: <a href="http://danbernier.googlepages.com/new_fibonacci_tests.rb">here&#8217;s the file</a>.  I <a href="http://en.wikipedia.org/wiki/Memoization">memoized</a> the methods, for two reasons:</p>
<ol>
<li>It&#8217;s clearly much faster, and it&#8217;s simple to do.</li>
<li>It lets us see exactly which Fibonacci numbers were calculated.</li>
</ol>
<p>I put the two methods in a test case, with four test methods.</p>
<p>The first test ensures that the new equation matches the old.  Unfortunately, I could only reach 6000 with the <code>fib_orig</code>, before I ran out of stack space.</p>
<p>The second test benchmarks the two versions.  It reports the memo array size (6000 for <code>fib_orig</code>, as expected, and 40 for <code>fib_new</code> &#8212; 99.3% fewer calculations).</p>
<p>When <code>fib_orig</code> ran out of stack space so quickly, I wondered how far I could take the new version (which should recurse many fewer times).  So in the third test, I benchmarked it with progressively bigger numbers.  It starts to slow down around the million<sup>th</sup> Fibonacci number: it completes in about 12 seconds on my machine.  I suspect it&#8217;s spending the extra time array-seeking at that point, since the array gets pretty sparse &#8212; the last few non-null array indexes are: 125001 249999 250000 250001 499999 500000 500001 1000000.  Maybe I&#8217;ll try a hash&#8230;</p>
<p>The fourth test is a bit of extra-credit, and a sanity check.  Fn / F(n+1) approaches the <a href="http://en.wikipedia.org/wiki/Golden_ratio">golden ratio</a>, 1.61803398874&#8230;, as N approaches infinity.  So I calculated F(1401) / F(1400) with <code>fib_new</code>, and it&#8217;s accurate to 15 decimal points, rounding the last one, which seems to be the limit of precision on my WinXP machine.  I tried using higher Fibonacci numbers, but was warned that I was exceeding the range of ruby&#8217;s floating point numbers.  Here&#8217;s the output of that test:</p>
<pre> actual golden ratio: 1.6180339887498948482
approx. golden ratio: 1.618033988749895
precision-level test: 0.333333333333333</pre>
<p>So it seems the new approach is correct, faster, uses less space, and is still pretty elegant. Who knows whether this will ever come in handy, but at least it was fun to do.</p>
<p>F(n) = F(x) F(n-y) + F(y) F(n-x), for n &gt; x, and y = x - 1</p>
<img alt="" border="0" src="http://feeds.wordpress.com/1.0/categories/invisibleblocks.wordpress.com/75/" /> <img alt="" border="0" src="http://feeds.wordpress.com/1.0/tags/invisibleblocks.wordpress.com/75/" /> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/invisibleblocks.wordpress.com/75/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/invisibleblocks.wordpress.com/75/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/invisibleblocks.wordpress.com/75/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/invisibleblocks.wordpress.com/75/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/invisibleblocks.wordpress.com/75/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/invisibleblocks.wordpress.com/75/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/invisibleblocks.wordpress.com/75/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/invisibleblocks.wordpress.com/75/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/invisibleblocks.wordpress.com/75/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/invisibleblocks.wordpress.com/75/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=invisibleblocks.wordpress.com&blog=290283&post=75&subd=invisibleblocks&ref=&feed=1" /></div>]]></content:encoded>
			<wfw:commentRss>http://invisibleblocks.wordpress.com/2008/03/22/a-faster-cheaper-fibonacci-definition/feed/</wfw:commentRss>
	
		<media:content url="http://a.wordpress.com/avatar/bonsaigiant-128.jpg" medium="image">
			<media:title type="html">bonsaigiant</media:title>
		</media:content>
	</item>
		<item>
		<title>Hartford Ruby Brigade starts with a tour of Ruby Facets</title>
		<link>http://invisibleblocks.wordpress.com/2008/03/17/hartford-ruby-brigade-starts-with-a-tour-of-ruby-facets/</link>
		<comments>http://invisibleblocks.wordpress.com/2008/03/17/hartford-ruby-brigade-starts-with-a-tour-of-ruby-facets/#comments</comments>
		<pubDate>Tue, 18 Mar 2008 02:36:24 +0000</pubDate>
		<dc:creator>Daniel Bernier</dc:creator>
		
		<category><![CDATA[Programming]]></category>

		<category><![CDATA[Ruby Facets Tour]]></category>

		<category><![CDATA[FacetsTour]]></category>

		<category><![CDATA[Hartford.rb]]></category>

		<category><![CDATA[Ruby]]></category>

		<category><![CDATA[RubyFacets]]></category>

		<guid isPermaLink="false">http://invisibleblocks.wordpress.com/?p=76</guid>
		<description><![CDATA[As Rob Bazinet has said, the Hartford Ruby Brigade is having its first meeting on March 24.  You can get all the details from his post.  Come join us!  There&#8217;s even a book raffle.
I&#8217;ll be giving the first presentation, a tour of Ruby Facets.  Facets is a pretty huge library (even [...]]]></description>
			<content:encoded><![CDATA[<div class='snap_preview'><br /><p>As <a href="http://rbazinet.wordpress.com/2008/03/15/first-meeting-of-the-hartford-ruby-brigade/">Rob Bazinet has said</a>, the <a href="http://groups.google.com/group/hartford-ruby-brigade">Hartford Ruby Brigade</a> is having its first meeting on March 24.  You can get all the details from his post.  Come join us!  There&#8217;s even a book raffle.</p>
<p>I&#8217;ll be giving the first presentation, a tour of <a href="http://facets.rubyforge.org/">Ruby Facets</a>.  Facets is a pretty huge library (even after they moved some really neat parts into <a href="http://blow.rubyforge.org/">their</a> <a href="http://stick.rubyforge.org/">own</a> <a href="http://english.rubyforge.org/">projects</a>), and it&#8217;s crazy to think we could cover it all in one night.  I&#8217;ll quickly touch on the simple features, just to let you know they&#8217;re there, and I&#8217;ll spend more time with some of the interesting parts.  If you&#8217;re stuck, it&#8217;s a good chance Facets has what you need; the trick is knowing it&#8217;s there, and where to look &#8212; I want to point out enough of Facets to help you with that.</p>
<p>I&#8217;ll also start a <a href="http://invisibleblocks.wordpress.com/tag/FacetsTour">Tour of Facets</a> series here, starting with this post.  I&#8217;m aiming for two to four posts a month, and will cover everything in the presentation, and then some.  So, on with the tour&#8230;</p>
<p><b><i>compare_on</i> and <i>equate_on</i></b></p>
<p>Remember the first time you saw <code>attr_reader</code> and <code>attr_writer</code>?  These tiny helpers got me excited about ruby, not just because they meant less typing and DRY-er code, but because they meant <i>I</i> could make helpers to generate methods, too, if only I could think of a reason to do it.</p>
<p>Facets has a great example of why you&#8217;d want to do that: <code>compare_on</code> and <code>equate_on</code>.</p>
<p>Most ruby programmers know you can make your objects sortable by defining <code>&lt;=&gt;</code>, the spaceship method, on them.  Typically, you wind up delegating to some attribute:</p>
<pre name="code" class="ruby">

class Person
   attr_reader :fname, :lname
   def initialize(fname, lname)
      @fname, @lname = fname, lname
   end
   def &lt;=&gt;(person)
      @lname.&lt;=&gt;(person.lname)
   end
end
</pre>
<p>Facets adds <code>compare_on</code>, which generates the spaceship method for you, based on that attribute.  Not only that, but you can <code>compare_on</code> multiple fields, and it handles the hairy logic for you automatically:</p>
<pre name="code" class="ruby">

require &#039;facets/compare_on&#039;

class Person
   attr_reader :fname, :lname
   def initialize(fname, lname)
      @fname, @lname = fname, lname
   end
   compare_on :lname, :fname
end

people = []
people.push Person.new(&#039;Adam&#039;, &#039;Smith&#039;)
people.push Person.new(&#039;John&#039;, &#039;Adams&#039;)

people.sort #=&gt; John Adams, Adam Smith
</pre>
<p>Correctly implementing the spaceship operator isn&#8217;t too hard, but object equality gets tricky in any language.  Facets helps you here by implementing ruby&#8217;s main three equality methods for you: <code>==</code>, <code>eql?</code>, and <code>hash</code>.</p>
<pre name="code" class="ruby">

require &#039;facets/compare_on&#039;

class Person
   attr_reader :fname, :lname
   def initialize(fname, lname)
      @fname, @lname = fname, lname
   end
   equate_on :lname, :fname
end

a_pres = Person.new(&#039;John&#039;, &#039;Adams&#039;)
another_pres = Person.new(&#039;John&#039;, &#039;Adams&#039;)
[a_pres].include?(another_pres) #=&gt; true
</pre>
<p>Again, you can equate on multiple attributes (<code>fname</code> and <code>lname</code>), and it handles all the details for you. Hope to see you at the Hartford Ruby Brigade!</p>
<img alt="" border="0" src="http://feeds.wordpress.com/1.0/categories/invisibleblocks.wordpress.com/76/" /> <img alt="" border="0" src="http://feeds.wordpress.com/1.0/tags/invisibleblocks.wordpress.com/76/" /> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/invisibleblocks.wordpress.com/76/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/invisibleblocks.wordpress.com/76/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/invisibleblocks.wordpress.com/76/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/invisibleblocks.wordpress.com/76/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/invisibleblocks.wordpress.com/76/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/invisibleblocks.wordpress.com/76/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/invisibleblocks.wordpress.com/76/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/invisibleblocks.wordpress.com/76/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/invisibleblocks.wordpress.com/76/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/invisibleblocks.wordpress.com/76/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=invisibleblocks.wordpress.com&blog=290283&post=76&subd=invisibleblocks&ref=&feed=1" /></div>]]></content:encoded>
			<wfw:commentRss>http://invisibleblocks.wordpress.com/2008/03/17/hartford-ruby-brigade-starts-with-a-tour-of-ruby-facets/feed/</wfw:commentRss>
	
		<media:content url="http://a.wordpress.com/avatar/bonsaigiant-128.jpg" medium="image">
			<media:title type="html">bonsaigiant</media:title>
		</media:content>
	</item>
		<item>
		<title>Continuations: a warm-up</title>
		<link>http://invisibleblocks.wordpress.com/2008/03/13/continuations-a-warm-up/</link>
		<comments>http://invisibleblocks.wordpress.com/2008/03/13/continuations-a-warm-up/#comments</comments>
		<pubDate>Thu, 13 Mar 2008 20:53:12 +0000</pubDate>
		<dc:creator>Daniel Bernier</dc:creator>
		
		<category><![CDATA[Functional Programming]]></category>

		<category><![CDATA[JavaScript]]></category>

		<category><![CDATA[Ruby]]></category>

		<category><![CDATA[scheme]]></category>

		<guid isPermaLink="false">http://invisibleblocks.wordpress.com/?p=67</guid>
		<description><![CDATA[Continuations and continuation-passing style (CPS) are introduced in The Little Schemer, chapter 8, using collectors: functions that collect values, through being repeatedly redefined.  It was a tough chapter for me, but the idea is simple once you get it, so I&#8217;d like to leave some help for others.  I&#8217;ll use Ruby for the [...]]]></description>
			<content:encoded><![CDATA[<div class='snap_preview'><br /><p><a href="http://en.wikipedia.org/wiki/Continuation">Continuations</a> and <a href="http://en.wikipedia.org/wiki/Continuation-passing_style">continuation-passing style</a> (CPS) are introduced in <a href="http://www.amazon.com/Little-Schemer-Daniel-P-Friedman/dp/0262560992">The Little Schemer</a>, chapter 8, using collectors: functions that collect values, through being repeatedly redefined.  It was a tough chapter for me, but the idea is simple once you get it, so I&#8217;d like to leave some help for others.  I&#8217;ll use Ruby for the examples, with some JavaScript and Scheme at the end.</p>
<p>In languages with first-class functions, you can assign functions to variables, and re-assign those variables.  Consider this Ruby example:</p>
<pre name="code" class="ruby">

func = lambda { |x| puts x }

[&#039;a&#039;, &#039;b&#039;, &#039;c&#039;].each { |ch|
    old_func = func
    func = lambda { |x| old_func[x + ch] }
}

func[&#039;d&#039;]  #=&gt; prints &#039;dcba&#039;
</pre>
<p>By re-defining <code>func</code> in terms of <code>old_func</code>, we&#8217;re building up a recursive computation.  It&#8217;s like normal recursion, but approached from the other side &#8212; without explicit definitions.  Since a Ruby function is a closure, it remembers the value of the variables in scope when it was created; each layer of this recursion holds its own value for <code>ch</code> and <code>old_func</code>.  When we call the last <code>func</code>, it sees <code>ch</code> = &#8216;c&#8217; and <code>x</code> = &#8216;d&#8217;.  It concatenates them, and calls its version of <code>old_func</code>&#8230;which sees <code>x</code> = &#8216;dc&#8217; and <code>ch</code> = &#8216;b&#8217;, concatenates them, and passes it to <i>its</i> <code>old_func</code>, and so on.In fact, if we wrote it like this, the execution of all those lambdas would be exactly the same:</p>
<pre name="code" class="ruby">

func_puts = lambda { |x| puts x }
func_add_a = lambda { |x| func_puts[x + &#039;a&#039;] }
func_add_b = lambda { |x| func_add_a[x + &#039;b&#039;] }
func_add_c = lambda { |x| func_add_b[x + &#039;c&#039;] }
func_add_c[&#039;d&#039;]  #=&gt; prints &#039;dcba&#039;
</pre>
<p>We could calculate factorials this way:</p>
<pre name="code" class="ruby">

def factorial(n, func)
    if n == 1
        func[1]
    else
        factorial(n - 1, lambda { |i| func[i * n] })
    end
end
factorial(3, lambda { |fact| puts fact })  #=&gt; prints 6
</pre>
<ol>
<li>On the first call to factorial, <code>n</code> = 3, and <code>func</code> just prints its argument.  But <code>func</code> isn&#8217;t called yet&#8230;since <code>n</code> isn&#8217;t 1, we recurse with <code>n - 1</code> = 2, and a new function that calls <code>func</code> with its argument <code>i</code> times<code></code> 3.</li>
<li>On the recurse, <code>n</code> = 2, and <code>func</code> calls the original printer <code>func </code>with its argument <code>i</code> times 3.  Since <code>n</code> still isn&#8217;t 1, we recurse again, with <code>n - 1</code> = 1, and a new function that calls our <code>func</code> with <i>its</i> argument <code>i</code> times 2.</li>
<li>On the final round, <code>n</code> = 1, so we (finally!) call <code>func</code> with 1, which&#8230;</li>
<li>&#8230;calls the previous <code>func</code> with 1 * 2, which&#8230;</li>
<li>&#8230;calls the <i>original</i> <code>func</code> with (1 * 2) * 3, which&#8230;</li>
<li>prints 6.</li>
</ol>
<p>As <code>factorial</code> recurses, it builds up a recursive tower of <code>func</code> calls.  In <code>factorial</code>&#8217;s base case, the last (and outermost) <code>func</code> is called, and we begin to climb down the <code>func </code>tower, to its bottom floor, the original <code>func</code>.  It&#8217;s recursion in two directions.</p>
<p>In case Ruby isn&#8217;t your favorite language, here are versions in JavaScript and Scheme:</p>
<pre name="code" class="jscript">

function factorial(n, func) {
    if (n == 1)
        func(1)
    else
        factorial(n - 1, function(i) {
            func(n * i)
        });
}

factorial(3, function(fact) { print(fact) })
</pre>
<pre>; Too bad WordPress doesn't format Scheme or Lisp!
(define factorial
  (lambda (n func)
    (cond ((= n 1) (func 1))
          (else (factorial (- n 1)
                           (lambda (i) (func (* n i))))))))

; Here, the original func is just an identity function.
(factorial 4 (lambda (fact) fact))</pre>
<p>Once this is clear, you can see many other applications:</p>
<ul>
<li>You could find all the even numbers in a list: instead of passing a number to <code>func</code>, pass the list of even numbers, and add each even number in.</li>
<li>You could separate the numbers into evens and odds: instead of passing just one list to <code>func</code>, pass two lists, for evens and odds, and add each number to the correct list.</li>
<li>You could separate any list of items by <i>any</i> criteria:  instead of hard-coding &#8220;is even?&#8221; into the function, pass a predicate function.  (Maybe you want to extract all occurrences of &#8216;tuna&#8217; from a list of words.)</li>
</ul>
<p>That should be enough of a warm-up for chapter 8.  See you in chapter 9, when they derive the <a href="http://en.wikipedia.org/wiki/Y_combinator">Y-combinator</a>!</p>
<img alt="" border="0" src="http://feeds.wordpress.com/1.0/categories/invisibleblocks.wordpress.com/67/" /> <img alt="" border="0" src="http://feeds.wordpress.com/1.0/tags/invisibleblocks.wordpress.com/67/" /> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/invisibleblocks.wordpress.com/67/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/invisibleblocks.wordpress.com/67/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/invisibleblocks.wordpress.com/67/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/invisibleblocks.wordpress.com/67/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/invisibleblocks.wordpress.com/67/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/invisibleblocks.wordpress.com/67/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/invisibleblocks.wordpress.com/67/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/invisibleblocks.wordpress.com/67/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/invisibleblocks.wordpress.com/67/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/invisibleblocks.wordpress.com/67/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=invisibleblocks.wordpress.com&blog=290283&post=67&subd=invisibleblocks&ref=&feed=1" /></div>]]></content:encoded>
			<wfw:commentRss>http://invisibleblocks.wordpress.com/2008/03/13/continuations-a-warm-up/feed/</wfw:commentRss>
	
		<media:content url="http://a.wordpress.com/avatar/bonsaigiant-128.jpg" medium="image">
			<media:title type="html">bonsaigiant</media:title>
		</media:content>
	</item>
	</channel>
</rss>