Hack request: rational numbers

Pearu Peterson pearu at ioc.ee
Thu Jan 25 14:55:15 EST 2001


> "Pearu Peterson" <pearu at cens.ioc.ee> wrote in message
> news:Pine.LNX.4.21.0101251759070.28148-100000 at kev.ioc.ee...
>     [snip]
> > Python. Closest to the above representation I find
> >
> >     3r/4
> >
> > that uses similar syntax as in constructing Python complex numbers
> > (cf. 3j+4).
> 
> What about r('3/4')?  Doesn't seem all that far off.  Or
> r(3)/4.  These are easy, and just 2 characters (the parentheses)
> away from your dream-syntax.

(
Personally, I find parentheses always difficult to type: I have used to
type first opening and closing parenthesis, then arrow left, and finally
the contents. For example, for typing `r(3)', I would press
	[r] [(] [)] [<] [3]
that makes 5 keystrokes (plus holding down the [shift] key) for something
that could have been inserted only with 2 keystrokes: [3] [r].
That's my personal convention, ignore it if you don't like it ;)
)

> But there may be something better...
> 
> r3/4 would work if your module could have a __getattr__ (and if
> you could reserve in your modules all variables of the form 'r\d+'),
> as would 3/r4.  I suspect you stand a slightly better chance to
> get some form of __getattr__ (and __setattr__) into modules, 

I would not like that: that makes infinitely many reserved names.

But your suggestions have made me come up with the following *working*
solution:

>>> from gmpy import *
>>> R = mpq(1)          # generator of rational numbers
>>> R*3/4
mpq(3,4)

that is, only one (capital or not) reserved name is needed!

Though, I would prefer that

>>> 3r
  File "<stdin>", line 1
    3r
     ^
SyntaxError: invalid syntax

would do something useful;) I think that my suggestion (in my previous
mail) will not break any existing Python code, it just extends Python
syntax. But that's up to whether such an extension is interesting to you.

Thanks,
	Pearu




More information about the Python-list mailing list