<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Dalibor Novak</title>
	<atom:link href="http://dalibornovak.co.uk/blog/feed/" rel="self" type="application/rss+xml" />
	<link>http://dalibornovak.co.uk/blog</link>
	<description>Tales from a grumpy developer...</description>
	<lastBuildDate>Sun, 27 Mar 2011 21:02:13 +0000</lastBuildDate>
	<language>en-US</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.4.2</generator>
		<item>
		<title>Seven Languages in Seven Weeks &#8211; Prolog &#8211; Day 1</title>
		<link>http://dalibornovak.co.uk/blog/seven-languages-in-seven-weeks-prolog-day-1/</link>
		<comments>http://dalibornovak.co.uk/blog/seven-languages-in-seven-weeks-prolog-day-1/#comments</comments>
		<pubDate>Sun, 27 Mar 2011 20:50:19 +0000</pubDate>
		<dc:creator>Dalibor "Bore" Novak</dc:creator>
				<category><![CDATA[books]]></category>
		<category><![CDATA[Books]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[Prolog]]></category>

		<guid isPermaLink="false">http://dalibornovak.co.uk/blog/?p=154</guid>
		<description><![CDATA[I am tackling a third language from the book today. This is Prolog and we are not complete strangers. I remember using it at uni for some lab practices and I can remember we didn&#8217;t get along like a house on fire. I found Prolog strange and at odds with imperative mindset I held back...<a href="http://dalibornovak.co.uk/blog/seven-languages-in-seven-weeks-prolog-day-1/">&#187;</a>]]></description>
			<content:encoded><![CDATA[<p><a href="http://dalibornovak.co.uk/blog/wp-content/uploads/2011/03/prologS.png"><img class="alignleft size-full wp-image-167" title="Prolog" src="http://dalibornovak.co.uk/blog/wp-content/uploads/2011/03/prologS.png" alt="Prolog prompt" width="200" height="185" /></a>I am tackling a third language from <a href="http://dalibornovak.co.uk/blog/seven-languages-in-seven-weeks/">the book</a> today. This is Prolog and we are not complete strangers. I remember using it at uni for some lab practices and I can remember we didn&#8217;t get along like a house on fire. I found Prolog strange and at odds with imperative mindset I held back then. Now that I am a bit older, I find the fact that language is a bit different appealing and intriguing and I look forward to see why was it designed in such manner and what benefits it&#8217;s approach brings.</p>
<p>Day 1 explains the very basic concepts behind the language. It explains its syntax which is very simple. Main constructs are atoms, variables, facts and rules.</p>
<pre class="brush: plain; title: ; notranslate">
%atoms
me.
brother.
mother.
granddad.

%facts
parent(me, mother).
parent(brother, mother).
parent(mother, granddad).

%rules
grandparent(X, Y) :- parent(X, Z), parent(Z, Y).
sibling(X, Y) :- \+(X = Y), parent(X, Z), parent(Y, Z).
% X, Y and Z are variables
</pre>
<p>No syntax highlighting is available &#8211; I guess that the &#8220;hip crowd&#8221; does not grok Prolog.<span id="more-154"></span></p>
<p>Atom is a general purpose name without an inherent meaning. Atoms are written as words starting with a lower case letter, if spaces, special characters or capital letter are required atoms have to be quoted using single quotes.</p>
<p>Variables are place holders for arbitrary terms. They are written as words starting with capital letter or an underscore. A single underscore stands for an anonymous variable matching any term.</p>
<p>Facts are expressed as expressions consisting a name (functor) and a comma separated list of arguments in parenthesis. Functor must following naming convention for atoms.</p>
<p>Rules are expressed as expression consisting of head and body that are separated by :- operator. Head is expressed as a functor followed by arguments. Body consists of sub goals that need to be met in order for the rule to be true.</p>
<p>We use these constructs to express our knowledge about our domain at hand. The idea is that we define a knowledge base about our domain and then question (query) Prolog for possible solutions to our problems within the scope of the defined domain.</p>
<p>So in the example above I&#8217;ve defined (somewhat abstract) knowledge base about my family. Facts define that mother is parent to both me and brother and that granddad is parent of mother.<br />
Then I&#8217;ve defined two rules grandparent and sibling. If I try to read the grandparent rule it reads like this: X is grandparent of Y if there are such X, Y and Z that Z is parent of X and Y is parent of Z. If you look at the rule definition it shouldn&#8217;t be too difficult to map between the previous sentence and rule itself.</p>
<p>Now that I have this knowledge base defined I can query Prolog about it like so:</p>
<pre class="brush: plain; title: ; notranslate">
%is mother my parent?
| ?- parent(me, mother).

yes
%is granddad brother's parent?
| ?- parent(brother, granddad).

no
</pre>
<p>These were very simple queries and Prolog did not have much work as I was just asking it to return the facts I stated. But even with only facts we can still have some fun. When we use a query with a variable Prolog will try to find if there is such combination of facts and rules which can satisfy the query. If it finds it it will print it out.</p>
<pre class="brush: plain; title: ; notranslate">
%Who is parent of brother?
| ?- parent(brother, Who).

Who = mother

yes

%Who's parent is mother?
| ?- parent(Who, mother).

Who = me ? ;

Who = brother ? ;

no
</pre>
<p>In first query we have used Who variable and Prolog was trying to find the value of the variable that would satisfy the query. It finds that mother value fits and prints it out. In second query Prolog finds more than one match: me and brother. When Prolog finds more than one match it will print out the first one it finds and wait. You can then type ; to get next solution, a to get all solutions or &lt;Enter&gt; to stop looking for more solutions. no at the last line of my interaction means that Prolog could not find any more solutions.</p>
<p>And we can have just as much fun with rules that build on top of facts. I will just provide some queries but will not go into detailed explanation of them as you should &#8220;get the drill&#8221; by now:</p>
<pre class="brush: plain; title: ; notranslate">
%is granddad brother's grandparent.
| ?- grandparent(brother, granddad).

yes

%is brother my sibling.
| ?- sibling(me, brother).

yes

%Who is granddad grandparent of?
| ?- grandparent(Who, granddad).

Who = me ? a

Who = brother

no

%Who is Grandparent of a Grandchild?
%(Find all Grandparent, Grandchild pairs.)
| ?- grandparent(Grandchild, Grandparent).

Grandchild = me
Grandparent = granddad ? a

Grandchild = brother
Grandparent = granddad

no
</pre>
<p>At first all of this building of knowledgebase and then querying of it seems a bit unnatural to most programmers (including me when I first saw it). To begin there is no explanation about how Prolog came to the solutions it offers. It doesn&#8217;t print any algorithms and it can be quite frustrating when you are expecting a certain result and Prolog just <a href="http://www.youtube.com/watch?v=7TYAQ0JWBzE">says: no</a>. But if you think of it it&#8217;s not that much different from creating a database and and then using SQL statements to query it. When using SQL you also don&#8217;t specify search algorithms and and the DBMS merely presents you with result.</p>
<p>First day with Prolog ends with two homework assignments:</p>
<p>HW1: Make a simple knowledge base. Represent some of your favorite books and authors. Find all books in your knowledge base written by one author.</p>
<pre class="brush: plain; title: ; notranslate">
%books.pl
book('The Metamorphosis', 'Franz Kafka').
book('The Trial', 'Franz Kafka').
book('1984', 'George Orwell').
book('Catch 22', 'Joseph Heller').
book('Breakfast of Champions', 'Kurt Vonnegut').
book('Slaughterhouse-Five', 'Kurt Vonnegut').
</pre>
<pre class="brush: plain; title: ; notranslate">
| ?- book(Which, 'Franz Kafka').

Which = 'The Metamorphosis' ? a

Which = 'The Trial'

no
</pre>
<p>This was the simplest way of tackling this task that I could come up with.</p>
<p>HW2: Make a knowledge base representing musicians and instruments. Also represent musicians and their genre of music. Find all musicians who play the guitar.</p>
<pre class="brush: plain; title: ; notranslate">
%musicians.pl
musician('Jimi Hendrix').
musician('Bob Marley').
musician('Ringo Starr').
musician('Terminator X').
musician('Peter Tosh').
musician('Fela Kuti').
musician('Johnny Stulic').

instrument(guitar).
instrument(drums).
instrument(keyboard).
instrument(turntables).
instrument(saxophone).

genre(rock).
genre(reggae).
genre(hip-hop).
genre(afrobeat).

plays('Jimi Hendrix', guitar).
plays('Bob Marley', guitar).
plays('Ringo Starr', drums).
plays('Ringo Starr', keyboard).
plays('Terminator X', turntables).
plays('Peter Tosh', guitar).
plays('Peter Tosh', keyboard).
plays('Fela Kuti', saxophone).
plays('Fela Kuti', keyboard).
plays('Johnny Stulic', guitar).

plays('Jimi Hendrix', rock).
plays('Bob Marley', reggae).
plays('Ringo Starr', rock).
plays('Terminator X', hip-hop).
plays('Peter Tosh', reggae).
plays('Fela Kuti', afrobeat).
plays('Johnny Stulic', rock).

plays_instrument(Musician, Instrument) :-
    musician(Musician),
    instrument(Instrument),
    plays(Musician, Instrument).

plays_genre(Musician, Genre) :-
    musician(Musician),
    genre(Genre),
    plays(Musician, Genre).

genre_instrumentalist(Musician, Instrument, Genre) :-
    plays_instrument(Musician, Instrument),
    plays_genre(Musician, Genre).

rock_guitarist(Musician) :-
    genre_instrumentalist(Musician, guitar, rock).

genre_instrument(Genre, Instrument) :-
    genre_instrumentalist(_, Instrument, Genre).
</pre>
<pre class="brush: plain; title: ; notranslate">
%Who plays the guitar?
| ?- plays_instrument(Who, guitar).

Who = 'Jimi Hendrix' ? ;

Who = 'Bob Marley' ? ;

Who = 'Peter Tosh' ? ;

Who = 'Johnny Stulic' ? ;

no

%Does Jimi Hendrix play the guitar?
| ?- plays_instrument('Jimi Hendrix', guitar).

true ?

yes

%Which instruments does Ringo Starr play?
| ?- plays_instrument('Ringo Starr', Which).

Which = drums ? ;

Which = keyboard ? ;

no

%Who is a rock guitarist?
| ?- rock_guitarist(Who).

Who = 'Jimi Hendrix' ? ;

Who = 'Johnny Stulic' ? ;

no

%Is Bob Marley a rock guitarist?
| ?- rock_guitarist('Bob Marley').

no

%Which instruments are used to play rock?
| ?- genre_instrument(rock, Which).

Which = guitar ? ;

Which = drums ? ;

Which = keyboard ? ;

Which = guitar ? ;

no
</pre>
<p>In the second task I have expanded a bit on requirements as it was otherwise almost completely the same as the first one. I have also used the same rule (plays) for instruments and genres to make the task more interesting and challenging.</p>
<p>After the first day with Prolog I must say I like it quite a lot. The language is very simple and logical (PROgramming in LOGic) and has low barrier to entry even for non programmers. I have explained basic structure of last program to my girlfriend who understood it quite quickly and was happy making queries on her own. When she once asked me to show her what I was working on at the moment (in Java), she gave up on it quite quickly as there was so much &#8220;noise&#8221; to explain before I could explain what am I actually trying to do. I think the barriers that exist around Prolog are result of it tackling problems from a different (even though as shown with the SQL analogy not completely unusual) angle and the lack of willingness amongst programmers to accept different approach to problems. But it&#8217;s only the end of the first day so my opinions are still only forming.</p>
]]></content:encoded>
			<wfw:commentRss>http://dalibornovak.co.uk/blog/seven-languages-in-seven-weeks-prolog-day-1/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Seven Languages in Seven Weeks &#8211; Io &#8211; Day 3</title>
		<link>http://dalibornovak.co.uk/blog/seven-languages-in-seven-weeks-io-day-3/</link>
		<comments>http://dalibornovak.co.uk/blog/seven-languages-in-seven-weeks-io-day-3/#comments</comments>
		<pubDate>Sun, 06 Mar 2011 13:05:34 +0000</pubDate>
		<dc:creator>Dalibor "Bore" Novak</dc:creator>
				<category><![CDATA[books]]></category>
		<category><![CDATA[Books]]></category>
		<category><![CDATA[Io]]></category>
		<category><![CDATA[Programming]]></category>

		<guid isPermaLink="false">http://dalibornovak.co.uk/blog/?p=133</guid>
		<description><![CDATA[It is day 3 with Io and the subjects that we are tackling are DSLs (domain specific languages) with a help from metaprogramming and concurrency in Io. As you can expect Io lends itself very naturally to defining DSLs due to its proverbial flexibility &#8211; after all the ability to change practically everything what it...<a href="http://dalibornovak.co.uk/blog/seven-languages-in-seven-weeks-io-day-3/">&#187;</a>]]></description>
			<content:encoded><![CDATA[<p><a href="http://dalibornovak.co.uk/blog/wp-content/uploads/2011/01/Io.jpg"><img class="alignleft size-full wp-image-61" title="Io" src="http://dalibornovak.co.uk/blog/wp-content/uploads/2011/01/Io.jpg" alt="" width="250" height="250" /></a>It is day 3 with <a href="http://iolanguage.com/">Io</a> and the subjects that we are tackling are <a href="http://www.martinfowler.com/bliki/DomainSpecificLanguage.html">DSLs</a> (domain specific languages) with a help from metaprogramming and <a href="http://www.iolanguage.com/scm/io/docs/IoGuide.html#Concurrency">concurrency</a> in Io.</p>
<p>As you can expect Io lends itself very naturally to defining DSLs due to its proverbial flexibility &#8211; after all the ability to change practically everything what it does, allows you to change the nature of Io to your specific problem domain.</p>
<p>In book this is explained through a simple example of defining a DSL in 13 lines of code that allows map definition in JSON like syntax. Homework 2 sets a similar but simpler goal of defining a syntax based on brackets that allows definition of lists. So here it is:</p>
<p>HW2: Create a list syntax that uses brackets</p>
<pre class="brush: plain; title: ; notranslate">
squareBrackets := method(
    call message arguments map(value,
        self doMessage(value)
    )
)

aList := [1, 2, 30, &quot;forty&quot;]
aList println
aList at(3) println
</pre>
<p><span id="more-133"></span>I have added squareBrackets slot that gets invoked when square brackets are encountered in the environment. This means that my method will be invoked when parser comes across [] pair. Once invoked the method inspects the activation to fetch arguments passed, arguments are then simply mapped into a list of their evaluated values.</p>
<p>After a quick scan of the reference documentation I noticed that Call prototype has an evalArgs method that will do it all for me. By using it solution becomes almost embarrassingly simple, so I have also added support for retrieving list elements by using square bracket notation by defining squareBracket slot on List prototype. This method gets invoked when square brackets are encountered in scope of an object cloned from List.</p>
<pre class="brush: plain; title: ; notranslate">
squareBrackets := method(call evalArgs)

List squareBrackets := method(index, self at(index))

aList := [1, 2, 30, &quot;forty&quot;]
aList println
aList[3] println
</pre>
<p>Another neat trick Bruce shows for tackling DSLs is redefining the &#8220;forward&#8221; method. This is the method that gets invoked when an object receives a message and doesn&#8217;t have a corresponding slot. As mentioned in <a href="http://dalibornovak.co.uk/blog/seven-languages-in-seven-weeks-io-day-1/">day1 article</a> the usual implementation of forward searches object&#8217;s prototypes trying to find a matching slot, but as it is just a method it can be replaced with a different functionality all together. This mechanism is then exploited to redefine a forward method on a Builder object in order to allow us to expres XML in Lisp-ish syntax. The example provided is then used as a base for two homework assignments.</p>
<p>HW1: Enhance the XML program to add spaces to show the indentation structure.</p>
<pre class="brush: plain; title: ; notranslate">
#!/usr/bin/env io

Builder := Object clone do(
    indent := 0

    forward := method(
        indentedText := method(text,
            &quot;  &quot; repeated(indent) .. text
        )

        indentedTag := method(tag, open,
            indentedText(if(open, &quot;&lt;&quot;, &quot;&lt;/&quot;) .. tag .. &quot;&gt;&quot;)
        )

        indentedOpenTag := method(tag,
            indentedTag(tag, true)
        )

        indentedCloseTag := method(tag,
            indentedTag(tag, false)
        )

        writeln(indentedOpenTag(call message name))
        indent = indent + 1
        call message arguments foreach(arg,
            content := doMessage(arg)
            if(content type == &quot;Sequence&quot;,
                writeln(indentedText(content))
            )
        )
        indent = indent - 1
        writeln(indentedCloseTag(call message name))
    )
)

Builder ul(
    li(&quot;Io&quot;),
    li(&quot;Lua&quot;, ul(li(&quot;Ioke&quot;), li(&quot;Self&quot;))),
    li(&quot;JavaScript&quot;)
)
</pre>
<p>The first part of the forward method defines some internal helper methods to deal with indentation (I like how you can limit a scope like that), the second (business) part of method the inspects call object introduced in <a href="http://dalibornovak.co.uk/blog/seven-languages-in-seven-weeks-io-day-2/">day 2</a> and renders the XML.</p>
<p>HW3: Enhance the XML program to handle attributes: if the first argument is a map (use the curly brackets syntax), add attributes to the XML program. For example: book({&#8220;author&#8221;: &#8220;Tate&#8221;}&#8230;) would print &lt;book author=&#8221;Tate&#8221;&gt;</p>
<pre class="brush: plain; title: ; notranslate">
#!/usr/bin/env io

OperatorTable addAssignOperator(&quot;:&quot; , &quot;atPutProperty&quot; )

curlyBrackets := method(
    aMap := Map clone
    call message arguments foreach(arg,
        aMap doMessage(arg)
    )
    return aMap
)

Map atPutProperty := method(
    self atPut(
        call evalArgAt(0) asMutable removePrefix(&quot;\&quot;&quot;) removeSuffix(&quot;\&quot;&quot; ),
        call evalArgAt(1)
    )
)

Map asAttributes := method(
    self map(k, v, &quot; #{k}=\&quot;#{v}\&quot;&quot; interpolate) join
)

Builder := Object clone do(

    indent := 0

    forward := method(

        indentedText := method(text,
            &quot;  &quot; repeated(indent) .. text
        )

        args := call message arguments
        tag := call message name

        write(indentedText(&quot;&lt;&quot; .. tag))
        if(args first name == &quot;curlyBrackets&quot;,
            write(doMessage(args first) asAttributes)
            args = args rest
        )
        writeln(&quot;&gt;&quot;)
        indent = indent + 1

        args foreach(arg,
            content := doMessage(arg)
            if(content type == &quot;Sequence&quot;,
                writeln(indentedText(content))
            )
        )

        indent = indent - 1
        writeln(indentedText(&quot;&lt;/&quot; .. tag .. &quot;&gt;&quot;))
    )
)

doRelativeFile(&quot;lispML.txt&quot;)

</pre>
<p>lispML.txt:</p>
<pre class="brush: plain; title: ; notranslate">
Builder ul(
    li(
        ul({&quot;paradigm&quot;:&quot;Object Oriented&quot;, &quot;typing&quot;:&quot;Dynamic&quot;},
                li(&quot;Io&quot;),
                li(&quot;Ruby&quot;))),
    li (
        ul({&quot;paradigm&quot;:&quot;Object Oriented&quot;, &quot;typing&quot;:&quot;Static&quot;},
                li(&quot;Java&quot;),
                li(&quot;C#&quot;))))
</pre>
<p>So let me try to give brief explanation of what is happening here. The bit of code on the top relating to operators, Map and curly brackets will parse JSON like Map definition and expose it as a string representing the XML element attributes. By now it should be fairly straightforward to understand. The Builder&#8217;s forward method was changed to check if the first argument is a &#8220;curlyBrackets&#8221; message. If it is it receives special treatment by being converted to string representing element attributes and written to opening tag. The rest of the arguments get treated in the usual manner as in HW1.</p>
<p>There is a caveat which wasted a fair bit of my time (<a href="http://comments.gmane.org/gmane.comp.lang.io/11745">and other peoples too</a>). When you update OperatorTable within the file, you are not changing semantics of the current file as the table was already read. So the changed behaviour only applies to any subsequently parsed files (or strings). This is why there is a separate lispML.txt file.</p>
<p>Next subject that book tackles is concurrency. As I expected by now Io has a very simple yet elegant approach to <a href="http://www.iolanguage.com/scm/io/docs/IoGuide.html#Concurrency">concurrency</a>. From concurrency point of view every object can be seen as an <a href="http://en.wikipedia.org/wiki/Actor_model">actor</a>. Messages can be passed to actors (objects) by prepending them with @ or @@. If a message is prefixed with @ it will be sent to actor&#8217;s queue and a future will be returned. Future object will become a result once the result is available. If it&#8217;s value is requested and result is not yet available it will block until it is. If a message is prefixed with @@ it will be put on actor&#8217;s queue and nil will be returned immediately.  When processing the message actor will start a coroutine which will process it asynchronously. That is pretty much all there is to it &#8211; simples. There were no homework assignments regarding concurrency but I might revisit this area to provide an example.</p>
<p>Let me try to sum up my impression of the Io after this brief encounter. The language is very simple and flexible (you could almost say it&#8217;s liquid like). Which I found to be a very good trait as it tries to get out of your way as much as possible and lets you do with practically  anything you can possibly come up with. This makes it exciting and fun to work with. On the flip side there is not that much of resources available for Io. And sometimes you are left wondering and trawling through mailing lists and lurking on IRC channels. Thankfully this doesn&#8217;t happen that often due to intrinsic simplicity and decent documentation on <a href="http://www.iolanguage.com/">iolanguage.com</a> which is very simple and minimal in true fashion of the language. As expected of such a dynamic language the single thread performance leaves much to be desired.</p>
<p>I am sure I will be returning to Io, if nothing else when working on some hobby code. Working with Io is just too much fun to leave it aside. Long live the clones!</p>
]]></content:encoded>
			<wfw:commentRss>http://dalibornovak.co.uk/blog/seven-languages-in-seven-weeks-io-day-3/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Seven Languages in Seven Weeks &#8211; Io &#8211; Day 2</title>
		<link>http://dalibornovak.co.uk/blog/seven-languages-in-seven-weeks-io-day-2/</link>
		<comments>http://dalibornovak.co.uk/blog/seven-languages-in-seven-weeks-io-day-2/#comments</comments>
		<pubDate>Wed, 26 Jan 2011 22:18:04 +0000</pubDate>
		<dc:creator>Dalibor "Bore" Novak</dc:creator>
				<category><![CDATA[books]]></category>
		<category><![CDATA[Books]]></category>
		<category><![CDATA[Io]]></category>
		<category><![CDATA[Programming]]></category>

		<guid isPermaLink="false">http://dalibornovak.co.uk/blog/?p=85</guid>
		<description><![CDATA[&#8220;Day 2&#8243; with Io on my more and more misnamed quest. In this chapter Bruce explains basics of conditionals, looping, operator definition and reflection. He also spends a bit more time to explain message passing in Io. In conditionals and looping section we get overview of some typical looping and branching structures. Such as a...<a href="http://dalibornovak.co.uk/blog/seven-languages-in-seven-weeks-io-day-2/">&#187;</a>]]></description>
			<content:encoded><![CDATA[<p><a href="http://dalibornovak.co.uk/blog/wp-content/uploads/2011/01/Io.jpg"><img class="alignleft size-full wp-image-61" title="Io" src="http://dalibornovak.co.uk/blog/wp-content/uploads/2011/01/Io.jpg" alt="" width="250" height="250" /></a>&#8220;Day 2&#8243; with <a href="http://www.iolanguage.com/">Io</a> on my more and more <a href="http://dalibornovak.co.uk/blog/seven-languages-in-seven-weeks/">misnamed quest</a>. In this chapter <a href="http://en.wikipedia.org/wiki/Bruce_Tate">Bruce</a> explains basics of conditionals, looping, operator definition and reflection. He also spends a bit more time to explain message passing in Io.</p>
<p>In conditionals and looping section we get overview of some typical looping and branching structures. Such as a simple infinite loop that will keep evaluating until a break:</p>
<pre class="brush: plain; title: ; notranslate">

loop(&quot;you spin me right round...&quot; println)

</pre>
<p>This can come in handy when implementing things such as servers etc. We also get to meet our good old friends (often seen in most languages) for and while loop:</p>
<pre class="brush: plain; title: ; notranslate">
i := 1
while(i &lt;= 10, i println; i = i + 1)

for(i, 1, 10, i println)

for(i, 10, 1, -1, i println)
</pre>
<p>First two lines are an example of a while loop. It will print numbers from 1 to 10. While loop takes a condition as a first parameter and it will keep evaluating statements passed in second parameter while the condition holds. Lines 4 and 6 are examples of a for loop. First one prints numbers from 1 to 10 and second one counts back from 10 to 1. This is due to the fact that second for loop utilises the optional step parameter. The parameters of a for loop method are: the name of the counter, the first value, the last value, optional step, and a message with sender. As we can see from example step parameter can be negative.<span id="more-85"></span></p>
<p>Next we learn about if method whose basic form is: if(condition, true code, false code) and that it if comes in following two flavours:</p>
<pre class="brush: plain; title: ; notranslate">
if(true, &quot;It's true&quot; println, &quot;It isn't true&quot; println)

if(true) then(
    &quot;It's true&quot; println
) else(
    &quot;It isn't true&quot; println
)
</pre>
<p>The syntax of first option is if(condition, true code, false code). The second option is self explanatory, I hope.</p>
<p>You might have noticed that I refer to &#8220;for&#8221;, &#8220;while&#8221; and &#8220;if&#8221; as methods. Which is in fact exactly what they are, as there are barely any keywords in Io due to its minimal syntax. All of them are merely methods defined on Object object. <img src='http://dalibornovak.co.uk/blog/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
<p>Next we move to operators which as you might have guessed by know are again just methods. All of the operators are defined in OperatorTable object which also holds operator precedence data. So to add a new operator all we have to do is add the operator to the table and define the method on the objects that we wish to support the operator on. Example based on <a href="http://planetmath.org/encyclopedia/LogicalImplication.html">logical implication</a>:</p>
<pre class="brush: plain; title: ; notranslate">
// hint: type OperatorTable in Io console for list of all
// supported operators and their precedence

OperatorTable addOperator(&quot;=&gt;&quot;, 12)

true =&gt; := method(bool, bool)
false =&gt; := true
</pre>
<p>We then proceed to learn a bit about message passing and reflection. Every message has three components: sender that sends the message, target that executes the message and arguments. We learn about the fact, that we can access all the information about the current message via &#8220;call&#8221; method exposed in each block (method). This method provides access to <a href="http://www.iolanguage.com/scm/io/docs/reference/index.html#/Core/Core/Call">Call</a> object which stores information and methods related to currently executed method . For instance this is the way to access message name and arguments:</p>
<pre class="brush: plain; title: ; notranslate">
mirror := Object clone

mirror reflect := method(
    call message name println
    call message arguments println
)

Io&gt; mirror reflect(1, &quot;two&quot;, 3)
reflect
list(1, &quot;two&quot;, 3)
==&gt; list(1, &quot;two&quot;, 3)
</pre>
<p>Armed with this knowledge we are asked to tackle 8 &#8220;homework&#8221; tasks:</p>
<p>HW1: A Fibonacci sequence starts with two 1s. Each subsequent number is the sum of the two numbers that came before: 1, 1, 2, 3, 5, 8, 13, 21, and so on. Write a program to find the nth Fibonacci number. fib(1) is 1, and fib(4) is 3. As a bonus, solve the problem with recursion and with loops.</p>
<pre class="brush: plain; title: ; notranslate">
fib := method(n, if (n &lt; 3, 1, fib(n - 2) + fib (n - 1)))

fibIter := method(n,
    previous := 1
    current := 1
    for (i, 3, n,
        buffer := current
        current = previous + current
        previous = buffer
    )
    return current
)

for (i, 1, 10, &quot;rec:#{fib(i)} iter:#{fibIter(i)}&quot; interpolate println)
</pre>
<p>I am used to programming in iterative style but I must say that this task lent itself naturally to recursion, which lead to a very simple one liner. Both methods rely on the fact that there is no need to calculate first 2 positions and 1 can be returned in that case. Armed with first 2 positions calculating the rest of the sequence is trivial.<br />
In recursive variant you can also see that I rely on the fact that return method (yep method again) is optional. If you don&#8217;t provide it method will simply return the value of the last evaluated statement.</p>
<p>HW2: How would you change / to return 0 if the denominator is zero?</p>
<pre class="brush: plain; title: ; notranslate">
Number originalDivision := Number getSlot(&quot;/&quot;)

Number / := method(denominator,
    if (denominator == 0, return 0, self originalDivision(denominator))
)

(1 / 2) println
(1 / 0) println
(2 / 1) println
</pre>
<p>I found this task quite interesting as I was wondering how to change the existing method without overwriting it. The solution I came up with is to just simply store original method in a new slot and redefine the division slot. The newly defined division slot then treats the exception when denominator is 0 and passes &#8220;business as usual&#8221; calculation to the original method.</p>
<p>HW3: Write a program to add up all of the numbers in a two-dimensional<br />
array.</p>
<pre class="brush: plain; title: ; notranslate">
sum2d := method(array, array flatten sum)

sum2d(list(list(1, 2, 3), list(1, 2, 3), list(1, 2, 3))) println
</pre>
<p>This one almost falls under the easier done than said section. First list is flattened into single dimension and then sum of flattened list&#8217;s elements is returned. Easy peasy.</p>
<p>HW4: Add a slot called myAverage to a list that computes the average of all the numbers in a list. What happens if there are no numbers in a list? (Bonus: Raise an Io exception if any item in the list is not a number.)</p>
<pre class="brush: plain; title: ; notranslate">
List myAverage := method((self sum) / (self size))

List myAverage1 := method(
    self map(element, if (element type == &quot;Number&quot;, element, 0)) myAverage
)

List myAverage2 := method(
    sum := 0
    counter := 0
    self foreach(element,
        if (element type != &quot;Number&quot;, Exception raise(&quot;Not a number element&quot;))
        sum = sum + element
        counter = counter + 1
    )
    sum / counter
)

a := list(1, 2, 3, 4, 5, 6, 7)

a myAverage println
list(&quot;a&quot;, &quot;b&quot;, &quot;c&quot;) myAverage1 println
a append(&quot;a&quot;)
a myAverage1 println
list(1,2,3) myAverage2 println
a myAverage2
</pre>
<p>I have solved this task in three different ways.<br />
First relies on methods provided by <a href="http://www.iolanguage.com/scm/io/docs/reference/Core/Core/List/index.html">List</a> prototype. It is very simple and reads well but it doesn&#8217;t handle non number elements.<br />
Second option first maps the List into a new List where non Number elements are replaced by 0 and then invokes &#8220;myAverage&#8221; method on it.<br />
Third option is the most verbose but I wanted to solve the problem with counters as well.</p>
<p>HW5: Write a prototype for a two-dimensional list. The dim(x, y) method should allocate a list of y lists that are x elements long. set(x, y, value) should set a value, and get(x, y) should return that value.<br />
HW6: Bonus: Write a transpose method so that (new_matrix get(y, x)) == matrix get(x, y) on the original list.<br />
HW7: Write the matrix to a file, and read a matrix from a file.</p>
<pre class="brush: plain; title: ; notranslate">
List2d := List clone do(
    dim := method(x, y, self setSize(y) mapInPlace(list() setSize(x)))

    set := method(x, y, value, self at(y) atPut(x, value))

    get := method(x, y, self at(y) at(x))

    transpose := method(
        newX := self size
        newY := self first size
        newMatrix := List2d clone dim(newX, newY)
        for(x, 0, newX -1,
            for (y, 0, newY -1,
                newMatrix set(x, y, get(y, x))
            )
        )
        return newMatrix
    )
)

setAndDisplay := method(matrix, x, y, value,
    matrix set(x, y, value)
    matrix get(x, y) println
    matrix println
)

matrix := List2d clone dim(3, 2)
matrix println

setAndDisplay(matrix, 0, 0, 5)
setAndDisplay(matrix, 1, 0, 10)
setAndDisplay(matrix, 2, 0, 15)

setAndDisplay(matrix, 0, 1, 20)
setAndDisplay(matrix, 1, 1, 25)
setAndDisplay(matrix, 2, 1, 300)

setAndDisplay(matrix, 2, 1, 30)

matrix transpose println

File with(&quot;matrix.dat&quot;) open write(matrix serialized) close
matrix = nil
matrix println
matrix := doRelativeFile(&quot;matrix.dat&quot;)
matrix println
</pre>
<p>&#8220;dim&#8221; method does the job by setting the size of the main list to y, as task prescribes. Next &#8220;mapInPlace&#8221; method is used to update each element of that field by setting it to a list with size of x. Beautiful.  I will not explain &#8220;set&#8221; and &#8220;get&#8221; methods as I think they are easy enough to understand.<br />
&#8220;transpose&#8221; method works on the principle of inspecting a List2d that we&#8217;re transposing and creating a new instance with swapped dimensions. Iterating through the elements and swapping their coordinates does the rest of the job.<br />
In regards to saving a matrix to a file and reading from it, I resorted to simple serialization. As Io serializes its objects into Io scripts, all I have to do to deserialize matrix from the file is to execute the contents of the file by virtue of &#8220;doRelativeFile&#8221; method.</p>
<p>HW8: Write a program that gives you ten tries to guess a random number<br />
from 1–100. If you would like, give a hint of “hotter” or “colder”<br />
after the first guess.</p>
<pre class="brush: plain; title: ; notranslate">
number := Random value(1, 100) round
previousDif := nil

loop(
    guess := File standardInput readLine(&quot;Take a guess: &quot;) asNumber

    if(guess isNan, continue)
    if(guess == number, break)

    dif := (number - guess) abs

    if(previousDif,
        if(previousDif &gt; dif) then(
            &quot;Warmer&quot; println
        ) elseif(previousDif &lt; dif) then(
            &quot;Colder&quot; println
        ) else(continue))

    previousDif = dif
)

&quot;You da man&quot; println
</pre>
<p>I don&#8217;t think there is much need to spend too many words on this task. It is quite self explanatory. The only new concepts introduced are generating a random number and reading from standard input, but they are very straightforward as you can see.</p>
<p>If I try to sum up my impressions after day 2 I must say that I am still finding it hard to wipe the smirk of my face when playing with Io. It is just so full of pleasant surprises and combined with the simplicity of the language it is hard for any self confessed geek not to like it IMHO.</p>
<p>Happy cloning!!</p>
]]></content:encoded>
			<wfw:commentRss>http://dalibornovak.co.uk/blog/seven-languages-in-seven-weeks-io-day-2/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Seven Languages in Seven Weeks – Io – Day 1</title>
		<link>http://dalibornovak.co.uk/blog/seven-languages-in-seven-weeks-io-day-1/</link>
		<comments>http://dalibornovak.co.uk/blog/seven-languages-in-seven-weeks-io-day-1/#comments</comments>
		<pubDate>Tue, 18 Jan 2011 00:08:56 +0000</pubDate>
		<dc:creator>Dalibor "Bore" Novak</dc:creator>
				<category><![CDATA[books]]></category>
		<category><![CDATA[Books]]></category>
		<category><![CDATA[Io]]></category>
		<category><![CDATA[Programming]]></category>

		<guid isPermaLink="false">http://dalibornovak.co.uk/blog/?p=60</guid>
		<description><![CDATA[My quest to learn seven languages in seven weeks continues. Next language that I am tackling is Io. By this time I am now very well aware, that due to the fact that I don&#8217;t have much time for private life lately, I will probably end up spending seven months for the task as mentioned...<a href="http://dalibornovak.co.uk/blog/seven-languages-in-seven-weeks-io-day-1/">&#187;</a>]]></description>
			<content:encoded><![CDATA[<p><a href="http://dalibornovak.co.uk/blog/wp-content/uploads/2011/01/Io.jpg"><img class="alignleft size-full wp-image-61" title="Io" src="http://dalibornovak.co.uk/blog/wp-content/uploads/2011/01/Io.jpg" alt="" width="250" height="250" /></a>My quest to learn <a href="http://dalibornovak.co.uk/blog/seven-languages-in-seven-weeks/">seven languages in seven weeks</a> continues. Next language that I am tackling is <a href="http://www.iolanguage.com/">Io</a>. By this time I am now very well aware, that due to the fact that I don&#8217;t have much time for private life lately, I will probably end up spending seven months for the task as mentioned in my <a href="http://dalibornovak.co.uk/blog/seven-languages-in-seven-weeks-ruby-week-1/">previous post</a>. In order to make some visible progress, I decided to blog about my endeavours on a day by day rather than language by language basis.</p>
<p>So let me sum up my thought after day one with Io. You might not heard about this language before as it is not as popular or well known as others mentioned in the book. Io is an object oriented prototype language. This means that it doesn&#8217;t have the notion of a class as an object template meaning that there is no distinction between classes and instances &#8211; all object are merely clones of other objects. The language is very simple and syntax is minimal. Objects are created by cloning like this:</p>
<pre class="brush: plain; title: ; notranslate">
Food := Object clone
</pre>
<p><span id="more-60"></span>As mentioned the language is not very widespread hence no syntax highlighting. Objects are nothing more than a collections of &#8220;slots&#8221;. Slots can hold values or methods both of which are objects and this is how slots are created:</p>
<pre class="brush: plain; title: ; notranslate">
Food description := &quot;Something to eat&quot;
Food eat := method(&quot;Yum!&quot; println)
</pre>
<p>First line defines a &#8220;description&#8221; slot that holds a value and second line defines an &#8220;eat&#8221; slot that holds a method. When message is passed to an object object is checked whether it contains a slot with that name. If it does it will either return a value or invoke the method held in the slot. If it doesn&#8217;t, then its protoype (object it was cloned from) and its prototypes are search for the matching slot and that one gets invoked if it exists. Otherwise an exception gets raised. This means that if we clone Food object to create pizza and define description and shape slots we get following behaviour:</p>
<pre class="brush: plain; title: ; notranslate">
Pizza := Food clone
Pizza description := &quot;Flat bread with toppings&quot;
Pizza shape := &quot;Round&quot;

Io&gt; Pizza description
==&gt; Flat bread with toppings
Io&gt; Pizza shape
==&gt; Round
Io&gt; Pizza eat
Yum!
==&gt; Yum!
</pre>
<p>What I find very amusing about this is that we can change slots and prototypes at run time, which shows the malleability of language and makes it feel like working with putty. For instance let&#8217;s assume Pizza is also a programming language (which is an unorthodox but not a <a href="http://en.wikipedia.org/wiki/Pizza_%28programming_language%29">completely insane idea</a>). Not a problem &#8211; new ProgrammingLanguage object needs to be cloned and it has to be added to list of Pizza&#8217;s prototypes.</p>
<pre class="brush: plain; title: ; notranslate">
ProgrammingLanguage := Object clone
ProgrammingLanguage description := &quot;Something to use for programming&quot;
ProgrammingLanguage paradigm := &quot;generics, algebraic types&quot;
ProgrammingLanguage eat := &quot;It's silly to try to eat a language&quot;

Pizza appendProto(ProgrammingLanguage)

Io&gt; Pizza description
==&gt; Flat bread with toppings
Io&gt; Pizza paradigm
==&gt; generics, algebraic types
Io&gt; Pizza eat
Yum!
==&gt; Yum!
</pre>
<p>We have just proven of Io&#8217;s flexibility and at the same time seen how it deals with multiple inheritance. If an object does not have a slot that would respond to the message passed to it, it will search it&#8217;s prototypes using depth first algorithm. That&#8217;s why Pizza will search it&#8217;s own slots when trying to respond to  a message, if it can&#8217;t find a match it will try Food&#8217;s slots. If it can&#8217;t find a match there either, it will search Food&#8217;s prototype &#8211; Object. After it has gone full depth on first prototype (Food) and it still hasn&#8217;t found an appropriate slot, it will try the next prototype (if present), which in our case is ProgrammingLanguage. And so on&#8230;  This is how &#8220;paradigm&#8221; message gets resolved on Pizza object in our example.</p>
<p>&#8220;Homework&#8221; is really simple at the end of the first day with Io. Probably due to the fact that it is not completely trivial to <a href="http://ozone.wordpress.com/2006/07/27/build-io-on-ubuntu-dapper/">install</a>.</p>
<p>First task is to run an Io program from a file. Which is just the same as running a <a href="http://dalibornovak.co.uk/blog/seven-languages-in-seven-weeks-ruby-week-1/">ruby</a> script. If you write your application in a file called HelloWorld.io, you can run it like this:</p>
<pre class="brush: plain; title: ; notranslate">
$io HelloWorld.io
</pre>
<p>It is also possible to make script executable on *nix systems by marking file as executable and adding a <a href="http://en.wikipedia.org/wiki/Shebang_%28Unix%29">shebang</a> to the top of the file like so:</p>
<pre class="brush: plain; title: ; notranslate">
#!/usr/bin/env io

&quot;Hello Cruel World!&quot; println
</pre>
<p>Second task is executing the code in a slot given its name. It&#8217;s almost easier done than said. <img src='http://dalibornovak.co.uk/blog/wp-includes/images/smilies/icon_wink.gif' alt=';)' class='wp-smiley' /> </p>
<pre class="brush: plain; title: ; notranslate">
Io&gt; Pizza perform(&quot;description&quot;)
==&gt; Flat bread with toppings
</pre>
<p>Thus far I am very impressed by Io. Exploring it just brings a smirk on my cheeks and what I&#8217;ve seen so far makes me quite excited at the prospect of finding out what&#8217;s next on its agenda. I think having that much fun, must be worth something, even if I might never get to do anything productive with the language.</p>
<p>Well I hope on day 2 Io will show more of its tricks&#8230;</p>
]]></content:encoded>
			<wfw:commentRss>http://dalibornovak.co.uk/blog/seven-languages-in-seven-weeks-io-day-1/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Seven Languages in Seven Weeks &#8211; Ruby &#8211; Week 1</title>
		<link>http://dalibornovak.co.uk/blog/seven-languages-in-seven-weeks-ruby-week-1/</link>
		<comments>http://dalibornovak.co.uk/blog/seven-languages-in-seven-weeks-ruby-week-1/#comments</comments>
		<pubDate>Mon, 03 Jan 2011 22:15:29 +0000</pubDate>
		<dc:creator>Dalibor "Bore" Novak</dc:creator>
				<category><![CDATA[books]]></category>
		<category><![CDATA[Books]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[Ruby]]></category>

		<guid isPermaLink="false">http://dalibornovak.co.uk/blog/?p=29</guid>
		<description><![CDATA[It is the end of the first &#8220;week&#8221; with the book. Due to very busy pre holidays period and holidays it actually took me a month to get through it. I hope things will be less hectic in coming weeks so that I can live up to the book&#8217;s title. So week one with Ruby...<a href="http://dalibornovak.co.uk/blog/seven-languages-in-seven-weeks-ruby-week-1/">&#187;</a>]]></description>
			<content:encoded><![CDATA[<p><a href="http://dalibornovak.co.uk/blog/wp-content/uploads/2011/01/Star-Ruby-The-Delong-Star-Ruby.jpg"><img class="alignleft size-medium wp-image-55" title="Star Ruby (The-Delong-Star-Ruby)" src="http://dalibornovak.co.uk/blog/wp-content/uploads/2011/01/Star-Ruby-The-Delong-Star-Ruby-300x277.jpg" alt="Star Ruby (The-Delong-Star-Ruby)" width="300" height="277" /></a>It is the end of the first &#8220;week&#8221; with the <a href="http://dalibornovak.co.uk/blog/seven-languages-in-seven-weeks/">book</a>. Due to very busy pre holidays period and holidays it actually took me a month to get through it. I hope things will be less hectic in coming weeks so that I can live up to the book&#8217;s title.</p>
<p>So week one with Ruby then. Everyone interested in software development has almost certainly come across this language. It has captured the interest of disgruntled masses with very productive Rails framework back in 2005. I remember seeing the infamous blog demo videocast and being blown away by the fact that this guy seems to be able to knock up a blog from scratch in about 15 minutes. What I was even more impressed with was how clean and sensible the code he was writing was. I tinkered around with Ruby for a little bit back then, but I got pulled more deeply into the world of Java at that time, as as this was lingua franca in company where I worked and the idea was that it was more important for me to master that than a side language.</p>
<p>So what did I miss out on by doing that?  For one Ruby is a pure Object Oriented programming language which means that everything including literals is an object. It uses strong and dynamic (<a href="http://en.wikipedia.org/wiki/Duck_typing">duck</a>) typing strategies. This allows for polymorphism by functionality rather then by declared types; which gives you more freedom and less typing at the expense of compile time type checking. All the classes in Ruby are <a href="http://rubylearning.com/satishtalim/ruby_open_classes.html">open</a> and can be extended, including classes such as String and NilClass. It supports <a href="http://juixe.com/techknow/index.php/2006/06/15/mixins-in-ruby/">mixins</a> (think interfaces with implementation) as a workaround for multiple inheritance. Provided APIs are rich and frequently provide same functionality via different methods. Ruby and it&#8217;s APIs rely on <a href="http://martinfowler.com/bliki/Closure.html">code blocks</a> (closures, higher order functions &#8211; how ever you want to call them) heavily.  It also provides good <a href="http://weare.buildingsky.net/2009/08/25/rubys-metaprogramming-toolbox">metaprogramming</a> facilities.  All of this makes it a wonderful and expressive language, but at the same time it gives you all the rope you want to hang yourself.<span id="more-29"></span></p>
<p>Bruce Tate (author) organised each of the chapters into 3 &#8220;days&#8221; per language each followed by self-study a.k.a. &#8220;homework&#8221;.</p>
<p>On day 1 Bruce introduces Ruby and some of it&#8217;s syntax. We learn about the fact that it is purely OO and strongly &#8220;duck&#8221; typed. Even this little knowledge is enough to have so decent fun with Ruby. For instance one of the homework exercises requires you to print your name 10 times, which can be accomplished very elegantly with a following one liner:</p>
<pre class="brush: ruby; title: ; notranslate">10.times { puts 'Dalibor' }</pre>
<p>We can do this as Ruby is purely OO language which means that literal 10 represents an object of Fixnum class. We can lookup API and discover times method that takes a code block; which we use to print the name. This solution is very elegant and also reads very well. With the exception of cryptic puts keyword it could be read by anyone and understood immediately, which is probably not the case with your &#8220;good old&#8221; for loop.</p>
<p>On day 2 both standard collections get introduced Array and Hash. Ruby <a href="http://rubylution.ping.de/articles/2005/12/21/rubys-rich-array-api">rich API</a> strategy gets introduced on the example of Array which can be treated as any of the following: array, stack, queue, set or a linked list. Code blocks get explained (whops! &#8211; I already started using them in day one, but on the other hand we are encouraged by author to explore). Function and class syntax gets explained, which is not very surprising past the fact that due to dynamic typing types don&#8217;t get declared. What is more interesting is how Ruby tackles the multiple inheritance by providing mixins. Mixins get included in a class and extend it with their own behaviour. As they get effectively included in the host class they can access and depend on their functionality. It is explained how <a href="http://www.ruby-doc.org/core/classes/Comparable.html">Comparable</a> and <a href="http://www.ruby-doc.org/core/classes/Enumerable.html">Enumerable</a> use this mechanism to provide very rich APIs to classes that include them &#8211; all the host classes have to provide are implementation of &lt;=&gt; operator and each method. An example of a task given on day 2 is implementation of a simple grep tool which I solved like this:</p>
<pre class="brush: ruby; title: ; notranslate">
#!/usr/bin/env ruby

unless ARGV.size == 2
    puts 'Provide name of the file to grep and what to grep for'
    exit
end

counter = 0
File.foreach(ARGV[0]) do |line|
    counter += 1
    puts &quot;#{counter}: #{line}&quot; if line.include? ARGV[1]
end
</pre>
<p>In this example I&#8217;ve used two mechanisms I find interesting. One is String variable substitution &#8211; this is a functionality provided by double quoted strings which allows variables values to be used as part of the string by wrapping them in #{} (see line 11 for example).  Another one is file access using code block. By using foreach method that takes a code block file gets opened and closed for us and executes provided code block for every line in the file. This is quite a lot of functionality from a one method and is also very flexible. I could do something similar in Java, but I would probably have to use an anonymous inner class which would be very verbose.</p>
<p>On day 3 <a href="http://weare.buildingsky.net/2009/08/25/rubys-metaprogramming-toolbox">metaprogramming</a> hits the stage. Two mechanisms are explained &#8211; metaprogramming via method_missing method. This method gets invoked every time a method that does not exist is invoked on an object. By inspecting the method and arguments passed we can provide implementation for methods that don&#8217;t formally exist on the class. Other (arguably cleaner) mechanism is using modules. This mechanism involves mixing a module into class which then modifies the host by adding new capabilities. This is used by Rails framework to provide ActiveRecord functionality.<br />
Metaprogramming can be demonstrated by following homework assignment. RubyCsv class has ActAsCsv module mixed in. When module is included in a class included method gets invoked. This in turn extends base class (RubyCsv) with ClassMethods module that contains acts_as_csv method. When this method gets invoked it includes InstanceMethods module that reads a csv file and initialises instance variables. It also provides each method that returns instances of CsvRow objects, which uses method_missing to provide &#8220;getters&#8221; for values based on headers.</p>
<pre class="brush: ruby; title: ; notranslate">
#!/usr/bin/env ruby

module ActsAsCsv

  def self.included(base)
    base.extend ClassMethods
  end

  module ClassMethods
    def acts_as_csv
      include InstanceMethods
    end
  end

  module InstanceMethods

    def read
      @csv_contents = []
      filename = self.class.to_s.downcase + '.txt'
      File.open(filename) do |file|
          @headers = file.gets.chomp.split(', ')

          file.each do |row|
            @csv_contents &lt;&lt; row.chomp.split(', ')
          end
      end
    end

    attr_accessor :headers, :csv_contents

    def each &amp;block
        @csv_contents.each do |line|
            block.call CsvRow.new(@headers, line)
        end
    end

    def initialize
      read
    end

  end

end

class CsvRow

    def initialize headers, row
        @data = {}
        headers.each_index do |index|
            @data[headers[index]] = row[index]
        end
    end

    def method_missing name, *args
        if @data.has_key? name.to_s
            @data[name.to_s]
        end
    end

end

class RubyCsv  # no inheritance! You can mix it in
    include ActsAsCsv
    acts_as_csv
end

m = RubyCsv.new
puts m.headers.inspect
puts m.csv_contents.inspect
m.each {|row| puts &quot;#{row.capital} is capital city of #{row.country}&quot;}

</pre>
<pre class="brush: plain; title: ; notranslate">
country, capital
Slovenia, Ljubljana
United Kingdom, London
</pre>
<p>So if we use provided sample csv file the result we will get will be:</p>
<pre class="brush: plain; title: ; notranslate">
[&quot;country&quot;, &quot;capital&quot;]
[[&quot;Slovenia&quot;, &quot;Ljubljana&quot;], [&quot;United Kingdom&quot;, &quot;London&quot;]]
Ljubljana is capital city of Slovenia
London is capital city of United Kingdom
</pre>
<p>So what are my thoughts on Ruby after my brief encounter with the language. I am impressed with flexibility, expressiveness and productivity of the language. I can see how it can be extended to provide very rich and readable APIs and DSLs. Language feels very malleable due to its metaprogramming support. On the other hand, as much as duck typing helps with keeping the code simple, it does leave me feel a bit exposed to all sorts of type issues, it makes writing IDEs like I&#8217;m used to difficult and surely doesn&#8217;t help with performance. As language allows the programmer to take many liberties with it, I think it warrants quite a lot of discipline and good understanding of the entire codebase of the project you are working on. This makes me think, that working an a project that uses Ruby would probably be pure delight if the team would be knowledgeable and disciplined. I have a sneaky suspicion that it would be a right nightmare to work on a project involving legacy code and a suboptimal team. Especially if there are members that think they know more than they actually do and get entangled in all the rope Ruby will happily provide.</p>
]]></content:encoded>
			<wfw:commentRss>http://dalibornovak.co.uk/blog/seven-languages-in-seven-weeks-ruby-week-1/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>Seven Languages in Seven Weeks</title>
		<link>http://dalibornovak.co.uk/blog/seven-languages-in-seven-weeks/</link>
		<comments>http://dalibornovak.co.uk/blog/seven-languages-in-seven-weeks/#comments</comments>
		<pubDate>Mon, 29 Nov 2010 22:34:39 +0000</pubDate>
		<dc:creator>Dalibor "Bore" Novak</dc:creator>
				<category><![CDATA[books]]></category>
		<category><![CDATA[Books]]></category>
		<category><![CDATA[Clojure]]></category>
		<category><![CDATA[Erlang]]></category>
		<category><![CDATA[Haskell]]></category>
		<category><![CDATA[Io]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[Prolog]]></category>
		<category><![CDATA[Ruby]]></category>
		<category><![CDATA[Scala]]></category>

		<guid isPermaLink="false">http://boreplusplus.co.uk/blog/?p=17</guid>
		<description><![CDATA[Lately I have a feeling that Java ecosystem is getting a bit stale. To add to that grass seemed greener on the other side of the fence. Several of my friends that I started my coding career with in J2EE trenches have deserted and moved on to Ruby. None of them ever mentioned regretting the...<a href="http://dalibornovak.co.uk/blog/seven-languages-in-seven-weeks/">&#187;</a>]]></description>
			<content:encoded><![CDATA[<p><a href="http://www.pragprog.com/titles/btlang/seven-languages-in-seven-weeks"><img class="alignleft size-full wp-image-18" title="Seven Languages in Seven Weeks" src="http://dalibornovak.co.uk/blog/wp-content/uploads/2010/11/sevenLanguages.gif" alt="Book Cover: Seven Languages in Seven Weeks: A Pragmatic Guide to Learning Programming Languages by Bruce A. Tate" /></a>Lately I have a feeling that Java ecosystem is getting a bit stale. To add to that grass seemed greener on the other side of the fence. Several of my friends that I started my coding career with in J2EE trenches have deserted and moved on to Ruby. None of them ever mentioned regretting the move.</p>
<p>Then new languages that run on JVM started gaining traction and I had a little play with Groovy couple of years ago. I liked the language very much and I grokked why my friends were so happy with Ruby path they&#8217;ve chosen. Sheer expressiveness and productivity provided were impressive. I tried to push for Groovy to be used at work but it never got beyond utilities and scripts. I once read that someone said that the problem Groovy has, is that it is not called Business Logic Expression Language. It seems that sentiment rings quite true.</p>
<p>Anyway as I mentioned earlier Java no longer feels quite like a nice new comfy shirt. I am feeling that it&#8217;s constraining me and due to my brushes with alternative, there is always that little question in the back of my head: &#8220;Am I using the proverbial golden hammer?&#8221;</p>
<p>Recently I started looking over the fence again and I am seeing that there seems to be more choice than ever. One of the languages that sparked my interest was Scala. I checked out some of the websites devoted to it and found that community seems quite vibrant and that the language itself is very interesting indeed. Also the fact that it allows and encourages functional programming sparked my interest even further. I am quite familiar with object orientation and have merely brushed with functional programming at uni. The prospect of getting my head around something new and the promises that functional programming paradigm brings (especially regarding concurrency) got me quite excited.</p>
<p>As I almost decided to devote more time to Scala I have attended <a href="http://skillsmatter.com/event/agile-scrum/agile-testing-bdd-exchange-2010">Agile Testing &amp; BDD eXchange</a>. In one of the presentations Erik Stenman talked about Erlang amongst other things and caught my attention.<span id="more-17"></span></p>
<p>Now I knew I have a problem. Too many languages and too little time. I realised that before I commit to a single language I want to have a bit of a nose around the programming languages landscape. So I thought, wouldn&#8217;t it be great if there was a book that would give you a crash course in several languages. Nothing too deep &#8211; only enough to present you the language&#8217;s philosophy and give you a feel of the language. Preferably these languages should cover different paradigms so that I could evaluate them as well and try to understand their strengths and weaknesses as well.</p>
<p>Well guess what a bit less than a month ago The Pragmatic Bookshelf have published <a href="http://pragprog.com/titles/btlang/seven-languages-in-seven-weeks">Seven Languages in Seven Weeks: A Pragmatic Guide to Learning Programming Languages by Bruce A. Tate</a>. From a bit of scan reading it seems that book is almost a perfect fit to my requirements. It promises to take you on a journey through seven languages in seven days (I&#8217;ll see if I can keep up) and languages are chosen to give you a flavour of object orientated programming, function programming, prototype based OO, logic programming and hybrids.</p>
<p>I will try to keep up with the program and tackle a new language each week. For those interested in my progress and findings I intend to blog about them as I go along. Wish me luck on my journey of discovery.</p>
]]></content:encoded>
			<wfw:commentRss>http://dalibornovak.co.uk/blog/seven-languages-in-seven-weeks/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
	</channel>
</rss>
