Investigations into Io Concurrency

After yesterday’s very enjoyable Code Retreat in London, i went with Matt Pep to visit Hack Space where we worked together on some Io.

I confess, i haven’t quite finished Day 2’s exercises, but i was anxious to get on and try some of the concurrency stuff. We discovered a couple of interesting things by playing around with it.

Waiting for asynchronous processes

If you start an asynchronous message but don’t add a ‘wait’, the process stays on hold until another Io process starts up. For example:

Io> slower := Object clone
Io> faster := Object clone
Io> slower start := method(wait(2); writeln("slowly ", Date now))
Io> faster start := method(wait(1); writeln("quickly ", Date now))

I’ve added timestamps to the example because it helps to see what is happening.

slower @@start; faster @@start
==> nil
Io> Date now
==> 2011-06-26 12:33:30 BST
Io> wait(3)
quickly 2011-06-26 12:33:34 BST
slowly 2011-06-26 12:33:35 BST
==> nil

I started both slower and faster asynchronously but didn’t wait for them to finish. I checked the current date and time for reference. Then I did a wait(3). At that point Io was in control again and could run the asynchronous processes. The timestamp shows that they didn’t run until the wait had begun.

I wonder, is there a way of detecting whether there are asynchronous processes still waiting to be run?

Actors do one thing at a time

Although you can run start on the objects slower and faster together in parallel, you can’t run two processes on the same object asynchronously. See what happens if we try:

Io> slower @@start; slower @@start; wait(5)
slowly 2011-06-26 12:35:12 BST
slowly 2011-06-26 12:35:14 BST
==> nil

I kind of expected those to come out at the same time, but no, it waits for the method to finish before running it again. I checked and the same thing is true with two different methods. It seems that an object does not run two methods simultaneously.

This is because the object has become an actor, and an actor manages its own resources. I suspect this is probably part of Io’s strategy for avoiding race conditions.


The concept of futures excited me. It conjured an impression that you’d be able to calculate multiple versions of possible futures … but unfortunately it’s not that exciting.

It seems that a future result is one that may not yet be known. But it doesn’t hold up your program while waiting for the answer. You can store the future answer and move on. Only when you actually try to use it will your program block until it’s available.

Calculating futures seems to follow the same restrictions as the other asynchronous actor processes, in that one object can only do one thing at a time. But two objects can calculate future results concurrently.


Ahhh, we didn’t get that far! I hope i’ll be able to do a bit before the skype call today! :)

An Io testing framework

I couldn’t go on for much longer in Io without somehow testing my code. I’m okay with printing out results for a little while, but as soon as i come to refactoring my code i feel the need to assert somehow the results i’m expecting.

I had a nice chat with Matt Pep about it and tried a few things before i came to the idea of adding a shouldEqual slot on Object so that anything can assert equality.

Object shouldEqual := method(expected,
  if(self == expected,
    "." print,
    ("Expected " .. self .. " to equal " .. expected) println

This means i can do a few things like this:

myList := List2d clone
myList dim(3, 5)
myList items size shouldEqual(5)

And things like this:

myList set(2, 3, "Middle")
myList get(2, 3) shouldEqual("Middle")

The only question i have now is: how do i take that assertEqual slot definition out of this file and into a file of its own that i can include everywhere from now on?

I’d like to do something like:


How would you do such a thing in Io?

I’m afraid i still haven’t finished Day 2’s exercises yet! I must move on to Day 3 tomorrow …! :)


Susan Potter has found the answer! I will try this later: Io’s “require”

Week 2 Day 2 – Io craziness!

Io, you mad sexy beast! What kind of craziness is going on here?!

You don’t hide any secrets, do you? I can see all the operators by typing OperatorTable. I see their order of precedence. I can add an operator anywhere i like!

But i’m afraid i’m lost with your message targets and receivers. I’m looking at the example in the book but i’m really not sure what it’s getting at. I think i’m going to have to be guided to try my own example that needs message reflection before i really get this.

Still, cool that i can can implement an ‘unless’ … i see why they say that everything in Io is a message, even things that look like keywords.

Ah, i understand object reflection much more easily. Nice bit of recursion going on there, going up through the prototype hierarchy.

Well, it’s fair to say that day 2 is really stretching me. I spent ages on the fibonacci calculator last night, and still wasn’t happy with my output. I did a recursive calculator which i understood well but it was slow. I then did an iterative calculator which i couldn’t comprehend so well but at least it was faster. I wanted to do some clever algorithm using Phi, but i was too tired!

Tonight i got a bit further. I was stuck by the division by zero problem until i realised that you can use getSlot(“/”) to pull out the current functionality to save for later.

Adding up all the numbers in a 2D array was nice. I first did it as a stand-alone method, like this:

sum2d := method(array,
  total := 0
  array foreach(i, innerArray, total = total + innerArray sum)


I later had the idea of adding a sum2d slot on the List prototype, like this:

List sum2d := method(
  total := 0
  self foreach(i, innerArray, total = total + innerArray sum)

array sum2d

I got the idea from the myAverage slot exercise, which i also enjoyed. I found it quite fascinating that you can extend List so easily like this:

List myAverage := method(
  self sum / self size

Later on i went into more detail so as to perform an average only on numeric values in the list:

List myAverage := method(
  sum := 0
  size := 0
  self foreach(i, value,
    if(value type == "Number", sum = sum + value; size = size + 1)
  if(size == 0, return 0)
  sum / size

I was very pleased to learn today that, like Ruby, Io has a return option to get out of a method early. That saves a lot of code.

I’m really liking what i’ve seen so far of Io. The hardest thing is getting to know the syntax and idioms.

I still have more to do on Day 2, but that’ll do for tonight!


P.S. Tomorrow i want to make a simple testing framework. I want to be able to do this:

list(1, 2, "only", "average", "numbers", 3) myAverage should == 2

With what i’ve learned so far in Io i think i can do it.

Week 2 Day 1 – Dipping my toe into Io

Today i started to learn a new programming language, for the first time since trying out Lisp several months ago. Here are my first thoughts upon encountering Io.

My initial reactions

Reading a book doesn’t tell you much. I read the chapter twice before i actually tried it out, and doing feels so different from reading. Something about seeing it produce results before your very eyes feels thoroughly enlightening!

I like the space between the receiver and message. It’s so readable. “Vehicle type” and “Vehicle description” are just natural language, you’d hardly think it was code at all!

I don’t much like the concept of the Lobby. It’s like everything is just hanging around there, chilling out, doing nothing. Don’t you guys have someplace to be?! I suppose every language has to keep its objects somewhere – the difference with Io is we get to find them all in one place.

Really understanding prototypes

When i tried out the proto method i think i properly GOT IT. Seeing those hex identifiers really proved to me that i didn’t clone my ferrari from some abstract Car concept. I cloned an actual Car. THE Car, in fact.

Io> ferrari proto
==>  Car_0x1002a6be0:
  drive            = method(...)
  type             = "Car"

Io> Car
==>  Car_0x1002a6be0:
  drive            = method(...)
  type             = "Car"

Io> Car proto
==>  Vehicle_0x1003d9090:
  description      = "Something to take you far away"
  type             = "Vehicle"

Creating a singleton

Could it possibly be any easier to create a singleton?!

Io> Highlander clone = Highlander
==>  Highlander_0x1005ae7f0:
  clone            = Highlander_0x1005ae7f0
  type             = "Highlander"

“Highlander, your clone method returns Highlander.” — “Right you are!”

Io typing

I would say that Io is strongly typed. It will not let me add together a Number and a Sequence (Sequence seems to be what Io calls a string)

Io> 1 + "2"

  Exception: argument 0 to method '+' must be a Number, not a 'Sequence'
  message '+' in 'Command Line' on line 1

However, like Ruby, some strings can be converted to numbers:

Io> 1 + "2" asNumber
==> 3

So, even though Io might have guessed what i meant by 1 + “2” it’s not going to just do it for me unless i ask nicely!

The typing is dynamic, meaning it is figured out at runtime, as demonstrated by this test:

Io> Tester := Object clone
==>  Tester_0x100532ad0:
  type             = "Tester"

Io> Tester test := method(1 + "2")
==> method(
    1 + "2"

Io> Tester test

  Exception: argument 0 to method '+' must be a Number, not a 'Sequence'
  +                                   Command Line 1
  Tester test                          Command Line 1

Other discoveries

Here is a useful thing:

Io> Object slotNames sort
==> list(, !=, -, .., <, , >=, ?, @, @@, actorProcessQueue, actorRun, ancestorWithSlot, ancestors, and, appendProto, ...)

I am not sure of the distinction between a Sequence and a String. It appears that a Sequence is a String.

Io> "hello" type
==> Sequence
Io> "hello" isKindOf(Sequence)
==> true
Io> "hello" isKindOf(String)
==> true

You can change an object’s prototype and all of a sudden it won’t be able to respond to slots anymore:

Io> Vehicle := Object clone
==>  Vehicle_0x1003d94b0:
  type             = "Vehicle"

Io> Vehicle description := "Something to take you far away"
==> Something to take you far away

Io> Car := Vehicle clone
==>  Car_0x1004ed400:
  type             = "Car"

Io> Car description
==> Something to take you far away

Io> Car setProto(Object)
==>  Car_0x1004ed400:
  type             = "Car"

Io> Car description

  Exception: Car does not respond to 'description'
  Car description                      Command Line 1

I found that interesting!

I think i’m going to like Io! :)

Ruby Classes and Superclasses

An interesting question came up in this week’s Seven Languages in Seven Weeks skype call. We initially thought it might be a difference between versions of Ruby, but having looked more closely, i don’t think it is. Both 1.8.7 and 1.9.2 behave in this slightly odd way.

For reference, we are talking about Figure 2.1: Ruby Metamodel on page 26.

As we all now know, 4 is an object.

> 4.class
 => Fixnum

Fixnum inherits from Integer which inherits from Numeric.

> Fixnum.superclass
 => Integer
> Integer.superclass
 => Numeric

Each of Fixnum, Integer and Numeric are of class Class.

> [Fixnum, Integer, Numeric].map(&:class)
 => [Class, Class, Class]

The superclass of Numeric is Object.

> Numeric.superclass
 => Object

But the superclass of Class goes to Module and then to Object.

> Class.superclass
 => Module 
> Module.superclass
 => Object

And now, through the power of my very limited Open Office Drawing skills, i shall try to demonstrate what i think the diagram really looks like.

So where did Module come from? Why is a Class also a Module? And if Numeric is of class Class, why is its superclass not also Module?

I don’t think it’s particularly important to know these things, but they were interesting questions and i don’t know the answers.

Does anyone know?

Week1 Day 3 – Ruby metaprogramming

Seven Languages in Seven Weeks really does more than scratch the surface of a language. It shows off what each language does best. Ruby is great at expressive metaprogramming, so we wasted no time into diving deep into not one, but three types of metaprogramming:

  1. Opening an existing class to add extra methods
  2. Using method_missing to define dynamic methods
  3. Creating mixin modules to extend functionality

For me, this was highly insightful. Metaprogramming is always something that Other People do. I have written a couple of gems before, but i didn’t really understand what i was doing – i just played around copying examples until it did what i wanted. Or more often, i would be quick to use inheritance, not realising that a mixin module might serve me better.

I was inspired by Seven Languages in Seven Weeks where it showed how to start with a simple module and then adapt it a little to make it even more flexible. In future i will refer to this book to guide me as it explains so well what’s going on.

module ActsAsCsv

  def self.included(base)
    base.extend ClassMethods

  module ClassMethods
    def acts_as_csv
      include InstanceMethods

  module InstanceMethods
    attr_accessor :headers, :csv_contents

    def initialize

    def read
      # ...


class RubyCsv
  include ActsAsCsv

We write a module which, once included, the first thing it does is adds another module to the class which included it. That module provides a macro method which, when called, adds instance methods and attributes.

I now realise that there is nothing special about the module names ClassMethods and InstanceMethods. They are just named that way for clarity. There is not really any voodoo going on here.

When trying to add an each method i started off like this:

m =
m.each{|row| puts row.inspect }

I implemented an each method like this:

def each(&block)
  @csv_contents.each {|r| }

Sure enough, i was able to inspect the row. But then we wanted to do this, where one of the headings in the CSV file was ‘one’:

m.each{|row| puts }

“No problem!” i thought. “Time for a method_missing” … but then i realised something i definitely would not have anticipated without doing the exercise.

undefined method `one' for ["lions", "tigers"]:Array (NoMethodError)

There you see the problem?! I’m working with an array at this point! Looking back at the book, it gave me a hint, which i had missed:

Modify the CSV application to support an each method to return a CsvRow object.

Ah, so that’s the answer! I modified my each method to do this:

def each(&block)
  @csv_contents.each do |r|
    row =, r)

I had to decide where to put the CsvRow class, and decided to put it as part of the module so there’s nothing else i had to require when mixing in the module.

I needed to pass the headings found, so that the row could implement its method_missing and find the right position in the array. The CsvRow class ended up like this:

class CsvRow
  attr :contents, :headers

   def initialize(headers, contents)
    @headers = headers
    @contents = contents

  def method_missing(method)
    index = @headers.index(method.to_s)
    raise "No heading '#{method}' in the CSV file." if index.nil?


The full solution can be found here: week1-ruby/acts_as_csv_module.rb

I am really glad of the opportunity to explore and understand Ruby metaprogramming a lot better. I am also extremely excited for what i’m going to learn in the other six languages in the next six weeks. This has set me up to expect some really awesome things!

Week 1 Day 2 – Diving deeper into Ruby

I had a really great day. Gave myself a day off from working, and went to London to meet my apprentice Rohit, see a few friends and go to eXtreme Tuesday Club in the evening.

At 6pm i met with Dan in Covent Garden and we worked through a bit of #7languages7weeks Day 2 together. We came up with three ways of splitting up an array into groups of four, ending with the beautifully elegant each_slice method. You can see the result of our efforts here: week1-ruby/day2.rb

I worked through the remaining exercises on the train home. One thing really caught me out, which is how Ruby is so eager to convert hashes to arrays when you iterate. For example:

> hash = {1 => 'one', 2 => 'two', 3 => 'three'}
=> {1=>"one", 2=>"two", 3=>"three"}
> hash.each {|part| puts part.inspect }
[1, "one"]
[2, "two"]
[3, "three"]

See that?! Surprise Array!

I had originally said that you can’t convert an array to a hash, but in a case like this you can, and to solve the tree initialization exercise i found i had to. Something like this:

> hash = {1 => 'one', 2 => 'two', 3 => 'three'}
=> {1=>"one", 2=>"two", 3=>"three"}
> hash.each {|part| puts ({part.first => part.last}).inspect }

My solution to the family tree exercise can be found here: week1-ruby/tree.rb

Finally, the find-in-file exercise. I really like this one. The book said the solution was simple, and my word, it truly is.'tree.rb').each_with_index do |line, line_number|
  puts "#{line_number}: #{line}" if line =~ /tree/

That’s it! So neat. I have always liked the application of the each method on a File. Here’s the output of the program:

$ ruby read_file.rb 
13:   def initialize_with_hash(tree)
14:     tree.each_pair do |name, children|
35: ruby_tree ='Ruby', ['Reia'),'MacRuby')])
38: ruby_tree.visit {|node| puts node.node_name }
41: puts 'Visiting entire tree'
42: ruby_tree.visit_all{|node| puts node.node_name }
44: family_tree ={'grandpa' => {
50: puts 'Visiting family tree'
51: family_tree.visit_all{|node| puts node.node_name }

Very neat! Although i’ve been programming in Ruby for a long time, i am appreciating its beauty and simplicity all the more tonight!


Since looking at Alberto’s excellent solutions and checking the Ruby Hash#each documentation, i now realise that the each method is supposed to take two elements in the block. For some reason i always thought you had to use each_pair for that. So there we go, talk about failing publicly! :)

Week 1 Day 1 – studying the basics of Ruby

Today i began the Seven Languages in Seven Weeks challenge. The first week is Ruby.

I know Ruby well so it wasn’t difficult for me. But to my great joy, my partner decided to study along with me, so i had the privilege of witnessing a newcomer’s approach to Ruby.

Together we learnt a bit about the syntax of Ruby: variables, conditions, loops, and a few of the things that make Ruby special, such as: Everything is an object, including numbers and even true and false. We then learned a bit about converting objects from one type to another, and duck typing: if it walks like a duck and quacks like a duck then it’s a duck.

I took a back-seat on the exercises and allowed my partner (who isn’t a programmer) to try out some ideas. I had to smile at the attempt to use a goto:

I said, “I can’t fault your logic – it’s perfect! But we don’t program like that anymore!”

You can see our final soution here: week1-ruby/day1.rb

As Stuart pointed out, we could also have used recursion … “But that’s going a bit too far, don’t you think?” (bonus points for a Mary Poppins reference?!)

How did everyone else get on today? In Ruby i feel qualified to answer questions about the language, so feel free to ask me. I’m certainly going to be needing to ask questions in later weeks!

Seven Languages kick-off

We had a skype call today to meet some of the people who are going to be studying Seven Languages in Seven Weeks together. Attending today were Daniel, Susan, Sarah, Matthew, Dirk and Matt. There are some people who couldn’t make it today and a few who have signed up since, so we’re going to have a similar skype call tomorrow (sunday) at 8pm BST.

We introduced ourselves and talked about our experiences and what we each want to get out of the seven weeks. We discussed briefly what we already know about the languages we’ll be studying.

We talked about tools we can use to encourage each other.

Susan has made a very useful git repository that we can fork and use to work in: There is a branch with all the examples from the book, and a branch where you can publish a blog to github pages. That might be a very good way to keep a record of your thoughts as we go.

Matt has set up a shared folder in Google Docs for us: 7 languages in 7 weeks. It is publicly viewable. I like learning in public. If you want write access, please tell me or Matt your google email address.

There is a twitter list of the people who have committed to studying: You can use that to get to find the people we’re studying along with.

It feels like there is a lot of excitement about the forthcoming seven weeks, and a lot of anticipation for what we’ll be learning. I was thrilled when i peeked ahead in the book and saw we’ll be using Prolog to solve a Sudoku! I can’t wait for that!

I’ll be blogging here a lot about what i’m learning. If you’re not studying with us, i hope you’ll still feel involved just by reading about it.

So, to all participants and followers … here’s to a great seven weeks! Have fun! :D

7 languages in 7 weeks

Thank you for all the response over twitter about studying Seven Languages in Seven Weeks. We are going to start a study group on monday. You can participate from anywhere in the world. Here’s how i think it could work.

My ideas

We should have a get-together over Skype each weekend (starting tomorrow if possible!) in which we discuss the coming language, any tips for installing, share any prior knowledge of the language. In later weeks we can also start discussing languages we’ve studied, compare and contrast them, and share how we feel about what we’ve learnt.

During the week there is text to read and exercises to study and try out. You should be responsible for your own studying. Being busy is not an excuse: if you really want to do this you’ll make time. Personally, my schedule is insanely busy next week. It would be very easy for me to put this off and say it’s not a good time. But if i do that, when will it ever be a good time? We have said we want to do this, so let’s do it!

Please blog a lot about what you’re learning. It will help provide discussion points for the weekend skype chat.

Tweet a lot. I have decided that the hashtag will be #7languages7weeks – it’s the shortest it can be while still being meaningful!

Get the book

If you haven’t yet bought the book, you need to do that straight away now! There is still time to buy it from Amazon and get it delivered on time, but HURRY!

If you want to get it for Kindle or other e-reader you can order it directly from Pragmatic Bookshelf choosing the eBook format.

Sign up now

I want to know who is serious about this, so please sign up here:

I propose we have a skype call at 13:00 British Summer Time tomorrow. If that doesn’t work for you, please let me know straight away and we’ll see what works better.

If you think any of my plans could be improved, tell me. Let’s iterate on this until we get something that really works well.

Talk to me on twitter @sermoa or add me on skype – also sermoa.

Hope to skype chat with you tomorrow! :)