# Io Day 3

My experience with day three of exploring Io through Seven Languages in Seven Weeks.

The final day of Io ramps things up and looks at how it supports metaprogramming and concurrency.

## Creating a DSL

The first example in the book demonstratea how powerful Io can be in terms of helping us to create a DSL by allowing us to redefine operators, symbols etc.

Say we had a list of phone numbers represented in the following format

We could use the following code to generate a hash from it.

Io allows us to define our own operators so we’ve added an operator “:” which when encountered is parsed as the atPutNumber method. The first argument will be treated as the hash key, the second its value. We define a CurlyBrackets method which is called when the parser encounters {}. It creates an empty map and then iterates through the numbers in the list. For each name and phone number it calls r doMessage(arg). So for the first pairing it will execute

"Jane Smith": "07891234112" The : is then translated as atPutNumber

r atPutNumber("Jane Smith", "07891234112")

The atPutNumber take the name and strips the quotes and adds the phone number to the hash using the name as the key.

## Forward Message

Next the book looks at Io’s forward message which is similar to Ruby’s method_missing. The example shows how you can represent XML data as Io code.

In the example we’ve overridden the forward method. When an unrecognised method is received our method gets called. It creates an open tag with the method name. It then looks at the arguments and they are string it prints it without quotes. If it is another method call it creates an open tag for it and repeats the process. Finally it prints a closing tag.

## Concurrency

One of the major positives for Io is its great concurrency libraries.

The @ and @@ fire a message asynchronously. Yield voluntarily suspends a process and transfers to another process. The talk and rhyme methods run concurrently yielding to each other at specified intervals. This is useful for solutions requiring cooperative multitasking.

## Futures

If you fire a message asynchronously using @ it returns a result object called a future. This is the value of the last statement returned. If you ask for the value before it is available the process blocks until it is ready. Futures provide automatic deadlock detection and raise an exception.

## Do:

Enhance the XML program to add spaces to show the indentation structure.

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({“author”: “Tate”}…) would print <book author="Tate">

Check out my code at github