Tuesday, September 27, 2005

Dynamic Programming

Magik gives you the ability to call methods without knowing the name of the method at compile time. It does this via the perform method. With the perform method, which is defined on object and can therefore be sent to any type of object, takes a symbol as the first argument. This symbol is the name of the method to call. Any subsequent arguments to the perform method are passed to the invoked method. Here's an example:

MagikSF> r << rope.new()
$
sw:rope:[1-0]
MagikSF> r.add("hi")
$
"hi"
MagikSF> r.perform(:size)
$
1

You can do this with any type of method, including the square brackets method, as long as you create the symbol correctly with the vertical bars:

MagikSF> r.perform(:|[]|, 1)
$
"hi"

And you can even use the setter method:

MagikSF> r.perform(:|[]<<|, "joe", 1)
$
"joe"

MagikSF> r[1]
$
"joe"

Notice the strange order of the arguments to this method. I would have thought the index would have been the first argument, but it's not.

So, we can build up calls to objects by creating strings and then sending them as method names (really messages) to the object. What if we want to send a message to an exemplar where name of the exemplar is derived dynamically? To do this you use the square bracket method on the package containing the exemplar. Here's an example:

MagikSF> !current_package![:rope]
$
sw:rope:[1-1]

This stuff isn't used that much, but it can come in handy.

0 Comments:

Post a Comment

<< Home