On 2013-Apr-15, at 05:20 , Robert K. wrote:
I prefer to look at this on the language level and not the MRI implementation
(even though they are closely related). On the language level the optimization is
invisible and hence irrelevant for the reasoning here. The reason for the absence
of an increment operator is that there was a design decision to make numbers
immutable (at least with regard to their numeric value). If instances of a type
are immutable their state will never change - hence you cannot change them from
representing 1 to 2 etc.
Having said that, “++a” could be made syntactic sugar for “a+=1” but that would
not work if a was referencing a String even though String#+ is defined. The only
way out of this would be to make “++a” syntactic sugar for something like
“a+=a.class.one” where Integer would implement “one” as “return 1”. But what
would String.one return then?
Kind regards
robert
–
remember.guy do |as, often| as.you_can - without end
http://blog.rubybestpractices.com/
Why wouldn’t the syntactic sugar for ++a be a=a.succ (for “successor”)
since that is defined on more types? From the PIckaxe:
So far weve shown ranges of numbers and strings. However, as youd expect
from an object- oriented language, Ruby can create ranges based on
objects that you define. The only constraints are that the objects must
respond to succ by returning the next object in sequence and the objects
must be comparable using <=>.
– Programming Ruby 1.9 & 2.0, p. 93, Ch.6 Standard Types
irb2.0.0> a = 1
#2.0.0 => 1
irb2.0.0> a.succ
#2.0.0 => 2
irb2.0.0> a = “hello”
#2.0.0 => “hello”
irb2.0.0> a.succ
#2.0.0 => “hellp”
For String, which does have mutable instances, there’s also #succ! to
change the object itself.
irb2.0.0> a
#2.0.0 => “hello”
irb2.0.0> a = “hello”
#2.0.0 => “hello”
irb2.0.0> a.succ
#2.0.0 => “hellp”
irb2.0.0> a
#2.0.0 => “hello”
irb2.0.0> a.succ!
#2.0.0 => “hellp”
irb2.0.0> a
#2.0.0 => “hellp”
for --a you could use a=a.pred (for “predecessor”), but that’s only
defined on Integer (and had no built-in use like #succ does).
irb2.0.0> a = 1
#2.0.0 => 1
irb2.0.0> a.pred
#2.0.0 => 0
irb2.0.0> a.pred
NoMethodError: undefined method pred' for "hello":String from (irb):5 from /Users/rab/.rbenv/versions/2.0.0-p0/bin/irb:12:in
’
From my Wayback Machine, about 25 years ago the company I worked for had
an internally developed C compiler (yes, back in the stone age before C
was even a standard language and gcc was that weird, free compiler) that
actually did define ++ and – for doubles (floating point numbers) as
a+=1.0 and a-=1.0 for just this reason.
-Rob