Robert Klemme wrote:
>> Operators in Ruby are nothing more than syntactic sugar for method 
>> calls.
> 
> Well, in a way that's what they are in every procedural language - they
> are just a special notation for a method / function invocation, aren't
> they?

I don't think so. Well, not in C anyway. The operation "a + b" is 
defined to be an operation on a and b (e.g. integer addition or float 
addition). It is not defined as a function call, and it cannot be 
changed by the user.

The same applies to Perl I think.

In Ruby, + is not defined in terms of its operation (i.e. what it does 
with the arguments), but just that it dispatches to a method on the 
left-hand argument. They really are syntactic sugar, since they parse to 
exactly the same as the explicit method call syntax:

$ cat add1.rb
1 + 2 * 3
$ cat add2.rb
1.+(2.*(3))
$ parse_tree_show add1.rb
s(:call,
 s(:lit, 1),
 :+,
 s(:array, s(:call, s(:lit, 2), :*, s(:array, s(:lit, 3)))))
$ parse_tree_show add2.rb
s(:call,
 s(:lit, 1),
 :+,
 s(:array, s(:call, s(:lit, 2), :*, s(:array, s(:lit, 3)))))

Now, in principle a C compiler could be written such that a+b is 
rewritten at the parsing stage to cc_int_add(a,b) or somesuch. But this 
wouldn't be a function like a user-written one. For a start, it would 
have to generate machine code or some intermediate VM code directly, 
since there is no primitive '+' operator to use. Secondly, it would need 
to be able to handle arguments in different combinations of registers, 
so that an expression like cc_int_add(a, cc_int_mul(b,c)) doesn't spill 
registers everywhere.

So cc_int_add() might *look* like a function, but actually it would be a 
special node type which generates addition code. In that case, the parse 
tree may as well remember that it's a "+" operator with two arguments, 
since converting it to something which looks like a function call (but 
isn't) doesn't help at all.

Regards,

Brian.
-- 
Posted via http://www.ruby-forum.com/.