Skip to content

Empty Message Dasgn

vic edited this page Sep 14, 2010 · 1 revision

Destructuring Assigment and the Empty Messageempty_message_dasgn

Since Ola added support for destructuring assignment in ioke, it is possible to write things like:

(a, b, c) = (1, 2, 3)

The = method assigns each object from the tuple1 on the right2 to the corresponding name on the tuple of the left side.

So if we had a Person kind like:


  Person = Origin mimic
  Person initialize = method(name, age, occupation, 
     @name = name
     @age = age
     @occupation = occupation
  )

we can rewrite the initialize method using destructuring assignment like so (changed @ for self as I think it’s a bit more communicative about what are we doing):


  Person initialize = method(name, age, occupation, 
     self (name, age, occupation) = (name, age, occupation)
  )

That’s really nice and clean. Now consider the following code:


(a, b, c) = [1, 2, 3]
ary = list(4)
ary ([3], [2], [1]) = (a, b, c)

Note that in the last line, the left tuple elements ([3],[2],[1]) are not names but places in the ary object where ioke will perform assignment. As you can expect, the final value of ary is: [4, 3, 2, 1]

Now, based on the fact that we assigned three elements with ary ([3], [2], [1]) = (a, b, c), I’d like to extract them in a simetric way, I mean, by activating the empty message on ary:


(x,y,z) = ary ([1], [2], [3])
x should == 3
y should == 2
z should == 1

In mainstream ioke, this doesn’t work and assigns a new array to each element on the left tuple, which seems counterintuitive to me:
x = [1], y = [2], z = [3]

What I wanted is a way to create a tuple from a given object, (in this case the ary object).

The empty_message_dasgn branch implements this, by letting the empty message work as it did before, but evaluating its elements on the reciver if invoked explicitly on one. In the following example, when you send the empty message to the x object, it will create a tuple from evaling its arguments on x:


a = 1
c = 3
(a, 2, c)   =>   (1, 2, 3)

x = [a, 2, c]
x (length, last) => (3, 3)
x (a, 2, c)  => Error, no such cell 'a' on 'x'

1 Tuples can be created by invoking the Empty Message with more than one arguments. Be sure to have an space before the braces, otherwise you will be activating another method instead of the empty message:

Person mimic(:daniel, 10, :gaming) ☜ Activates the mimic method of Person, giving it three arguments.
Person mimic (:daniel, 10, :gaming) ☜ Activates the empty message with three arguments on the result of calling Person mimic

2 Actually destructured assignment can take any object on the right hand side that responds to the asTuple method

Clone this wiki locally