Thursday, November 11, 2010

More fun with Io

One of Io's distinguishing features is an ability to extend its own syntax. Suppose that for some reason (for example to improve the readability of your code) you need unless keyword, similar to the one used in Ruby. You can define it as follows:
Object unless := method(if(call evalArgAt(0) not, call evalArgAt(1), call evalArgAt(2)))
That's it. You can now use a new keyword in your scripts:
Io> x := 15; unless(x < 10, "passed", "failed")
==> passed
Io> x := 5; unless(x < 10, "passed", "failed")
==> failed
In Common Lisp a similar effect can be achieved by using a macro like this:
(defmacro unless (condition &rest body) `(if (not ,condition) ,@body))
but in contrast to Common Lisp, Io does not use separate constructs to extend the language - what you can do in Lisp using macros, you can do in Io using only its own introspective features.

No comments: