[Tutor] Re: Re: Python vs. Ruby

Andrei project5 at redrival.net
Fri Oct 31 05:36:59 EST 2003


Gregor Lingl wrote on Fri, 31 Oct 2003 01:20:35 +0100:

<snip>
> at least this last example is not so much different from Python:
> 
>  >>> 5.0.__add__(3)
> 8.0
>  >>>

Actually, my original intention was to use 5.+ 3 in Ruby, since this
doesn't seem to work in Python. 5.0.+ was more illustrative since 5.+ 3
returning 8 could be interpreted as Ruby being 'smart' and returning an
integer when adding a float and an integer :).

>>> 5.__add__(3)
  File "<input>", line 1
    5.__add__(3)
            ^
SyntaxError: invalid syntax
>>> int(5).__add__(3)
8

> which shows that in Python + also is only some sort of syntactical
> sugar.

class Tt
  def initialize(val)
    @val = val
  end
  def +(newval)
    @val + newval +1
  end
end
x = Tt.new(5)
x + 2
- - - - - - - - - - - - - - - 
=> 8

When was the last time you named a method "+" in Python? :) But it does
indeed show that the differences between the languages are mostly
skin-deep, since you can achieve the same in Python. It's just that you
can't call it "+".

> Testtask: is it possible to subclass (numerical)  functions - say this
> new class is named Fun - e.g. by adding a __add__ method, in a
> way that their instances can be added, like:
>  >>> from math import sin, cos
>  >>> f = Fun(sin) + Fun(cos)   ### see remark below
>  >>> f(1)
> #### should output sin(1)+cos(1)

from math import *

class Fun:
    def __init__(self, *funcs):
        self.funcs = []
        self.funcs.extend(funcs)
    def __add__(self, func):
        self.funcs.extend(func.funcs)
        return Fun(*self.funcs)
    def __call__(self, *args):
        results = [ f(*args) for f in self.funcs ]
        return sum(results)
        
f = Fun(sin) + Fun(cos)
for i in range(1000):
    if f(i) != sin(i)+cos(i):
        print "Error @",i

> Is a task of this sort more easily ( and/or more
> in accordance with the philosophy of the language)
> solvable in Ruby?

I figured it out in Python, but I don't know enough Ruby to do it off-hand.
But I'll bet it's possible.

-- 
Yours,

Andrei

=====
Mail address in header catches spam. Real contact info (decode with rot13):
cebwrpg5 at bcrenznvy.pbz. Fcnz-serr! Cyrnfr qb abg hfr va choyvp cbfgf. V
ernq gur yvfg, fb gurer'f ab arrq gb PP.




More information about the Tutor mailing list