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

<channel>
	<title>Building Blocks</title>
	<atom:link href="http://chimu.wordpress.com/feed/" rel="self" type="application/rss+xml" />
	<link>http://chimu.wordpress.com</link>
	<description>Building Software Better</description>
	<lastBuildDate>Wed, 17 Sep 2008 23:41:33 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.com/</generator>
<cloud domain='chimu.wordpress.com' port='80' path='/?rsscloud=notify' registerProcedure='' protocol='http-post' />
<image>
		<url>http://s2.wp.com/i/buttonw-com.png</url>
		<title>Building Blocks</title>
		<link>http://chimu.wordpress.com</link>
	</image>
	<atom:link rel="search" type="application/opensearchdescription+xml" href="http://chimu.wordpress.com/osd.xml" title="Building Blocks" />
	<atom:link rel='hub' href='http://chimu.wordpress.com/?pushpress=hub'/>
		<item>
		<title>Scratch Textual Language</title>
		<link>http://chimu.wordpress.com/2008/09/17/scratch-textual-language/</link>
		<comments>http://chimu.wordpress.com/2008/09/17/scratch-textual-language/#comments</comments>
		<pubDate>Wed, 17 Sep 2008 20:28:43 +0000</pubDate>
		<dc:creator>Mark</dc:creator>
				<category><![CDATA[Scratch]]></category>

		<guid isPermaLink="false">http://chimu.wordpress.com/?p=195</guid>
		<description><![CDATA[Scratch is a visual programming language, but it might usefully have a textual version as well. Scratch in it&#8217;s graphical form can verify syntax intuitively &#38; automatically, and the resulting graphics are definitely beautiful, but it took quite some effort to produce these diagrams when trying to document a program, and it is even harder [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=chimu.wordpress.com&amp;blog=4683676&amp;post=195&amp;subd=chimu&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p><a href="http://scratch.mit.edu/">Scratch</a> is a visual programming language, but it might usefully have a textual version as well.  Scratch in it&#8217;s graphical form can verify syntax intuitively &amp; automatically, and the resulting graphics are definitely beautiful, but it took quite some effort to produce <a href="a-taste-of-scratch">these diagrams</a> when trying to document a program, and it is even harder to reference sections of the diagram.</p>
<p>This activity came out of producing a Scratch Player in Flash, and I wanted to see whether the parse of the file produced the correct program.  A textual dump of the parse was an obvious solution, but then this &#8216;dump&#8217; might as well be the same as a complete program declaration so it was clearly &#8216;complete&#8217; and I wasn&#8217;t missing anything.<br />
<span id="more-195"></span> </p>
<h2>Scratch Textual</h2>
<p>The core concepts in this proposed textual language for Scratch are:</p>
<ul>
<li>It should match Scratch as closely as possible</li>
<li>It should be a readable and easily writeable textual language (vs. XML as an interchange format)</li>
<li>It should be translatable to other human languages for the blocks (as Scratch is)</li>
<li>It should be really simple to produce and parse</li>
<li>Given Scratch is graphical, visual indentation is reasonable</li>
<li>It is not a complete &#8216;dump&#8217; of the Scratch project &#8212; no media resources are included.</li>
</ul>
<p>The above concepts produced the following initial choices:</p>
<ul>
<li>Different sections start with simple keywords: &#8220;stage:&#8221; and &#8220;sprite:&#8221; for the main objects, &#8220;vars:&#8221; and &#8216;listVars:&#8221; for declaring variables, &#8220;comment:&#8221; for a comment section, and &#8220;script:&#8221; for declaring a sequence of blocks.</li>
<li>Variables simply define their name and an initial value (if desired&#8230; otherwise it would be &#8217;0&#8242;)</li>
<li>Each block is written out textually with its &#8216;spec&#8217; &#8212; a human readable description of the block and its parameters</li>
<li>The parameters to a block (if any) come immediately after, and are preferably indented [say 4 spaces] from the block they are parameters too.  Note that the indentation is not necessary because you can tell the number of parameters from the block &#8216;spec&#8217;, but indenting makes it more readable.</li>
<li>If a block can contain other blocks, contained blocks _must be_ indented [say 4 spaces] so you can tell they are inside the block vs. after the block.  This is in a fashion similar to Python.</li>
<li>There should be no blank line within a &#8216;script:&#8217; section.  The end of a script: section is the first blank (non-comment) line.</li>
<li>Comments within the textual blocks use &#8216;#&#8217; to match with Python.  Multi-line comments do not exist.  Note that Textual Comments are not parsed at all (and do not round-trip), so they should be minimal and merely augment parsing the textual source &#8212; use &#8216;comment:&#8217; for real documentation.</li>
<li>&#8216;script:&#8217; and &#8216;comment:&#8217; could have position information after them using the &#8216;loc&#8217; property (e.g. &#8220;loc = 500@250&#8243;) but this is not likely to be useful since any edits would cause positions to be wrong</li>
</ul>
<h3>An Example</h3>
<p>The following is a complete &#8220;normal expanded format&#8221; version.  See further below for a possible optimization to make things more vertically compressed.</p>
<p><pre class="brush: python;">

#===========================
#=== Morph: Stage 
#===========================
stage: Stage

#============
#=== Vars 
#============

vars:
talest-pole-height = 6
previous-moved-disk = 0
potential-disk = 1
num-disks = 5
next-disk = 0
base-disk = 0

listVars:
pole-1 = undefined
pole-2 = undefined
moveable-disks = undefined
pole-3 = undefined

#============
#=== Script 
#============
script:

when 'find-next-disk'
set next-disk to %n
    0
broadcast %e and wait
    propose-next-disk
repeat until %b  
    %n &gt; %n
        next-disk  
        0
    set potential-disk to %n
    if %b  
        not %b
            %n = %n
                potential-disk  
                previous-moved-disk  
        set next-disk to %n
            potential-disk  
broadcast %e and wait
    move-next-disk

#============
#=== Script 
#============
script:

when 'Scratch-StartClicked'
set num-disks to %n
    5
set base-disk to %n
    %n + %n
        num-disks  
        1
set next-disk to %n
    num-disks  
repeat until %b  
    %n &lt; %n
        next-disk  
        1
    set next-disk to %n
        %n - %n
            next-disk  
            1
broadcast %e and wait
    initialize
set previous-moved-disk to %n
    0
set talest-pole-height to %n
    0
repeat until %b  
    %n &gt; %n
        talest-pole-height  
        num-disks  
    broadcast %e and wait
        find-next-disk
    set talest-pole-height to %n
    if %b  
        %n &gt; %n
            talest-pole-height  
        set talest-pole-height to %n


#===========================
#=== Morph: Sprite1 
#===========================
sprite: Sprite1

#============
#=== Vars 
#============

vars:
can-move = 3
am-on-top = 1
disk-id = 1
pole = 3
height = 6
previous-pole = 1
pole-at-start = 1

#============
#=== Script 
#============
script:

when 'move-next-disk'
if %b  
    %n = %n
        disk-id  
        next-disk  
    set previous-moved-disk to %n
        disk-id  
    set pole-at-start to %n
        pole  
    if %b  
        %b and %b
            not %b
                %b or %b
                    %n = %n
                        previous-pole  
                        1
                    %n = %n
                        pole  
                        1
            %n &lt; %n
                disk-id  
        set pole to %n
            1
    if %b  
        %b and %b
            not %b
                %b or %b
                    %n = %n
                        previous-pole  
                        2
                    %n = %n
                        pole  
                        2
            %n &lt; %n
                disk-id  
        set pole to %n
            2
    if %b  
        %b and %b
            not %b
                %b or %b
                    %n = %n
                        previous-pole  
                        3
                    %n = %n
                        pole  
                        3
            %n &lt; %n
                disk-id  
        set pole to %n
            3
    set previous-pole to %n
        pole-at-start  
    if %b  
        %n = %n
            previous-pole  
            1
    if %b  
        %n = %n
            previous-pole  
            2
    if %b  
        %n = %n
            previous-pole  
            3
    if %b  
        %n = %n
            pole  
            1
        set height to %n
    if %b  
        %n = %n
            pole  
            2
        set height to %n
    if %b  
        %n = %n
            pole  
            3
        set height to %n

#============
#=== Script 
#============
script:

when 'propose-next-disk'
set am-on-top to %n
    0
set can-move to %n
    0
if %b  
    %b and %b
        %n = %n
            pole  
            1
        %n = %n
            disk-id  
    set am-on-top to %n
        1
if %b  
    %b and %b
        %n = %n
            pole  
            2
        %n = %n
            disk-id  
    set am-on-top to %n
        1
if %b  
    %b and %b
        %n = %n
            pole  
            3
        %n = %n
            disk-id  
    set am-on-top to %n
        1
if %b  
    %n &gt; %n
        am-on-top  
        0
    if %b  
        %b and %b
            not %b
                %b or %b
                    %n = %n
                        previous-pole  
                        1
                    %n = %n
                        pole  
                        1
            %n &lt; %n
                disk-id  
        set can-move to %n
            1
    if %b  
        %b and %b
            not %b
                %b or %b
                    %n = %n
                        previous-pole  
                        2
                    %n = %n
                        pole  
                        2
            %n &lt; %n
                disk-id  
        set can-move to %n
            2
    if %b  
        %b and %b
            not %b
                %b or %b
                    %n = %n
                        previous-pole  
                        3
                    %n = %n
                        pole  
                        3
            %n &lt; %n
                disk-id  
        set can-move to %n
            3
    if %b  
        %n &gt; %n
            can-move  
            0

#============
#=== Script 
#============
script:

when 'initialize'
set disk-id to %n
    1
set pole to %n
    1
set previous-pole to %n
    0
set can-move to %n
    0
set am-on-top to %n
    0
set height to %n
    %n + %n
        %n - %n
            base-disk  
            disk-id  
        1
</pre></p>
<h3>Vertical Compression</h3>
<p>The format above has every block on its own line.  This is readable and informative (you can see the argument types) but is vertically expansive.  Assuming parentheses or some other paired delimiter are not used for anything else in names, we could replace the argument placeholders with parentheses like below.  This gives a more lisp-like feel, at least for the inner evaluations.  If you leave one or more placeholders off, they would come from the next lines in &#8216;missing&#8217; order, kind of like a macro.</p>
<p><pre class="brush: python;">
script:

when 'find-next-disk'
set next-disk to (0)
broadcast (propose-next-disk) and wait
repeat until ((next-disk) &gt; (0))
    set potential-disk to (0)
    if (not ( (potential-disk) = (previous-moved-disk)) )
        set next-disk to (potential-disk)
broadcast (move-next-disk) and wait

</pre></p>
<br /><img alt="" border="0" src="http://feeds.wordpress.com/1.0/categories/chimu.wordpress.com/195/" /> <img alt="" border="0" src="http://feeds.wordpress.com/1.0/tags/chimu.wordpress.com/195/" /> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/chimu.wordpress.com/195/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/chimu.wordpress.com/195/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/chimu.wordpress.com/195/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/chimu.wordpress.com/195/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/chimu.wordpress.com/195/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/chimu.wordpress.com/195/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/chimu.wordpress.com/195/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/chimu.wordpress.com/195/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/chimu.wordpress.com/195/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/chimu.wordpress.com/195/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/chimu.wordpress.com/195/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/chimu.wordpress.com/195/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/chimu.wordpress.com/195/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/chimu.wordpress.com/195/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=chimu.wordpress.com&amp;blog=4683676&amp;post=195&amp;subd=chimu&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://chimu.wordpress.com/2008/09/17/scratch-textual-language/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/e8534283d788fb4fe8854c40a124361d?s=96&#38;d=identicon" medium="image">
			<media:title type="html">marklfussell</media:title>
		</media:content>
	</item>
		<item>
		<title>A Taste of Scratch</title>
		<link>http://chimu.wordpress.com/2008/09/08/a-taste-of-scratch/</link>
		<comments>http://chimu.wordpress.com/2008/09/08/a-taste-of-scratch/#comments</comments>
		<pubDate>Mon, 08 Sep 2008 04:15:13 +0000</pubDate>
		<dc:creator>Mark</dc:creator>
				<category><![CDATA[Ruby]]></category>
		<category><![CDATA[Scratch]]></category>
		<category><![CDATA[Smalltalk]]></category>

		<guid isPermaLink="false">http://chimu.wordpress.com/?p=169</guid>
		<description><![CDATA[One of my favored books in the 1980s was ‘A Taste of Smalltalk’. This was a very short book that gave you the flavor of Smalltalk programming (the language and IDE) as compared to Pascal, C, and Lisp. I believe it is always important to show multiple programming languages for concepts and this book followed [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=chimu.wordpress.com&amp;blog=4683676&amp;post=169&amp;subd=chimu&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>One of my favored books in the 1980s was ‘A Taste of Smalltalk’. This was a very short book that gave you the flavor of Smalltalk programming (the language and IDE) as compared to Pascal, C, and Lisp. I believe it is always important to show multiple programming languages for concepts and this book followed that rule. The goal of this post-series is to take ‘A Taste of Smalltalk’ and apply it to Scratch (a visual programming language).  This is the third of my comparisons in this series, where the first one was in Ruby.</p>
<p><span id="more-169"></span><br />
You can find the original book here:</p>
<ul>
<li><a href="http://www.iam.unibe.ch/~ducasse/FreeBooks/Taste/">A Taste of Smalltalk</a></li>
<li><a href="http://stephane.ducasse.free.fr/FreeBooks.html">Free Smalltalk Books</a></li>
</ul>
<p>Given the original book is available online, I will not repeat it.</p>
<p>You can both see the example in Scratch and get tools and background on the Scratch project at:<br />
<a href="http://scratch.mit.edu/projects/parseroo/260752">Tower of Hanoi</a>.  The scratch tools and the community web site are free.</p>
<h2>Tower of Hanoi &#8212; Object-Oriented (V4) &#8212; Scratch</h2>
<p>The standard pattern for this series is to translate as closely as possible each of the chapters in &#8220;A Taste of Smalltalk&#8221; to the new target language.  This worked reasonably well for Ruby and Flex &#8212; the Smalltalk was translated and interesting features of the language came out with each translation.  But this approach utterly fails for Scratch because the first two &#8216;models&#8217; of the Hanoi algorithm are completely dependent on recursion, which Scratch does not have.  Even the third, stack-less version of Hanoi requires inter-object calls that Scratch can not handle.  So _none_ of the algorithms within &#8220;A Taste of Smalltalk&#8221; can be directly translated to Scratch.</p>
<p>This might appear to be a limitation of the language (and in some ways it certainly is), but somewhat impressively, I believe thinking about this problem, with the restrictions of Scratch, actually leads to a better design solution than any of the ones in the book.  It is certainly a very object-oriented solution, where the &#8216;Hanoi Disks&#8217; have a lot of intelligence and are made as responsible as possible for figuring out what to do next.  This version of the algorithm, I will call &#8216;V4&#8242;.</p>
<h3>The V4 Algorithm</h3>
<p>The V4 Algorithm works as follows:</p>
<ol>
<li>Ask each of the disks whether they have a legal move</li>
<li>Decide which of the disks with a legal move should move</li>
<li>Tell that disk to move</li>
</ol>
<p>The interesting parts of this algorithm are that:</p>
<ul>
<li>Step 1 can be completely parallel.  You can ask 1 to 1000000 disks at the same moment whether they have a legal move.</li>
<li>Step 2 is really trivial: just don&#8217;t move the same disk you did last time</li>
</ul>
<p>Compared to the V3 version, the V4 version puts more intelligence in the disks (and less in the tower), couples them less, and supports mass parallel-execution.  The parallel-execution is not useful in Hanoi, but the concepts behind it are definitely very interesting &#8212; and Scratch&#8217;s restrictions forces this kind of &#8216;sophisticated&#8217; approach [or at least it forced me down this path to maintain code-sanity and maintainability].</p>
<h3>The main Scratch Player view</h3>
<p>Scratch is designed to be an easy-to-learn language and environment.  Its heritage is along the lines of the spirit of Logo: there is a Stage drawing area and a default Sprite (a Cat) that you interact with for animation and drawing.  But this Stage can also show the variables involved with the program.  So it produces a nice overview of the whole Hanoi program:</p>
<p><a href="http://chimu.files.wordpress.com/2008/09/atasteofscratch_d3.png"><img src="http://chimu.files.wordpress.com/2008/09/atasteofscratch_d3.png" alt="" title="Tower of Hanoi -- Graphical Overview" width="491" height="438" class="alignnone size-full wp-image-180" /></a></p>
<p>Not all application variables are shown, but those shown are the most important ones.  The details of the variables will be gone over later, but some are self-evident:</p>
<ul>
<li>num-disks: The number of disks (the height) of the Tower of Hanoi</li>
<li>pole-#: A List (treated as a Stack) of Disk identifiers, where &#8217;6&#8242; = a base (immovable) disk</li>
<li>movable-disks: A List of disks that can be moved.  This is transitory for each iteration of the algorithm.</li>
</ul>
<p>If you click the &#8216;Green Flag&#8217;, the program executes and on pretty much every step the display is updated, so you can see disks being proposed and moved (in both animation and variables).  Independently of Scratch having a graphical programming language, it has a very nice graphical development and run environment.</p>
<h3>Application Variables</h3>
<p>The application variables are shown below.  All of these are &#8216;Globals&#8217; and can be accessed by any object.  Those variables colored in red are lists and those colored in orange are numbers/strings/etc.  All the variables that have check-marks next to them are being displayed on top of the Stage above.</p>
<p><a href="http://chimu.files.wordpress.com/2008/09/atasteofscratch_d1.png"><img src="http://chimu.files.wordpress.com/2008/09/atasteofscratch_d1.png" alt="" title="Application Variables" width="224" height="220" class="alignnone size-full wp-image-178" /></a></p>
<p>There is no such thing as a &#8216;local&#8217; variable (private to a block of code), so it might be useful to use a naming prefix to differentiate between &#8216;local&#8217; variables (like &#8216;potential-disk&#8217;) from instance variables and even &#8216;parameter&#8217; variables that go with a broadcast (&#8216;next-disk&#8217;).  But in-the-small, that is not particularly important.</p>
<h3>Application Initialization</h3>
<p>Now that we have an overview of the application and its global state variables, we can start working through the algorithm itself.  The main &#8216;Object&#8217; in Scratch is the Stage, and I made this own the outer-most aspects of the Hanoi application and algorithm.  The first activity is &#8216;Initialization&#8217;, which is triggered by the &#8216;Green Flag&#8217; [my particular choice].  </p>
<p><a href="http://chimu.files.wordpress.com/2008/09/atasteofscratch_d2.png"><img src="http://chimu.files.wordpress.com/2008/09/atasteofscratch_d2.png" alt="" title="Application Initialization" width="487" height="616" class="alignnone size-full wp-image-179" /></a></p>
<p>Because this is the first example of Scratch, I will walk through the sections of the code and what they do with a few visual marker numbers (see the right column of blue).</p>
<p>When the Stage gets the Green Flag event: </p>
<ol>
<li>It sets the number of disks to &#8217;5&#8242;.  This is hard-coded because Scratch is currently unable to clone Sprites (objects) on the fly, so we have to precreate all the needed sprites.  In any case, this is simple enough to change if someone wants.  The additional variable &#8216;base-disk&#8217; is defined so it can be used below.  &#8216;base-disk&#8217; is just a local variable and is never used again. After this, we just clear the lists so they are &#8216;clean&#8217;</li>
<li>Next we add the &#8216;base-disk&#8217; to the bottom of each pole.  The base-disks are invisible and immovable (no matching Sprite/Object), so this is a very clean way of making the algorithm simpler later on. </li>
<li>Next we add the disks to &#8216;pole-1&#8242; using what should be another local variable.  Later I reuse this variable [something I don't like doing] just because we otherwise have a clutter of variables.</li>
<li>Next we send out a broadcast to _all objects_ telling them to initialize themselves.  There is no direct message send to an object, so it is up to the other objects to know what to respond to and what to ignore.  The broadcast waits until all object&#8217;s acknowledge they are finished.</li>
<li>Finally, we go into the main loop.  Until all the disks have moved to a new pole, we will execute &#8216;find-next-disk&#8217; which both finds and moves the next disk.  When we are done, we make a noise <img src='http://s0.wp.com/wp-includes/images/smilies/icon_smile.gif' alt=':-)' class='wp-smiley' /> </li>
</ol>
<h3>Find and Move Next Disk</h3>
<p>The main part of the algorithm has some nice aspects and some nastier aspects.  The nice side: We simply send out a broadcast of &#8216;propose-next-disk&#8217;, which all Disks should respond to by adding themselves to &#8216;movable-disks&#8217; if they have a desire to move.  This will only ever be one or two movable disks at any given time.  One of those disks may have been moved immediately previously, so we skip over it.  The selected disk is put into &#8216;next-disk&#8217; and another broadcast goes out &#8220;move-next-disk&#8221;.  The second broadcast is not really a broadcast.  It is a message send to &#8216;next-disk&#8217;, but it is only by the disks themselves ignoring a broadcast that isn&#8217;t to them that it becomes a message send.  So that is slightly nasty.</p>
<p>In any case, the code is pretty clean and concise, and this ends the code on the Stage itself.  The rest of the algorithm is on the Disks.</p>
<p><a href="http://chimu.files.wordpress.com/2008/09/atasteofscratch_d4.png"><img src="http://chimu.files.wordpress.com/2008/09/atasteofscratch_d4.png" alt="" title="Find and Move Next Disk " width="398" height="316" class="alignnone size-full wp-image-182" /></a></p>
<h3>Disks Variables</h3>
<p>The Disks have access to all the Stage global variables.  In addition, each Sprite can have its own instance-private variables, which are either true instance variables (&#8216;disk-id&#8217;, &#8216;pole&#8217;, &#8216;previous-pole&#8217;) or would be local variables if Scratch supported them (&#8216;can-move&#8217;, &#8216;am-on-top&#8217;, etc.)</p>
<p><a href="http://chimu.files.wordpress.com/2008/09/atasteofscratch_d5.png"><img src="http://chimu.files.wordpress.com/2008/09/atasteofscratch_d5.png" alt="" title="Hanoi Disk Variables" width="182" height="149" class="alignnone size-full wp-image-183" /></a></p>
<p>Instance variables can be displayed on the Stage also, but this becomes overwhelming if all instances are turned on.</p>
<h3>Disk Initialization</h3>
<p>Upon receiving the &#8216;initialize&#8217; broadcast, all Disks set their &#8216;disk-id&#8217; (which must be different for each disk), and then set themselves up properly in size, color, and move onto the correct pole.</p>
<p><a href="http://chimu.files.wordpress.com/2008/09/atasteofscratch_d6.png"><img src="http://chimu.files.wordpress.com/2008/09/atasteofscratch_d6.png" alt="" title="Hanoi Disk Initialization" width="362" height="274" class="alignnone size-full wp-image-186" /></a></p>
<h3>Propose Next Disk</h3>
<p>Scratch has certain deficiencies that rear their heads badly in the Hanoi code.  The concept of Propose Next Disk is as simple as:</p>
<pre style="background-color:#eef;font-size:1.3em;padding:10px;">
If
   * I am on-top of a pole
   * And I can move to a new pole (with a bigger disk on its top)
   * And that new pole isn't the pole I just came from
Then
   * Add myself to the movable-disks list
</pre>
<p>But because Scratch (or my knowledge of Scratch) is deficient in dynamic referencing of variables, the &#8216;propose-next-disk&#8217; code needs to expand all the potential pole values from 1 through 3.  Fortunately this is only a three-valued expansion, but the code looks quite nasty for being as simple as the above.</p>
<p><a href="http://chimu.files.wordpress.com/2008/09/atasteofscratch_d7.png"><img src="http://chimu.files.wordpress.com/2008/09/atasteofscratch_d7.png" alt="" title="Propose Next Disk" width="640" height="613" class="alignnone size-full wp-image-184" /></a></p>
<h3>Move Next Disk</h3>
<p>The Move Next Disk code has (1) the filter on the broadcast (in this case by &#8216;disk-id&#8217;) to make it only go to a single object and (2) a ton of noise due to &#8216;pole&#8217; expansion mentioned above.  But the code gets the job done and it looks fairly colorful <img src='http://s0.wp.com/wp-includes/images/smilies/icon_smile.gif' alt=':-)' class='wp-smiley' /> </p>
<p><a href="http://chimu.files.wordpress.com/2008/09/atasteofscratch_d8.png"><img src="http://chimu.files.wordpress.com/2008/09/atasteofscratch_d8.png" alt="" title="Move Next Disk" width="650" height="887" class="alignnone size-full wp-image-185" /></a></p>
<h2>Conclusions</h2>
<p>I was impressed that Scratch was able to get Tower of Hanoi to run properly.  Scratch has actively avoided certain features that the Scratch team finds are difficult to understand.  But the toolbox of event processing, broadcasts, lists, and Sprites (objects with Stage presence <img src='http://s0.wp.com/wp-includes/images/smilies/icon_smile.gif' alt=':-)' class='wp-smiley' />  ) are rich enough that a pre-sized Hanoi can be created and will run correctly.  A dynamic Hanoi would require Sprite cloning, which is not in Scratch 1.3.</p>
<p>The nastiest aspect to Scratch was its inability to dynamically reference the pole lists.  And a missing feature to Scratch are simple procedures (for example, the &#8216;glide&#8217; code is repeated twice).  The missing recursion is clearly another missing feature, but in this case getting rid of that recursion made the algorithm somewhat nicer.</p>
<p>On the whole, Scratch is a very inspiring visual language and development environment, and it did a good job with this &#8216;offbeat&#8217; test.</p>
<br /><img alt="" border="0" src="http://feeds.wordpress.com/1.0/categories/chimu.wordpress.com/169/" /> <img alt="" border="0" src="http://feeds.wordpress.com/1.0/tags/chimu.wordpress.com/169/" /> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/chimu.wordpress.com/169/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/chimu.wordpress.com/169/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/chimu.wordpress.com/169/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/chimu.wordpress.com/169/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/chimu.wordpress.com/169/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/chimu.wordpress.com/169/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/chimu.wordpress.com/169/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/chimu.wordpress.com/169/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/chimu.wordpress.com/169/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/chimu.wordpress.com/169/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/chimu.wordpress.com/169/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/chimu.wordpress.com/169/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/chimu.wordpress.com/169/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/chimu.wordpress.com/169/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=chimu.wordpress.com&amp;blog=4683676&amp;post=169&amp;subd=chimu&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://chimu.wordpress.com/2008/09/08/a-taste-of-scratch/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/e8534283d788fb4fe8854c40a124361d?s=96&#38;d=identicon" medium="image">
			<media:title type="html">marklfussell</media:title>
		</media:content>

		<media:content url="http://chimu.files.wordpress.com/2008/09/atasteofscratch_d3.png" medium="image">
			<media:title type="html">Tower of Hanoi -- Graphical Overview</media:title>
		</media:content>

		<media:content url="http://chimu.files.wordpress.com/2008/09/atasteofscratch_d1.png" medium="image">
			<media:title type="html">Application Variables</media:title>
		</media:content>

		<media:content url="http://chimu.files.wordpress.com/2008/09/atasteofscratch_d2.png" medium="image">
			<media:title type="html">Application Initialization</media:title>
		</media:content>

		<media:content url="http://chimu.files.wordpress.com/2008/09/atasteofscratch_d4.png" medium="image">
			<media:title type="html">Find and Move Next Disk </media:title>
		</media:content>

		<media:content url="http://chimu.files.wordpress.com/2008/09/atasteofscratch_d5.png" medium="image">
			<media:title type="html">Hanoi Disk Variables</media:title>
		</media:content>

		<media:content url="http://chimu.files.wordpress.com/2008/09/atasteofscratch_d6.png" medium="image">
			<media:title type="html">Hanoi Disk Initialization</media:title>
		</media:content>

		<media:content url="http://chimu.files.wordpress.com/2008/09/atasteofscratch_d7.png" medium="image">
			<media:title type="html">Propose Next Disk</media:title>
		</media:content>

		<media:content url="http://chimu.files.wordpress.com/2008/09/atasteofscratch_d8.png" medium="image">
			<media:title type="html">Move Next Disk</media:title>
		</media:content>
	</item>
		<item>
		<title>Ruby Naming Convention Failure</title>
		<link>http://chimu.wordpress.com/2008/09/04/ruby-naming-convention-failure/</link>
		<comments>http://chimu.wordpress.com/2008/09/04/ruby-naming-convention-failure/#comments</comments>
		<pubDate>Thu, 04 Sep 2008 01:20:40 +0000</pubDate>
		<dc:creator>Mark</dc:creator>
				<category><![CDATA[Dylan]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[Ruby]]></category>
		<category><![CDATA[Smalltalk]]></category>

		<guid isPermaLink="false">http://chimu.wordpress.com/?p=144</guid>
		<description><![CDATA[Ruby has a strong recommendation against using CamelCase for method and variable names and to use only underscores instead. There are lots of arguments out there on different naming conventions, and whatever side I pick in isolation is fairly irrelevant since either the whole community or the individual team has to chose the best approach. [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=chimu.wordpress.com&amp;blog=4683676&amp;post=144&amp;subd=chimu&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>Ruby has a strong recommendation against using CamelCase for method and variable names and to use only underscores instead.  There are lots of arguments out there on different naming conventions, and whatever side I pick in isolation is fairly irrelevant since either the whole community or the individual team has to chose the best approach.<br />
<span id="more-144"></span><br />
In case people care, in isolation of other issues, I would pick this order as being the most natural:</p>
<ol>
<li>Mark-Fussell (or mark-fussell)</li>
<li>MarkFussell</li>
<li>Mark_Fussell (or mark_fussell)</li>
</ol>
<p>where the underscore goes third mostly because it can be hard to see [URLs and other things put underlines _on top_ of that underline like thus <u>Mark_Fussell</u>], is harder to type, and it over spaces things visually.  So I (and lots of people actually) believe programming languages _should_ use hyphens, but because a bunch of programming languages want &#8216;a-b&#8217; to be interpreted as &#8216;a &#8211; b&#8217;, they cop out and prevent the hyphen from being part of a name.  Ruby has that same cop out, so we can&#8217;t use hyphens in Ruby <img src='http://s0.wp.com/wp-includes/images/smilies/icon_sad.gif' alt=':-(' class='wp-smiley' /> </p>
<h2>Missing Phrase Delimiter</h2>
<p>So I said my opinion is fairly irrelevant, but I also want to say that people have missed an important aspect to this argument.  I may have a small preference for CamelCase over underlines as a single word delimiter, but I have a _huge_ preference to having both a &#8216;word&#8217; and a &#8216;phrase&#8217; delimiter.  And by insisting on just one delimiter in this naming standard, Ruby has significantly interfered with expressiveness.  Maybe I am unusual, but I have long-time argued that we should have both words and phrases in methods and frequently even in classes.  Back in the 1990s, I documented this as part of my <a href="http://www.chimu.com/publications/javaStandards2/part0006.html#E11E13">JavaStandards</a> and this was based on Smalltalk naturally having both of these pieces.  It was clearly more readable and you were much less likely to produce bad method names.</p>
<p>For method naming, the quick summary is:</p>
<ul>
<li>When naming a method</li>
<li>Start with a verb phrase (what you are asking the object to do)</li>
<li>Put an underscore where a parameter is expected (up to the first two at least)</li>
<li>Describe what that parameter is for right before the underscore, if it is not obvious from the verb</li>
</ul>
<p>this way, the reader of the code can immediately know how the parameters (in the parentheses) map onto their role in the method itself.  And the whole method name becomes a readable phrase&#8230; not just a weird long word strung together (by whatever convention you want).</p>
<h3>Array::insert</h3>
<p>So an example is:</p>
<pre style="background-color:#eef;font-size:1.3em;padding:10px;">Array::insert(index, obj)</pre>
<p>This is a method name that is ambiguous in usage:</p>
<pre style="background-color:#eef;font-size:1.3em;padding:10px;">anArray.insert(3,2)</pre>
<p>It is not clear what the code is going to do and I would actually intuitively expect it to be the other way around (except I know about getting burned so would then have to look it up).</p>
<p>A better name would be:</p>
<pre style="background-color:#eef;font-size:1.3em;padding:10px;">Array::insert_at(obj,index)</pre>
<p>so reading:</p>
<pre style="background-color:#eef;font-size:1.3em;padding:10px;">anArray.insert_at(3,2)</pre>
<p>is clearly inserting the &#8217;3&#8242; not inserting the &#8217;2&#8242;. </p>
<p>Or if people like the order the other way:</p>
<pre style="background-color:#eef;font-size:1.3em;padding:10px;">
   Array::insertAt_value(index,obj)

   anArray.insertAt_value(2,3)
</pre>
<p>And in the Ruby case where any number of values could follow, we should have:</p>
<pre style="background-color:#eef;font-size:1.3em;padding:10px;">
   Array::insertAt_values(index,obj...)

   anArray.insertAt_values(2,3)
   anArray.insertAt_values(2,5,3)
</pre>
<p>and everything reads naturally something like this &#8220;anArray insertAt: 2 values: 5 and 3&#8243;.</p>
<h3>forPolesOtherThan_do(disk)</h3>
<p>Related to a recent post on the Tower of Hanoi, I believe the resulting choice of:</p>
<pre style="background-color:#eef;font-size:1.3em;padding:10px;">forPolesOtherThan_do(disk) [block]</pre>
<p>is much clearer in both communicating what the passed in &#8216;disk&#8217; is for and that it requires a block as a second (semi-hidden) argument than if you have only a word delimiter and have any of:</p>
<pre style="background-color:#eef;font-size:1.3em;padding:10px;">
   for_poles_other_than
   for_poles_other_than_do
   forPolesOtherThan
   forPolesOtherThanDo
</pre>
<h2>What to do?</h2>
<p>Given Ruby wants to use underscore to separate words&#8230; I can&#8217;t separate the phrases at all.  I tried to wrestle my mind around using something different, but Ruby surprisingly (for a modern and internationally-created) language does not have any other punctuation that is allowed and could plausibly work.  So maybe use two underscores for the phrase point?  That seems seriously ugly and also two underscores don&#8217;t really look different from one underscore:</p>
<pre style="background-color:#eef;font-size:1.3em;padding:10px;">
   insert_at__values
   for_poles_other_than__do
</pre>
<p>Using capitals for this purpose just comes off weird (plausible but weird):</p>
<pre style="background-color:#eef;font-size:1.3em;padding:10px;">
   insert_at_Values
   for_poles_other_than_Do
</pre>
<p>It is also exactly the opposite of Smalltalk, and I try to be able to work across languages without having to flip upside down all the time.  Same regarding Java and Flex (two other languages I actively work in).  For reference, the Smalltalk version of these examples are:</p>
<pre style="background-color:#eef;font-size:1.3em;padding:10px;">
   insertAt: values:
   forPolesOtherThan: do:
</pre>
<h3>Arguments about non-English speakers</h3>
<p>One argument I (so far) find specious is that using capitals prevents non-native speakers from understanding the code.  I could maybe believe this is true in rare cases &#8212; but (1) nobody has a study referenced that shows that, and (2) if that were true, someone simply has to learn the language better.  You can&#8217;t argue that some people&#8217;s inability to use a language is a reason to not use a feature of that language.  That would argue that almost all syntax in languages should be stripped, and few languages (and especially computer languages) can survive that.  Actually only Lisp survives that (give me just a pair of delimiters, and I can rule the world <img src='http://s0.wp.com/wp-includes/images/smilies/icon_smile.gif' alt=':-)' class='wp-smiley' />  )</p>
<p>Also given Ruby uses CamelCase for classes, you already have a requirement to understand this kind of syntax aspect.  So Ruby is presupposing the reader can read the syntax it is arguing the reader can&#8217;t read.</p>
<h3>The standard, in different languages</h3>
<p>A more interesting question is whether the &#8220;word and phrase standard&#8221; survives human-language change.  Obviously the standard does not work &#8220;as written&#8221; if the language used is not a capital-capable language.  And an obviously important language for that test is written Chinese (traditional or simplified).  But actually the &#8216;underscores for phrases and parameters&#8217; degrades with Chinese better than &#8216;underscores for words&#8217;.  Chinese doesn&#8217;t require spaces for words to be apparent, and does not use spaces at all for that purpose (normally) &#8212; it is obvious where each word starts and ends without spacing because a word is only a couple characters long.  So given words are apparent, the only thing left is to have phrases.  Although unnatural to use underscores for phrases and parameters, it at least seems plausibly useful.</p>
<p>Admittedly I have not tried in depth to program in Chinese (Smalltalk/Agents by QKS had the ability way back but I only played with it a little) and have not found a study on it&#8230;  so I can&#8217;t say for sure whether the underscore for parameters would make sense.  But it is at least plausible it would make sense and it would make much more sense than underscore to separate (already separated) words.</p>
<p>Another plausible language to test against would be Hindi, but (I believe) most writers of Hindi in the computer field are also excellent English writers, so that is harder to argue for.</p>
<h3>Could be hyphens</h3>
<p>Note that the convention is totally happy with using &#8216;hyphens&#8217; as word separators if the environment supports it.</p>
<pre style="background-color:#eef;font-size:1.3em;padding:10px;">
   insert-at_values
   for-poles-other-than_do
</pre>
<h2>Summary: Ruby has it wrong &#8212; We need CamelWords or hyphen-words</h2>
<p>So I believe Ruby has it wrong and am very unhappy a modern language started 20 years after Smalltalk and several years after Dylan would get this kind of thing wrong.  And I recommend moving the Ruby standard to the CamelWord_UnderPhrase standard, or allowing the hyphen and use the hyphen-word_under-phrase standard.</p>
<br /><img alt="" border="0" src="http://feeds.wordpress.com/1.0/categories/chimu.wordpress.com/144/" /> <img alt="" border="0" src="http://feeds.wordpress.com/1.0/tags/chimu.wordpress.com/144/" /> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/chimu.wordpress.com/144/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/chimu.wordpress.com/144/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/chimu.wordpress.com/144/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/chimu.wordpress.com/144/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/chimu.wordpress.com/144/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/chimu.wordpress.com/144/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/chimu.wordpress.com/144/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/chimu.wordpress.com/144/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/chimu.wordpress.com/144/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/chimu.wordpress.com/144/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/chimu.wordpress.com/144/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/chimu.wordpress.com/144/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/chimu.wordpress.com/144/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/chimu.wordpress.com/144/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=chimu.wordpress.com&amp;blog=4683676&amp;post=144&amp;subd=chimu&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://chimu.wordpress.com/2008/09/04/ruby-naming-convention-failure/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/e8534283d788fb4fe8854c40a124361d?s=96&#38;d=identicon" medium="image">
			<media:title type="html">marklfussell</media:title>
		</media:content>
	</item>
		<item>
		<title>A Taste of Ruby (Part 7)</title>
		<link>http://chimu.wordpress.com/2008/09/03/a-taste-of-ruby-part-7/</link>
		<comments>http://chimu.wordpress.com/2008/09/03/a-taste-of-ruby-part-7/#comments</comments>
		<pubDate>Wed, 03 Sep 2008 02:28:10 +0000</pubDate>
		<dc:creator>Mark</dc:creator>
				<category><![CDATA[Rails]]></category>
		<category><![CDATA[Ruby]]></category>

		<guid isPermaLink="false">http://chimu.wordpress.com/?p=140</guid>
		<description><![CDATA[This is a multi-part series. The first in the series is here. Tower of Hanoi — Rules on Rails In part 6 we changed the algorithm of Tower Of Hanoi to work without requiring the stack &#8212; it instead &#8220;more naturally&#8221; put sufficient state and logic into the model that the model could start and [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=chimu.wordpress.com&amp;blog=4683676&amp;post=140&amp;subd=chimu&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>This is a multi-part series. The first in the series is <a href="a-taste-of-ruby">here</a>.</p>
<h2>Tower of Hanoi — Rules on Rails</h2>
<p>In part 6 we changed the algorithm of Tower Of Hanoi to work without requiring the stack &#8212; it instead &#8220;more naturally&#8221; put sufficient state and logic into the model that the model could start and stop and continue as needed.  I believe with Ruby 1.8.x, this is required to have Rails be able to work with the Tower of Hanoi.  So we should try it out and see how well it works <img src='http://s0.wp.com/wp-includes/images/smilies/icon_smile.gif' alt=':-)' class='wp-smiley' /> </p>
<p><span id="more-140"></span></p>
<p><pre class="brush: ruby;">
require 'hanoi_7'

class HanoiController &lt; ApplicationController
  def say
    @hanoi = session[:hanoi]

    if (@hanoi == nil) then
      @hanoi = createHanoi
      session[:count] = 0
      session[:consoleLog] = &quot;&quot;
    end
    

    @hanoi.initApp(self)
    @isDone = @hanoi.doNextMove_IsDone()

    #clear the app because otherwise it will be part of the attempted serialization
    #could also override the marshaling code, but this is simpler
    @hanoi.initApp(nil)

    #clear out the session variable, but @hanoi is still valid through
    #the rest of this interaction
    session[:hanoi] = @isDone ? nil : @hanoi
    
    @count = session[:count] ||= 0
    @count += 1
    session[:count] = @count

    if (@isDone) then
      render(:action =&gt; 'say_done')
    end
  end

  def appendLog(outString)
    logger.info(&quot;Append to Log: &quot;+outString)
    @consoleLog = session[:consoleLog] ||= &quot;\n&quot;
    @consoleLog = @consoleLog + outString + &quot;\n&quot;
    session[:consoleLog] = @consoleLog
  end

  def noteChange
    
  end
  
  def createHanoi
    hanoi = RulesTowerOfHanoi.new
    hanoi.initHeight(5)
    hanoi.setup_disks
    
    return hanoi
  end

  def getAsciiTowers
    result = &quot;&quot;
    lines = Array.new
    @hanoi.stacks.each_with_index do | eachStack, i |
      0.upto(10) do | j |
        eachDisk = eachStack[j]
        if (eachDisk == nil) then
          newLine = &quot; &quot;*12
        else
          newLine = eachDisk.to_s
        end

        newLine &lt;&lt; &quot; &quot;*(12 - newLine.length)

        currentLine = lines[j] ||= &quot;&quot;
        lines[j] = currentLine+&quot; &quot;+newLine
      end
    end
    lines.reverse.each {|line| result += line + &quot;\n&quot;}

    return result
  end

end
</pre></p>
<p><pre class="brush: xml;">
&lt;!DOCTYPE html PUBLIC &quot;-//W3C//DTD XHTML 1.0 Transitional//EN&quot;
        &quot;http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd&quot;&gt;

&lt;html xmlns=&quot;http://www.w3.org/1999/xhtml&quot; xml:lang=&quot;en&quot; lang=&quot;en&quot;&gt;
&lt;head&gt;
&lt;title&gt;Foo &lt;%= @page_title %&gt;&lt;/title&gt;
&lt;meta http-equiv=&quot;Content-Type&quot; content=&quot;text/html; charset=UTF-8&quot; /&gt;
&lt;meta http-equiv=&quot;refresh&quot; content=&quot;1&quot;&gt;
&lt;%= javascript_include_tag :defaults %&gt;
&lt;/head&gt;

&lt;body&lt;% if @page_class %&gt; class=&quot;&lt;%= @page_class %&gt;&quot;&lt;% end %&gt;&gt;

&lt;h1&gt;Tower of Hanoi (Move &lt;%= @count %&gt;) &lt;/h1&gt;

It's &lt;%= Time.now %&gt;.
&lt;br/&gt;
Done = &lt;%= @isDone %&gt;
&lt;br/&gt;
Render =
&lt;pre&gt;
&lt;%= controller.getAsciiTowers %&gt;  
&lt;/pre&gt;
Log =
&lt;pre&gt;
&lt;%= @consoleLog %&gt;
&lt;/pre&gt;

&lt;/body&gt;
</pre></p>
<br /><img alt="" border="0" src="http://feeds.wordpress.com/1.0/categories/chimu.wordpress.com/140/" /> <img alt="" border="0" src="http://feeds.wordpress.com/1.0/tags/chimu.wordpress.com/140/" /> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/chimu.wordpress.com/140/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/chimu.wordpress.com/140/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/chimu.wordpress.com/140/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/chimu.wordpress.com/140/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/chimu.wordpress.com/140/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/chimu.wordpress.com/140/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/chimu.wordpress.com/140/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/chimu.wordpress.com/140/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/chimu.wordpress.com/140/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/chimu.wordpress.com/140/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/chimu.wordpress.com/140/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/chimu.wordpress.com/140/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/chimu.wordpress.com/140/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/chimu.wordpress.com/140/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=chimu.wordpress.com&amp;blog=4683676&amp;post=140&amp;subd=chimu&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://chimu.wordpress.com/2008/09/03/a-taste-of-ruby-part-7/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/e8534283d788fb4fe8854c40a124361d?s=96&#38;d=identicon" medium="image">
			<media:title type="html">marklfussell</media:title>
		</media:content>
	</item>
		<item>
		<title>A Taste of Ruby (Part 6)</title>
		<link>http://chimu.wordpress.com/2008/09/03/a-taste-of-ruby-part-6/</link>
		<comments>http://chimu.wordpress.com/2008/09/03/a-taste-of-ruby-part-6/#comments</comments>
		<pubDate>Wed, 03 Sep 2008 02:18:13 +0000</pubDate>
		<dc:creator>Mark</dc:creator>
				<category><![CDATA[Flex]]></category>
		<category><![CDATA[Rails]]></category>
		<category><![CDATA[Ruby]]></category>
		<category><![CDATA[Smalltalk]]></category>

		<guid isPermaLink="false">http://chimu.wordpress.com/?p=138</guid>
		<description><![CDATA[This is a multi-part series. The first in the series is here. Tower of Hanoi — With Rule Disks (and no stack) The first passes at the Tower of Hanoi algorithm were all done with the algorithm being a recursive call on the stack. This is &#8216;true&#8217; as an algorithm, but comes off as a [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=chimu.wordpress.com&amp;blog=4683676&amp;post=138&amp;subd=chimu&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>This is a multi-part series. The first in the series is <a href="a-taste-of-ruby">here</a>.</p>
<h2>Tower of Hanoi — With Rule Disks (and no stack)</h2>
<p>The first passes at the Tower of Hanoi algorithm were all done with the algorithm being a recursive call on the stack.  This is &#8216;true&#8217; as an algorithm, but comes off as a bit unnatural for humans.  </p>
<p>But it also has a problem in that the algorithm can not be &#8216;suspended&#8217; in mid activity unless the language allows a feature (called a continuation) that can suspend the stack itself.  Although Ruby is multi-threaded and running two threads works in RubyShoes, Rails does not work either with a stateful server (and multiple threads) or with continuations.  At the end of each controller dispatch the session or the database has to have persisted all state.  So we need to do something like formalizing the state of the Disks and Towers to make the Tower of Hanoi work with Rails.</p>
<p>Also, the Smalltalk code in this section was among the most &#8216;closure-oriented&#8217;, so this helps show how that maps to Ruby.<br />
<span id="more-138"></span></p>
<h3>You aren&#8217;t capitalizing right?</h3>
<p>Before continuing into the code, people should realize I actively object to Ruby&#8217;s choice to have only one &#8216;word&#8217; delimiter by convention.  See my article <a href="ruby-naming-convention-failure">Ruby Naming Convention Failure</a> for details and the naming conventions I use, especially for methods.  But the quick summary is:</p>
<ul>
<li>I use CamelCase for combining words into a &#8216;part&#8217; of a method name or variable name</li>
<li>I use an underscore as a placeholder for the parameters of the method</li>
<li>I use an underscore to break up a phrase into logical parts</li>
</ul>
<p>If Ruby supported some other word delimiter than underscore (say hyphen &#8220;-&#8221; or &#8220;:&#8221;), I would be agnostic to dropping the CamelCase, but without that second word delimiter, dropping CamelCase is a losing proposition in expressiveness.  In a team setting we might have to discuss this, but in this case this is my code alone&#8230; and my standard actually makes it easier to convert to-from Smalltalk, Ruby, Flex, Java, etc.  The standard works cleanly with all of them.</p>
<h3>Tower&#8230; </h3>
<p>To migrate to the Rules version of the HanoiTower, it is easiest to start with the Disks themselves.</p>
<h4>RulesHanoiDisk</h4>
<p>A Rules based HanoiDisk just needs to be able to say &#8220;Can I move somewhere&#8221; and &#8220;If so, where&#8221;.  It does this in collaboration with the Tower.  &#8220;@tower&#8221; is now an instance variable that every Disk has set when it is created.  By using an instance variable, it is cleaner than using class variables (we can have multiple towers at the same time) and it works under Ruby serialization/marshalling.  </p>
<p><pre class="brush: ruby;">
class RulesHanoiDisk &lt; AnimatedHanoiDisk
  def hasLegalMove() 
    @towers.forPolesOtherThan_do(self) do | eachTopDisk |
      if (eachTopDisk.width  &gt; self.width) then return true end
    end
    return false
  end

  def bestMove()
    @towers.forPolesOtherThan_do(self) do | eachTopDisk |
      if ( (eachTopDisk.width &gt; self.width) &amp;&amp; (eachTopDisk.pole != @previousPole) ) then return eachTopDisk end
    end
    return nil
  end

  def move_upon(destination)
    @previousPole = @pole

    super(destination)
  end

end
</pre></p>
<p>Among the interesting things with the new RulesHanoiDisk is the extensive use of Blocks.  By using Blocks, we can iterate over the collection of stacks without creating new collections.  The Disk and the Tower collaborate to create custom iterators with minimal code.  See RulesTowerOfHanoi for the example.</p>
<h4>RulesTowerOfHanoi </h4>
<p><pre class="brush: ruby;">
class RulesTowerOfHanoi &lt; AnimatedTowerOfHanoi
  def initHeight(height)
    @height = height

    return self
  end

  def move_tower(height, fromPin, toPin, usingPin)
    while (!doNextMove_IsDone()) do end
  end
  
  def createDisk()
    result = RulesHanoiDisk.new
    result.setupTowers(self)
    
    return result
  end

  def doNextMove_IsDone()
    @currentDisk = decide()
    
    @stacks[@currentDisk.pole-1].pop()
    @stacks[@destinationDisk.pole-1].push(@currentDisk)
    @currentDisk.move_upon(@destinationDisk)
    
    @oldDisk = @currentDisk
    
    @app.noteChange if @app

    return isAllOnOneTower()
  end

  def isAllOnOneTower()
    foundStack = @stacks.detect { |eachStack|  eachStack.size == @height }
    return foundStack != nil
  end

  def forTopsOtherThan_do(disk)
    @stacks.each do | eachStack |
      if (eachStack.empty?) then next end

      topDisk = eachStack.last
      if (topDisk == disk) then next end

      yield topDisk
    end
  end
  
  def forPolesOtherThan_do(disk)
    @stacks.each_with_index do | eachStack, i |
      if (i == disk.pole-1) then next end;

      topDisk = if (eachStack.empty?) then @mockDisks[i] else eachStack.last end;

      yield topDisk
    end
  end

  def decide
    forTopsOtherThan_do(@oldDisk) do | eachDisk |
      if (eachDisk.hasLegalMove) then
        @destinationDisk = eachDisk.bestMove

        return eachDisk
      end
    end
  end
  
end

</pre></p>
<br /><img alt="" border="0" src="http://feeds.wordpress.com/1.0/categories/chimu.wordpress.com/138/" /> <img alt="" border="0" src="http://feeds.wordpress.com/1.0/tags/chimu.wordpress.com/138/" /> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/chimu.wordpress.com/138/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/chimu.wordpress.com/138/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/chimu.wordpress.com/138/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/chimu.wordpress.com/138/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/chimu.wordpress.com/138/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/chimu.wordpress.com/138/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/chimu.wordpress.com/138/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/chimu.wordpress.com/138/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/chimu.wordpress.com/138/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/chimu.wordpress.com/138/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/chimu.wordpress.com/138/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/chimu.wordpress.com/138/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/chimu.wordpress.com/138/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/chimu.wordpress.com/138/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=chimu.wordpress.com&amp;blog=4683676&amp;post=138&amp;subd=chimu&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://chimu.wordpress.com/2008/09/03/a-taste-of-ruby-part-6/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/e8534283d788fb4fe8854c40a124361d?s=96&#38;d=identicon" medium="image">
			<media:title type="html">marklfussell</media:title>
		</media:content>
	</item>
		<item>
		<title>A Taste of Flex (Part 6)</title>
		<link>http://chimu.wordpress.com/2008/09/02/a-taste-of-flex-part-6/</link>
		<comments>http://chimu.wordpress.com/2008/09/02/a-taste-of-flex-part-6/#comments</comments>
		<pubDate>Tue, 02 Sep 2008 16:46:40 +0000</pubDate>
		<dc:creator>Mark</dc:creator>
				<category><![CDATA[Flex]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[Ruby]]></category>
		<category><![CDATA[RubyShoes]]></category>
		<category><![CDATA[Smalltalk]]></category>

		<guid isPermaLink="false">http://chimu.wordpress.com/?p=130</guid>
		<description><![CDATA[This is a multi-part series. The first in the series is here. Tower of Hanoi — With Rule Disks (and no stack) The first passes at the Tower of Hanoi algorithm were all done with the algorithm being a recursive call on the stack. This is &#8216;true&#8217; as an algorithm, but comes off as a [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=chimu.wordpress.com&amp;blog=4683676&amp;post=130&amp;subd=chimu&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>This is a multi-part series. The first in the series is <a href="a-taste-of-flex">here</a>.</p>
<h2>Tower of Hanoi — With Rule Disks (and no stack)</h2>
<p>The first passes at the Tower of Hanoi algorithm were all done with the algorithm being a recursive call on the stack.  This is &#8216;true&#8217; as an algorithm, but comes off as a bit unnatural for humans.  But it also has a problem in that the algorithm can not be &#8216;suspended&#8217; in mid activity unless the language allows a feature (called a continuation) that can suspend the stack itself.  For a multi-threaded language, this inability to suspend may not be a problem because you could create one thread for the algorithm and another thread to listen for whenever a new (interesting) change in state occurs.  This is how the RubyShoes version works: the algorithm is in a new thread separate from the GUI thread (otherwise things behave badly).  Similarly, the Smalltalk-80 GUI is being drawn in a different thread than the main execution thread.  But in many circumstances even this multi-thread version would not work: say you have a client-server version (e.g. Rails) or want to pause/suspend the execution of the 100-tall tower of hanoi.  And finally, if you only have a single-threaded language like Flex, things just don&#8217;t work at all for intermediate renderings unless you can make the algorithm not be dependent on the call stack.<br />
<span id="more-130"></span></p>
<h3>Tower of Hanoi — With Rule Disks (and no stack) &#8212; Flex</h3>
<p>I think it is easiest to work up from the Disk perspective, although see the book for a different flow.  The main changes to HanoiDisk are to have it be able to figure out whether it has any legal moves, and what the bestMove (next move) would be.  To do each of these, the disk needs to communicate back with the towers.  In the Smalltalk code this was done through a Class Variable, but it is far simpler and more scalable to do this through instance variables: each Disk needs to know what tower it belongs to.</p>
<h4>HanoiDiskRules</h4>
<p><pre class="brush: jscript;">
package {

public class HanoiDiskRules extends HanoiDisk {
    protected var my_previousPole : Number;
    protected var my_towers : AnimatedRulesTowerOfHanoi;
    
    public function setupTowers(towers : AnimatedRulesTowerOfHanoi) : void {
        my_towers = towers;
    }
    
    public function hasLegalMove() : Boolean {
        var otherTops : Array = my_towers.selectPolesOtherThan(this);
        for (var i:int = 0; i&lt;otherTops.length; i++) {
            var eachTopDisk : HanoiDisk = otherTops[i];
            if (eachTopDisk.width &gt; this.width) return true;
        } 
        return false;
    } 
    
    public function bestMove() : HanoiDisk {
        var otherTops : Array = my_towers.selectPolesOtherThan(this);
        for (var i:int = 0; i&lt;otherTops.length; i++) {
            var eachTopDisk : HanoiDisk = otherTops[i];
            if ( (eachTopDisk.width &gt; this.width) &amp;&amp; (eachTopDisk.pole != my_previousPole) ) return eachTopDisk;
        } 
        return null;
    } 
    
    public override function moveUpon(destination : HanoiDisk) : void {
        my_previousPole = pole;
        
        super.moveUpon(destination);
    }
    
}

} //package
</pre></p>
<p>Compared to the Smalltalk version of this, the main difference is we are creating Array objects instead of passing a function into an iterator.  Again this seems the more natural for Flex&#8230; but&#8230; it is starting to get annoying looking and has real performance impact, so later we should try to do an iterator + function-based version.</p>
<h4>AnimatedRulesTowerOfHanoi (No Animation)</h4>
<p>The change to the Tower code for Flex is two parts:</p>
<ul>
<li>Provide methods that support the rules that the smarter HanoiDiskRules has</li>
<li>Drive the algorithm in a way to enable Flex to render the intermediary results</li>
</ul>
<p>We can do these in two steps, with the current step focused on just the algorithm changes</p>
<p><pre class="brush: jscript;">
package {

public class AnimatedRulesTowerOfHanoi extends AnimatedTowerOfHanoi {
    protected var my_oldDisk : HanoiDisk;
    protected var my_currentDisk : HanoiDisk;
    protected var my_destinationDisk : HanoiDisk;

    protected override function moveTower(height : int, fromPin : *, toPin : *, usingPin : *) : void {
        //Now that the disks know all the rules... we can ignore all the arguments!

        while (!doNextMove_IsDone) {};
    } 

    protected function doNextMove_IsDone() : Boolean {
        my_currentDisk = this.decide();
        
        (my_stacks[my_currentDisk.pole-1] as Array).pop();
        (my_stacks[my_destinationDisk.pole-1] as Array).push(my_currentDisk);
        my_currentDisk.moveUpon(my_destinationDisk);
        
        my_oldDisk = my_currentDisk;
        
        my_view.noteChange();
        
        return isAllOnOneTower();
    }
    
    protected function isAllOnOneTower() : Boolean {
        for (var i:int = 0; i&lt;my_stacks.length; i++) {
            var eachStack : Array = my_stacks[i];
            if (eachStack.length == my_height) return true;
        }
        return false;
    }
    
    public function selectTopsOtherThan(disk : HanoiDisk) : Array {
        var result : Array = new Array();
        for (var i:int = 0; i&lt;my_stacks.length; i++) {
            var eachStack : Array = my_stacks[i];
            
            if (eachStack.length == 0) continue;
            
            var topDisk : HanoiDisk = eachStack[eachStack.length-1];
            if (topDisk !== disk) {
                result.push(topDisk);
            }
        }
        return result;
    }
    
    public function selectPolesOtherThan(disk : HanoiDisk) : Array {
        var result : Array = new Array();
        for (var i:int = 0; i&lt;my_stacks.length; i++) {
            var eachStack : Array = my_stacks[i];
            
            if (i == disk.pole-1) continue;
            
            if (eachStack.length == 0)  {
                result.push(my_mockDisks[i]);        
            } else {
                var topDisk : HanoiDisk = eachStack[eachStack.length-1];
                result.push(topDisk);
            }
        }
        return result;
    }
    
    protected function decide() : HanoiDisk {
        var tops : Array = selectTopsOtherThan(my_oldDisk);
        for (var i:int = 0; i&lt;tops.length; i++) {
            var movingDisk : HanoiDiskRules = tops[i];
            if (movingDisk.hasLegalMove()) {
                my_destinationDisk = movingDisk.bestMove();
                
                return movingDisk;   
            }
        }
        //This should never happen
        return null;
    }
    
    protected override function createDisk() : HanoiDisk {
        var result : HanoiDiskRules = new HanoiDiskRules();
        result.setupTowers(this);
        return result;
    }
}

} //package
</pre></p>
<p>As mentioned in HanoiDiskRules section, the main annoyance of this particular implementation of the new algorithm compared to Smalltalk is having to create intermediate array objects just to communicate between the Disk and the Tower.</p>
<p>But things should work again.  Except we will still get only one rendering because the whole algorithm is executed in one call within a &#8220;while&#8221; loop.</p>
<h3>Tower of Hanoi — With Rule Disks and Correct Animation &#8212; Flex</h3>
<p>To make things work in Flex now, all we do is have to unwrap the immediacy [single call stack] of the while loop.  Instead of calling each &#8216;doNextMove&#8217; immediately, we will wait for an event.  That event could be anything, like clicking a button or the server sending a response.  Each time we get an event, we will do the next step.  To be easy to present and view, we will make the events be driven by a simple timer.  Each time the timer fires an event, we will do the next step.  Repeating this until we are done.</p>
<p>The only method changes are to &#8216;moveTower&#8217; and to &#8216;handleTimer&#8217;.  Everything else works just the way it was.</p>
<h4>AnimatedRulesTowerOfHanoi (No Animation)</h4>
<p><pre class="brush: jscript;">
package {
    import flash.events.TimerEvent;
    import flash.utils.Timer;
    

public class AnimatedRulesTowerOfHanoi extends AnimatedTowerOfHanoi {
    protected var my_oldDisk : HanoiDisk;
    protected var my_currentDisk : HanoiDisk;
    protected var my_destinationDisk : HanoiDisk;

    protected var my_timer : Timer;
    
    protected override function moveTower(height : int, fromPin : *, toPin : *, usingPin : *) : void {
        //Now that the disks know all the rules... we can ignore all the arguments!

        my_timer = new Timer(300)
        my_timer.addEventListener(TimerEvent.TIMER, handleTimer);
        my_timer.start();
        
    } 

    public function handleTimer(evt:TimerEvent):void {
        var isDone : Boolean = doNextMove_IsDone();
        
        if (isDone) {
            my_timer.stop();
            my_timer = null;
        }
    }
    
        
    
    
    protected function doNextMove_IsDone() : Boolean {
        my_currentDisk = this.decide();
        
        (my_stacks[my_currentDisk.pole-1] as Array).pop();
        (my_stacks[my_destinationDisk.pole-1] as Array).push(my_currentDisk);
        my_currentDisk.moveUpon(my_destinationDisk);
        
        my_oldDisk = my_currentDisk;
        
        my_view.noteChange();
        
        return isAllOnOneTower();
    }
    
    protected function isAllOnOneTower() : Boolean {
        for (var i:int = 0; i&lt;my_stacks.length; i++) {
            var eachStack : Array = my_stacks[i];
            if (eachStack.length == my_height) return true;
        }
        return false;
    }
    
    public function selectTopsOtherThan(disk : HanoiDisk) : Array {
        var result : Array = new Array();
        for (var i:int = 0; i&lt;my_stacks.length; i++) {
            var eachStack : Array = my_stacks[i];
            
            if (eachStack.length == 0) continue;
            
            var topDisk : HanoiDisk = eachStack[eachStack.length-1];
            if (topDisk !== disk) {
                result.push(topDisk);
            }
        }
        return result;
    }
    
    public function selectPolesOtherThan(disk : HanoiDisk) : Array {
        var result : Array = new Array();
        for (var i:int = 0; i&lt;my_stacks.length; i++) {
            var eachStack : Array = my_stacks[i];
            
            if (i == disk.pole-1) continue;
            
            if (eachStack.length == 0)  {
                result.push(my_mockDisks[i]);        
            } else {
                var topDisk : HanoiDisk = eachStack[eachStack.length-1];
                result.push(topDisk);
            }
        }
        return result;
    }
    
    protected function decide() : HanoiDisk {
        var tops : Array = selectTopsOtherThan(my_oldDisk);
        for (var i:int = 0; i&lt;tops.length; i++) {
            var movingDisk : HanoiDiskRules = tops[i];
            if (movingDisk.hasLegalMove()) {
                my_destinationDisk = movingDisk.bestMove();
                
                return movingDisk;   
            }
        }
        //This should never happen
        return null;
    }
    
    protected override function createDisk() : HanoiDisk {
        var result : HanoiDiskRules = new HanoiDiskRules();
        result.setupTowers(this);
        return result;
    }
}

} //package
</pre></p>
<h2>Comments</h2>
<br /><img alt="" border="0" src="http://feeds.wordpress.com/1.0/categories/chimu.wordpress.com/130/" /> <img alt="" border="0" src="http://feeds.wordpress.com/1.0/tags/chimu.wordpress.com/130/" /> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/chimu.wordpress.com/130/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/chimu.wordpress.com/130/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/chimu.wordpress.com/130/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/chimu.wordpress.com/130/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/chimu.wordpress.com/130/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/chimu.wordpress.com/130/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/chimu.wordpress.com/130/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/chimu.wordpress.com/130/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/chimu.wordpress.com/130/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/chimu.wordpress.com/130/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/chimu.wordpress.com/130/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/chimu.wordpress.com/130/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/chimu.wordpress.com/130/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/chimu.wordpress.com/130/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=chimu.wordpress.com&amp;blog=4683676&amp;post=130&amp;subd=chimu&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://chimu.wordpress.com/2008/09/02/a-taste-of-flex-part-6/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/e8534283d788fb4fe8854c40a124361d?s=96&#38;d=identicon" medium="image">
			<media:title type="html">marklfussell</media:title>
		</media:content>
	</item>
		<item>
		<title>A Taste of Flex (Part 5)</title>
		<link>http://chimu.wordpress.com/2008/09/02/a-taste-of-flex-part-5/</link>
		<comments>http://chimu.wordpress.com/2008/09/02/a-taste-of-flex-part-5/#comments</comments>
		<pubDate>Tue, 02 Sep 2008 07:44:58 +0000</pubDate>
		<dc:creator>Mark</dc:creator>
				<category><![CDATA[Flex]]></category>
		<category><![CDATA[Ruby]]></category>
		<category><![CDATA[RubyShoes]]></category>
		<category><![CDATA[Smalltalk]]></category>

		<guid isPermaLink="false">http://chimu.wordpress.com/?p=120</guid>
		<description><![CDATA[This is a multi-part series. The first in the series is here. Tower of Hanoi — With Graphics To follow the flow of code progress within &#8220;A Taste of Smalltalk&#8221;, we next need to include a graphical representation of the disks and their movement between the poles. Flex lives inside a Flash player (or app), [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=chimu.wordpress.com&amp;blog=4683676&amp;post=120&amp;subd=chimu&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>This is a multi-part series. The first in the series is <a href="a-taste-of-flex">here</a>.</p>
<h2>Tower of Hanoi — With Graphics</h2>
<p>To follow the flow of code progress within &#8220;A Taste of Smalltalk&#8221;, we next need to include a graphical representation of the disks and their movement between the poles.  Flex lives inside a Flash player (or app), so it is inherently capable of doing sophisticated graphics.  Actually it is hard to &#8216;contain&#8217; yourself to just doing the simplest possible thing when animating sprites around the screen is very easy.  But to try to compare Flex to Ruby and Smalltalk, we want to keep things in about the same ballpark &#8212; and again study how different languages work with the same problem.<br />
<span id="more-120"></span></p>
<h3>Tower of Hanoi — With Graphics &#8212; Flex</h3>
<p>Given our Flex version is already in a graphics environment, and the model (TowerOfHanoi) is already aware of having to talk the View, the changes are relatively minimal to get things working.  We need to render the disks in the Application/View and we need to notify the view whenever the model changes.</p>
<h4>Main Application</h4>
<p>To add rendering in, we just create a render canvas area and then create the UIComponents (shapes) on each redraw.  Normally we would be more likely to animate a single set of disks (vs. destroying them and recreating them), which would be both better in performance and be _much cooler_, but this matches the RubyShoes version better.</p>
<p><pre class="brush: xml;">
&lt;?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot;?&gt;
&lt;mx:Application xmlns:mx=&quot;http://www.adobe.com/2006/mxml&quot; layout=&quot;vertical&quot;
	creationComplete=&quot;handleCreationComplete()&quot;
&gt;
&lt;mx:Script&gt;
    &lt;![CDATA[
        import mx.core.UIComponent;
        var my_model : AnimatedTowerOfHanoi;
    
        function handleCreationComplete() : void {
            Array.prototype.first = function():Object { return this[0]; }

            my_model = new AnimatedTowerOfHanoi();
            my_model.initView(this);
        }
        
        function handleDoItClicked() : void {
            logToConsole(&quot;\n=== Doing a Hanoi tower &quot;+vTowerInput.text+&quot; tall\n&quot;);
            my_model.doHanoi(new Number(vTowerInput.text));
        }
        
        public function logToConsole(string : String) : void {
            vConsole.text = vConsole.text+string;
        }
        
        public function noteChange() : void {
            vRenderArea.removeAllChildren();
            
            var stacks : Array = my_model.getStacks();
            for (var i : int = 0; i&lt;stacks.length; i++) {
                var eachStack : Array = stacks[i];
                var poleCenterX : Number = i*100 + 50;
                
                for (var j:int = 0; j&lt;eachStack.length; j++) {
                    var eachDisk : HanoiDisk = eachStack[j];

                    var diskHeight : int = 180 - (j * 15);
                    var diskWidth  : int = eachDisk.width * 10;
                    
                    var eachShape : UIComponent = new UIComponent();
                    eachShape.graphics.beginFill(0xA00000);
                    eachShape.graphics.drawRect(poleCenterX - diskWidth / 2, diskHeight, diskWidth, 10);
                    
                    vRenderArea.addChild(eachShape);
                } 
            } 
        }
    ]]&gt;
&lt;/mx:Script&gt; 
&lt;mx:HBox&gt;
    &lt;mx:Text text=&quot;How tall a tower?&quot; /&gt;
    &lt;mx:TextInput id=&quot;vTowerInput&quot; /&gt;
    &lt;mx:Button label=&quot;Do It&quot; click=&quot;handleDoItClicked()&quot; /&gt;
&lt;/mx:HBox&gt;  
&lt;mx:Canvas id=&quot;vRenderArea&quot; width=&quot;300&quot; height=&quot;200&quot; borderStyle=&quot;solid&quot; /&gt;
&lt;mx:TextArea id=&quot;vConsole&quot; width=&quot;100%&quot; height=&quot;100%&quot; /&gt;
&lt;/mx:Application&gt;
</pre></p>
<h4>AnimatedTowerOfHanoi</h4>
<p>The AnimatedTower just needs to send out change events (via a simple callback vs. true event listeners that are in Flex).</p>
<p><pre class="brush: jscript;">
package {

public class AnimatedTowerOfHanoi extends ModeledTowerOfHanoi {
    protected override function setupDisks() : void {
        super.setupDisks();
        
        my_view.noteChange();
    }
    
    public function getStacks() : Array {
        return my_stacks;
    }

    protected override function moveDisk(fromPin : *, toPin : *) : void {
        super.moveDisk(fromPin, toPin);
        
        my_view.noteChange();
    }
}

} //package
</pre></p>
<h3>Super Easy&#8230;But doesn&#8217;t work</h3>
<p>Well, that was really easy&#8230; except it doesn&#8217;t really work <img src='http://s0.wp.com/wp-includes/images/smilies/icon_sad.gif' alt=':-(' class='wp-smiley' />   You can only see the final result of all the nice disks on the last stack.  None of the intermediary steps before this last rendering are shown at all.  </p>
<p>Clearly we are missing something&#8230; where is the &#8220;Sleep&#8221; equivalent?  If we could add a &#8216;sleep&#8217; then everything would work right?  Unfortunately both &#8220;No&#8221; and &#8220;NO!&#8221;.  When Flex/Flash are running user code, they are doing it between screen renderings and a bunch of other tasks Flash does.  So you can&#8217;t just keep rendering things in the same thread (same stack) and have any of that be visible except the last version.  If you could &#8216;sleep&#8217;, you would just make Flash pause for no good reason.</p>
<p>The solution is to do each rendering on some kind of event.  Something simple like do the next step of the hanoi algorithm every 0.3 seconds.  That sounds easy but: (1) Flex doesn&#8217;t have continuations either so you can&#8217;t just &#8216;pause&#8217; the stack and (2) The current hanoi algorithm is completely stack based.</p>
<p>Fortunately the fix is both &#8220;not that hard&#8221; and also happens to be the next chapter of &#8220;A Taste of Smalltalk&#8221; called &#8220;An Algorithm for the Rest of Us&#8221;.  So for the moment, lets punt on getting the animation in Flex right until we get to the next part.</p>
<h3>What&#8217;s Next</h3>
<p>A new non-stack algorithm.</p>
<br /><img alt="" border="0" src="http://feeds.wordpress.com/1.0/categories/chimu.wordpress.com/120/" /> <img alt="" border="0" src="http://feeds.wordpress.com/1.0/tags/chimu.wordpress.com/120/" /> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/chimu.wordpress.com/120/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/chimu.wordpress.com/120/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/chimu.wordpress.com/120/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/chimu.wordpress.com/120/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/chimu.wordpress.com/120/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/chimu.wordpress.com/120/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/chimu.wordpress.com/120/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/chimu.wordpress.com/120/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/chimu.wordpress.com/120/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/chimu.wordpress.com/120/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/chimu.wordpress.com/120/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/chimu.wordpress.com/120/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/chimu.wordpress.com/120/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/chimu.wordpress.com/120/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=chimu.wordpress.com&amp;blog=4683676&amp;post=120&amp;subd=chimu&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://chimu.wordpress.com/2008/09/02/a-taste-of-flex-part-5/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/e8534283d788fb4fe8854c40a124361d?s=96&#38;d=identicon" medium="image">
			<media:title type="html">marklfussell</media:title>
		</media:content>
	</item>
		<item>
		<title>A Taste of Flex (Part 4)</title>
		<link>http://chimu.wordpress.com/2008/09/02/a-taste-of-flex-part-4/</link>
		<comments>http://chimu.wordpress.com/2008/09/02/a-taste-of-flex-part-4/#comments</comments>
		<pubDate>Tue, 02 Sep 2008 07:13:17 +0000</pubDate>
		<dc:creator>Mark</dc:creator>
				<category><![CDATA[Flex]]></category>
		<category><![CDATA[Ruby]]></category>
		<category><![CDATA[Smalltalk]]></category>

		<guid isPermaLink="false">http://chimu.wordpress.com/?p=112</guid>
		<description><![CDATA[This is a multi-part series. The first in the series is here. Tower of Hanoi — With Model Objects The book &#8220;A Taste of Smalltalk&#8221; jumps from showing a single &#8216;TowerOfHanoi&#8217; object to both adding in Disk model objects and putting on a graphical representation of those Disk objects. Even though Flex has no issue [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=chimu.wordpress.com&amp;blog=4683676&amp;post=112&amp;subd=chimu&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>This is a multi-part series. The first in the series is <a href="a-taste-of-flex">here</a>.</p>
<h2>Tower of Hanoi — With Model Objects</h2>
<p>The book &#8220;A Taste of Smalltalk&#8221; jumps from showing a single &#8216;TowerOfHanoi&#8217; object to both adding in Disk model objects and putting on a graphical representation of those Disk objects.  Even though Flex has no issue with graphics, I want to separate these two changes both to match Ruby and because the changes are logically somewhat separate.  So first we can put in Disk objects and study that change.  After that, we can go into the GUI code.</p>
<p><span id="more-112"></span></p>
<h3>The Code</h3>
<h4>ModeledTowerOfHanoi</h4>
<p><pre class="brush: jscript;">
package {

/**
 * A ModeledTowerOfHanoi is the TowerOfHanoi algorithm
 * but it keeps track of the state of the Disks
 * with actual objects.  This makes it suitable for
 * model-based behavior (say tracking moves, animation or
 * other event listening) on top of those Disks
 */
public class ModeledTowerOfHanoi extends TowerOfHanoi{
    protected var my_height : Number;
    protected var my_mockDisks : Array;
    
    public override function doHanoi(height : int) : void {    
        my_height = height;
     
        setupDisks();
        
        logToConsole(&quot;\n\nStart\n&quot;);
        printStacks();

        logToConsole(&quot;\n\nMoves\n&quot;);
        moveTower(my_height, 1, 3, 2);
        
        logToConsole(&quot;\n\nResult\n&quot;);
        printStacks();
    }
    
    protected function setupDisks() : void {
        my_stacks = new Array();
        for (var i:int = 0; i&lt;3; i++) {
            my_stacks.push(new Array());
        }
        
        var firstStack : Array = my_stacks.first(); //[0];
        for (var j:int = 0; j&lt;my_height; j++) {
            firstStack.unshift(new HanoiDisk().initWidth_pole(j,1));
        }
        
        my_mockDisks = new Array();
        for (var k:int = 0; k&lt;3; k++) {
            my_mockDisks[k]=new HanoiDisk().initWidth_pole(1000,k);
        }
    }
    
    protected function printStacks() : void {
        for (var i:int = 0; i&lt;my_stacks.length; i++) {
            var eachStack : Array = my_stacks[i];
            logToConsole(&quot;   &lt;stack&gt;\n&quot;);
            for (var j:int = eachStack.length-1; j&gt;=0; j--) {
                var eachDisk : * = eachStack[j];
                logToConsole(eachDisk.toString()+&quot;\n&quot;);        
            }
            logToConsole(&quot;   &lt;/stack&gt;\n&quot;);
        }
    }
        

    protected override function moveDisk(fromPin : *, toPin : *) : void {
        var supportDisk = (my_stacks[toPin-1].length == 0) ? my_mockDisks[toPin-1] : my_stacks[toPin-1][0];
        
        var disk : HanoiDisk = my_stacks[fromPin-1].pop();
        my_stacks[toPin-1].push(disk);
        
        disk.moveUpon(supportDisk);
        
        logToConsole(disk + &quot; moved &quot; + fromPin + &quot;-&gt;&quot; + toPin+&quot;\n&quot;);
    }
    
    public function logToConsole(string : String) {
        my_view.logToConsole(string);
    }
    
}

} //package
</pre></p>
<h4>HanoiDisk</h4>
<p><pre class="brush: jscript;">
package {

public class HanoiDisk {
    protected const CONST_asciiA : Number = &quot;A&quot;.charCodeAt();

    public var width : Number;
    public var pole : Number;
    
    protected var my_name : String;
    protected var my_moveCount : Number = 0;
    
    public function initWidth_pole(aWidth : Number, aPole : Number) : HanoiDisk {
        width = aWidth;
        pole = aPole;
        
        if (width &lt; 1000) {
            my_name = &quot;Disk-#&quot;+String.fromCharCode(CONST_asciiA+width);
        } else {
            my_name = &quot;Base-#&quot;+pole;
        }
        
        return this;
    }
    
    
    public function toString() : String {
        return my_name+&quot;(&quot;+my_moveCount+&quot;)&quot;;
    }    

    public function moveUpon(destination : HanoiDisk) : void {
        pole = destination.pole;
        my_moveCount++;
    }
    
}

} //package
</pre></p>
<p>I believe the following are the most interesting aspects:</p>
<ol>
<li>Public Attributes (which may be wrapped or unwrapped instance variables)</li>
<li>Explicit &#8216;override&#8217;</li>
<li>Explicit return values</li>
</ol>
<h3>Public Attributes</h3>
<p>Flex allows you to have attributes that are either (1) just instance variables or (2) one or a pair of &#8216;set&#8217; and &#8216;get&#8217; accessors.  The notation of access looks the same, so it is up to the receiver/implementer to decide whether &#8216;wrapping&#8217; is necessary.  Although the Macro approach of Ruby is nicer than having to do add accessors manually (or even &#8216;refactor&#8217; them in with a tool), the Flex approach is by far the best for this kind of situation.  The language/compiler actually understands the intent of the programmer (declaratively) vs. running through a macro and the results just happen to be the same.</p>
<p>Note that Flex goes beyond simple public attributes and can attach notification capabilities on top of it.</p>
<h3>Explicit &#8216;override&#8217;</h3>
<p>Flex and ActionScript again clearly try to help the programmer avoid making a mistake, in this case by making sure code _knows_ it is overriding inherited code and that within that override you have to consider what the superclass wants, whether you need to call &#8216;super&#8217;, etc.</p>
<h3>Explicit return values</h3>
<p>Flex enables you to avoid specifying the type of a return value (defaulting to &#8216;Any&#8217;), but you have to decide whether you are going to return anything or nothing at all.  And if you are going to return anything, you need to explicitly say what you are going to return.</p>
<p>As I mentions in Part 4 of a Taste of Ruby, this approach is clearly the best &#8212; actually better than what I mentioned there.  So then returning &#8216;null&#8217; by default becomes a good second best (no language so far mentioned),  Returning &#8216;self&#8217; by default is third best (Smalltalk).  And Ruby returning of &#8220;whatever happens to be returned by the last statement&#8221; is a distant fourth.</p>
<h3>What Next</h3>
<p>Now onto the GUI itself.</p>
<br /><img alt="" border="0" src="http://feeds.wordpress.com/1.0/categories/chimu.wordpress.com/112/" /> <img alt="" border="0" src="http://feeds.wordpress.com/1.0/tags/chimu.wordpress.com/112/" /> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/chimu.wordpress.com/112/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/chimu.wordpress.com/112/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/chimu.wordpress.com/112/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/chimu.wordpress.com/112/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/chimu.wordpress.com/112/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/chimu.wordpress.com/112/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/chimu.wordpress.com/112/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/chimu.wordpress.com/112/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/chimu.wordpress.com/112/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/chimu.wordpress.com/112/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/chimu.wordpress.com/112/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/chimu.wordpress.com/112/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/chimu.wordpress.com/112/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/chimu.wordpress.com/112/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=chimu.wordpress.com&amp;blog=4683676&amp;post=112&amp;subd=chimu&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://chimu.wordpress.com/2008/09/02/a-taste-of-flex-part-4/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/e8534283d788fb4fe8854c40a124361d?s=96&#38;d=identicon" medium="image">
			<media:title type="html">marklfussell</media:title>
		</media:content>
	</item>
		<item>
		<title>A Taste of Flex (Part 3)</title>
		<link>http://chimu.wordpress.com/2008/09/02/a-taste-of-flex-part-3/</link>
		<comments>http://chimu.wordpress.com/2008/09/02/a-taste-of-flex-part-3/#comments</comments>
		<pubDate>Tue, 02 Sep 2008 05:11:06 +0000</pubDate>
		<dc:creator>Mark</dc:creator>
				<category><![CDATA[Flex]]></category>
		<category><![CDATA[Ruby]]></category>
		<category><![CDATA[Smalltalk]]></category>

		<guid isPermaLink="false">http://chimu.wordpress.com/?p=99</guid>
		<description><![CDATA[This is a multi-part series. The first in the series is here. Tower of Hanoi &#8212; With A Real Object The first two examples were not really object-based. They are purely procedural, the algorithm is expressed completely recursively, and execution state is maintained on the call stack. This works fine if we are just &#8216;tracing&#8217; [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=chimu.wordpress.com&amp;blog=4683676&amp;post=99&amp;subd=chimu&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>This is a multi-part series.  The first in the series is <a href="a-taste-of-flex">here</a>.</p>
<h2>Tower of Hanoi &#8212; With A Real Object</h2>
<p>The first two examples were not really object-based.  They are purely procedural, the algorithm is expressed completely recursively, and execution state is maintained on the call stack.  This works fine if we are just &#8216;tracing&#8217; the algorithm, but it does not let us show the state of the towers at any given time.  We also don&#8217;t see much in the way of real objects.  By adding the state of the towers in, we now have a reason to have stateful objects and new Classes of objects to maintain that state.  The added code with some explanation is in Chapter 4, Page 45.<br />
<span id="more-99"></span></p>
<h3>TowerOfHanoi</h3>
<p>The TowerOfHanoi main class is now able to be a pure ActionScript class, so it looks much cleaner and formats nicely now.  The only additional feature it needs (compared to say the Smalltalk or Ruby version) is a reference to its View so it can print into the Console of that view.  I could actually just use &#8216;Application.application&#8217; to get the outer view, but this is cleaner, more scalable, and makes it clearer what is happening [even though many people like to cheat with those kinds of Globals].</p>
<p><pre class="brush: jscript;">
package {

public class TowerOfHanoi {
    protected const CONST_asciiA : Number = &quot;A&quot;.charCodeAt();
    
    protected var my_view : *;
    protected var my_stacks : Array;
    
    public function initView(view : *) : void {
        my_view = view;
    }
    
    public function doHanoi(height : int) : void {    
        my_stacks = new Array();
        for (var i:int = 0; i&lt;3; i++) {
            my_stacks.push(new Array());
        }
        
        var firstStack : Array = my_stacks[0];
        for (var j:int = 0; j&lt;height; j++) {
            firstStack.unshift(&quot;Disk-#&quot;+String.fromCharCode(CONST_asciiA+j));
        }
        
        moveTower(height, 1, 3, 2);
    }
        

    protected function moveTower(height : int, fromPin : *, toPin : *, usingPin : *) : void {
        if (height &gt; 0) {
            moveTower(height-1, fromPin, usingPin, toPin);
            moveDisk(fromPin, toPin);
            moveTower(height-1, usingPin, toPin, fromPin);
        }
    } 
    
    protected function moveDisk(fromPin : *, toPin : *) : void {
        var disk = my_stacks[fromPin-1].pop();
        my_stacks[toPin-1].push(disk);
        
        my_view.logToConsole(disk + &quot; moved &quot; + fromPin + &quot;-&gt;&quot; + toPin+&quot;\n&quot;);
    }
    
}

} //package
</pre></p>
<h3>Main Application</h3>
<p>The main Application is now clean of model code and just (1) holds onto the outer model and (2) provides view services to others.  I made logToConsole public so people could identify what is meant to be used by others vs. what is not.  Ultimately &#8216;logToConsole&#8217; could be put into an interface to make it clearer that is all the &#8216;TowerOfHanoi&#8217; needs from its view.  </p>
<p><pre class="brush: xml;">
&lt;?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot;?&gt;
&lt;mx:Application xmlns:mx=&quot;http://www.adobe.com/2006/mxml&quot; layout=&quot;vertical&quot;
	creationComplete=&quot;handleCreationComplete()&quot;
&gt;
&lt;mx:Script&gt;
    &lt;![CDATA[
        var my_model : TowerOfHanoi;
    
        function handleCreationComplete() : void {
            my_model = new TowerOfHanoi();
            my_model.initView(this);
        }
        
        function handleDoItClicked() : void {
            logToConsole(&quot;\n=== Doing a Hanoi tower &quot;+vTowerInput.text+&quot; tall\n&quot;);
            my_model.doHanoi(new Number(vTowerInput.text));
        }
        
        public function logToConsole(string : String) : void {
            vConsole.text = vConsole.text+string;
        }
    ]]&gt;
&lt;/mx:Script&gt; 
&lt;mx:HBox&gt;
    &lt;mx:Text text=&quot;How tall a tower?&quot; /&gt;
    &lt;mx:TextInput id=&quot;vTowerInput&quot; /&gt;
    &lt;mx:Button label=&quot;Do It&quot; click=&quot;handleDoItClicked()&quot; /&gt;
&lt;/mx:HBox&gt;    
&lt;mx:TextArea id=&quot;vConsole&quot; width=&quot;100%&quot; height=&quot;100%&quot; /&gt;
&lt;/mx:Application&gt;
</pre></p>
<h2>Comments</h2>
<p>By moving the ActionScript portion out of the main Application XML, the syntax becomes clearer.  Another feature of Flex that is starting to show is that we can document and compile-time verify visibility (as needed), contractual interfaces (as needed), etc.  But we can also leave them off and things work fine.</p>
<p>We do need to document the existence of instance variables, local variables, and methods of whatever types we use (e.g. &#8216;self&#8217; / &#8216;this&#8217;) or the compiler will complain.  I believe this is far better (most of the time) than leaving that as a pure runtime issue and having typos potentially take significant time to debug.  And this does not interfere with things being &#8216;dynamic&#8217; (&#8216;duck typed&#8217;) in most cases although it is related to some meta-language capabilities.</p>
<p>Going into the Flex code itself, we can see a stronger relationship to &#8216;C&#8217; style control structures and not the higher-level block/closure structuring of things.  Although iterators and Functions are available in Flex/AS, they are not as natural in the language as in Smalltalk or Ruby because they don&#8217;t work well with collections (as defined in the current API) and are just a bit too verbose in general.  You could modify (monkey-patch) collections, but then the compiler would not understand the new functionality.    Although that is no worse than in Java/Ruby, it would be unusual in the community.  Maybe if Adobe adds it to AS4 just to be cross-language similar, it would be more natural.  But I didn&#8217;t want to augment the existing classes just to have the language match another language&#8217;s idioms</p>
<p>Examples of this kind of Monkey-Patch are:</p>
<ul>
<li><a href="http://www.rocketboots.com.au/blog/index.cfm?mode=entry&amp;entry=A5C356B1-E081-51EF-A79F47A1601ADEDF">RocketBoots</a></li>
<li><a href="http://www.kirupa.com/forum/archive/index.php/t-246045.html">Kirupa</a></li>
</ul>
<p>A minor note, the CharCode conversion is actually a Unicode conversion.  So you can put pretty much any character in the world languages you want to in there <img src='http://s0.wp.com/wp-includes/images/smilies/icon_smile.gif' alt=':-)' class='wp-smiley' />   For example, try it with &#8217;50023&#8242; for the CONST value.</p>
<h3>Where Next?</h3>
<p>Next we should go to Chapter 5 (Animating the Program) — Page 64.  This involves some graphic work for the &#8216;model&#8217; aspects to be realistic, and for Flex this is not at all difficult, but I will follow the same pattern of &#8216;Parts&#8217; that I did with Ruby, so the next Part is just changing to having real Domain Model Objects (vs. the UI Model separation that occurred above for TowerOfHanoi vs the Application)</p>
<br /><img alt="" border="0" src="http://feeds.wordpress.com/1.0/categories/chimu.wordpress.com/99/" /> <img alt="" border="0" src="http://feeds.wordpress.com/1.0/tags/chimu.wordpress.com/99/" /> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/chimu.wordpress.com/99/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/chimu.wordpress.com/99/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/chimu.wordpress.com/99/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/chimu.wordpress.com/99/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/chimu.wordpress.com/99/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/chimu.wordpress.com/99/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/chimu.wordpress.com/99/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/chimu.wordpress.com/99/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/chimu.wordpress.com/99/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/chimu.wordpress.com/99/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/chimu.wordpress.com/99/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/chimu.wordpress.com/99/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/chimu.wordpress.com/99/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/chimu.wordpress.com/99/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=chimu.wordpress.com&amp;blog=4683676&amp;post=99&amp;subd=chimu&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://chimu.wordpress.com/2008/09/02/a-taste-of-flex-part-3/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/e8534283d788fb4fe8854c40a124361d?s=96&#38;d=identicon" medium="image">
			<media:title type="html">marklfussell</media:title>
		</media:content>
	</item>
		<item>
		<title>A Taste of Flex (Part 2)</title>
		<link>http://chimu.wordpress.com/2008/09/02/a-taste-of-flex-part-2/</link>
		<comments>http://chimu.wordpress.com/2008/09/02/a-taste-of-flex-part-2/#comments</comments>
		<pubDate>Tue, 02 Sep 2008 04:12:08 +0000</pubDate>
		<dc:creator>Mark</dc:creator>
				<category><![CDATA[Flex]]></category>
		<category><![CDATA[RubyShoes]]></category>
		<category><![CDATA[Smalltalk]]></category>

		<guid isPermaLink="false">http://chimu.wordpress.com/?p=90</guid>
		<description><![CDATA[This is a multi-part series. The first in the series is here. Tower of Hanoi &#8212; Procedural With Input The second example from &#8220;A Taste of Smalltalk&#8221; is in Chapter 3, page 36 and does basic IO. Except that Smalltalk-80 includes a Windowing graphics system so it can automatically open Dialogs and other things. Fortunately [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=chimu.wordpress.com&amp;blog=4683676&amp;post=90&amp;subd=chimu&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>This is a multi-part series.  The first in the series is <a href="a-taste-of-flex">here</a>.</p>
<h2>Tower of Hanoi &#8212; Procedural With Input</h2>
<p>The second example from &#8220;A Taste of Smalltalk&#8221; is in Chapter 3, page 36 and does basic IO.  Except that Smalltalk-80 includes a Windowing graphics system so it can automatically open Dialogs and other things.    Fortunately Flex includes a Windowing system too, and can easily open up dialogs.  Opening up a Dialog might match the Smalltalk example the best, but given Flex is already running within a Window, opening up an extra dialog is a bit artificial.  Instead we can just add an input field for the value and a button to kick off the Hanoi.<br />
<span id="more-90"></span></p>
<h3>Tower of Hanoi &#8212; Procedural With Input &#8212; Flex</h3>
<p><pre class="brush: xml;">
&lt;?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot;?&gt;
&lt;mx:Application xmlns:mx=&quot;http://www.adobe.com/2006/mxml&quot; layout=&quot;vertical&quot;
	creationComplete=&quot;handleCreationComplete()&quot;
&gt;
&lt;mx:Script&gt;
    &lt;![CDATA[
        function moveTower(height : int, fromPin : *, toPin : *, usingPin : *) : void {
            if (height &gt; 0) {
                moveTower(height-1, fromPin, usingPin, toPin);
                moveDisk(fromPin, toPin);
                moveTower(height-1, usingPin, toPin, fromPin);
            }
        } 
        
        function moveDisk(fromPin : *, toPin : *) : void {
            vConsole.text = vConsole.text+fromPin + &quot;-&gt;&quot; + toPin+&quot;\n&quot;;
        }
        
        function handleCreationComplete() : void {
            //Don't need to do anything anymore
        }
        
        function handleDoItClicked() : void {
            vConsole.text = vConsole.text+&quot;\n=== Doing a Hanoi tower &quot;+vTowerInput.text+&quot; tall\n&quot;;
            moveTower(new Number(vTowerInput.text), 1, 3, 2);        
        }
    ]]&gt;
&lt;/mx:Script&gt; 
&lt;mx:HBox&gt;
    &lt;mx:Text text=&quot;How tall a tower?&quot; /&gt;
    &lt;mx:TextInput id=&quot;vTowerInput&quot; /&gt;
    &lt;mx:Button label=&quot;Do It&quot; click=&quot;handleDoItClicked()&quot; /&gt;
&lt;/mx:HBox&gt;    
&lt;mx:TextArea id=&quot;vConsole&quot; width=&quot;100%&quot; height=&quot;100%&quot; /&gt;
&lt;/mx:Application&gt;
</pre></p>
<p>To replace the dialog (in Smalltalk) or the command line request (in Ruby), we just create a horizontal row of a question label, an input field, and a Do It button.  Whenever a user clicks Do It, it takes the current value of the field and runs the Hanoi algorithm.</p>
<p>This is both pleasingly simply and also has the added benefit that we produced an interactive tool: you can just keep typing new numbers into it and it will give you new results.</p>
<h2>Comments</h2>
<p>Flex is highly capable with user input and interactivity.  It has a cleaner / simpler UI model than Smalltalk (IMO), which is good given we have had about 30 years of working with UIs to take things forward.  Compared to Ruby, Flex is as easy as RubyShoes for simple things like this example.  </p>
<h3>Where Next?</h3>
<p>Next we should go to Chapter 4 — Page 44. The Third Example (with Real Hanoi Classes)</p>
<br /><img alt="" border="0" src="http://feeds.wordpress.com/1.0/categories/chimu.wordpress.com/90/" /> <img alt="" border="0" src="http://feeds.wordpress.com/1.0/tags/chimu.wordpress.com/90/" /> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/chimu.wordpress.com/90/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/chimu.wordpress.com/90/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/chimu.wordpress.com/90/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/chimu.wordpress.com/90/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/chimu.wordpress.com/90/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/chimu.wordpress.com/90/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/chimu.wordpress.com/90/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/chimu.wordpress.com/90/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/chimu.wordpress.com/90/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/chimu.wordpress.com/90/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/chimu.wordpress.com/90/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/chimu.wordpress.com/90/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/chimu.wordpress.com/90/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/chimu.wordpress.com/90/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=chimu.wordpress.com&amp;blog=4683676&amp;post=90&amp;subd=chimu&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://chimu.wordpress.com/2008/09/02/a-taste-of-flex-part-2/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/e8534283d788fb4fe8854c40a124361d?s=96&#38;d=identicon" medium="image">
			<media:title type="html">marklfussell</media:title>
		</media:content>
	</item>
	</channel>
</rss>
