Rick DeNatale | 15 May 13:39

Re: Singleton methods on Float and Bignum

On Thu, May 15, 2008 at 5:24 AM, Matthias Wächter
<matthias <at> waechter.wiz.at> wrote:
> On 5/15/2008 5:33 AM, Joel VanderWerf wrote:
>>
>> x = 1.0
>> def x.foo; end
>> (1.0).foo   # what should happen here?
>
> x="abc"
> def x.foo; end
> "abc".foo     # what should happen here?
>
> I don't see your point. You can create new objects in various ways, while
> Strings and Floats just make it easier for you. I don't even see why there
> is no special built-in type of Fixnum (and nil/true/false) is available that
> can easily be passed by reference, just for convenience, which would allow
> applying singletons as well.

I, on the other hand, have a hard time seeing a motivating use case.
Consider this admittedly contrived example:

bignum = 1073741824
def  1073741824.to_s
   "Found me!"
end

What should happen here:

  puts bignum + 0

  puts  32768 * 32768

I daresay that most would be surprised that although 1 is always 1,
and 10 is always 10, but 1073741824 isn't always 1073741824.

My point is that we tend to think of numerics primarily in term of
their value rather than there identity, and singleton classes are tied
to the identity of the object.  Now perhaps, if we really wanted to
attach singleton methods to numerics the ruby implementation could do
things like:

    1) Use a lookup table to find the 'singleton' class for Fixnum
instances and other objects with immediate representation, similar to
the way instance variables for immediate objects are implemented (at
least in MRI, don't know how other implementations do that).  It's
hard to see how this would work without a significant cost. The table
would need to be searched first every time a method was dispatched to
an immediate object before searching the class chain. Should:

       def 42.+(i)
           42
       end

be allowed?  Regardless of the effect on results, what would this mean
for implementations like YARV which now do optimization of operations
like addition which get significant performance by bypassing method
lookup in the common case of adding two objects which happen to both
be Fixnums?

    2) Intern Bignums (and Floats?) so that there's only one instance
of  1073741824, just like there's only one instance of  1073741823
(this example is on an implementation where the boundary between
Fixnums and Bignums is 2**30).  The notion of interning Floats is a
little squirrelly since the 'value' of a float is fuzzy by definition.

I'd argue that the utility of adding singleton methods to Numerics
doesn't rise to the cost of implementing that ability.  If an
application really needs something like that, better for it to build a
class or classes which 'box' the numerics and contain the cost to
where it's really needed.

--

-- 
Rick DeNatale

My blog on Ruby
http://talklikeaduck.denhaven2.com/


Gmane