I'm reading through Seven Programming Languages in Seven Weeks, and one of the problems states:
How would you change /
to return 0
if the denominator is zero?
I first tried defining my own /
and proxying its implementation to the original /
method like this:
Number oldSlash := Number getSlot("/")
Number / = method(x, Number oldSlash(x))
However that was not working for me. After doing some Googling I found a similar piece of code. The code I found was using self
in the implementation of the method. So, I tried using self
and it seemed to work just fine:
Number oldSlash := Number getSlot("/")
Number / = method(x, self oldSlash(x))
My question is: Why does this work when the keyword self
is used, and why does it not work when Number
is used instead?
The short version:
Number
is a "base class" for numbers; not an actual numerical value. You can't use it for mathematical operations.self
represents the object your method was invoked on, which turns out to be the number you want to use as numerator in your division.The longer version:
First, some background: Division as you know takes two arguments. The method you're defining only takes one argument (the
x
). The other argument is implicit and it's the Number you're invoking the division on. To make it crystal clear, when you're writinga / b
the method/
is invoked on the objecta
and it gets passed the valueb
as parameter. In a more C-like language, you'd say something likea.divide(b)
. You don't passa
as a parameter, but it is accessible from the function anyway, asself
.So, using what we know from above, writing
self oldSlash(x)
performs division usingself
as numerator andx
as denominator. The value ofself
is set when your "newSlash" method is called, once again implicitly to the object you're calling the method on. If you're familiar with JavaScript,self
is Io's name forthis
.When instead you write
Number oldSlash(x)
you use the objectNumber
as the numerator in the division.Number
is not an actual number, but rather the "base class" for all numbers. It does not have a value. Hence you cannot perform mathematical operations on it.