dictionary of operators

R

rbossy

Hi,

In the standard library module "operator", it would be nice to have a dictionary
mapping operators strings with their respective functions. Something like:

{
'+': add,
'-': sub,
'in': contains,
'and': and_,
'or': or_,
...
}



Rationale:

Recently I had to implement a small language interpreter and I ended up building
such a dictionary. Indeed the parser (I used PLY then pybison) returned an AST,
where all arithmetic were represented by a single node type, like this:

class Arithmetic(Expression):
def __init__(self, op, lft, rgt):
self.op = op
self.lft = lft
self.rgt = rgt

def eval(self, scope):
return self.op(self.lft.eval(scope), self.rgt.eval(scope))

The dictionary allowed the parser to have a single rule action like this:

Arithmetic(opstr[term[1]], term[0], term[2])



Does such a dictionary already exist? Is it really a good and useful idea?

Thanks,
RB
 
A

A.T.Hofkamp

Hi,

In the standard library module "operator", it would be nice to have a dictionary
mapping operators strings with their respective functions. Something like:

{
'+': add,
'-': sub,
'in': contains,
'and': and_,
'or': or_,
...
}

Does such a dictionary already exist? Is it really a good and useful idea?

How would you handle changes in operator syntax?
- I have 'add' instead of '+'
- I have U+2208 instead of 'in'

I don't think this is generally applicable.


Why don't you attach the function to the +/-/in/... token instead? Then you
don't need the above table at all.


sincerely,
Albert
 
R

Robert Bossy

A.T.Hofkamp said:
How would you handle changes in operator syntax?
- I have 'add' instead of '+'
- I have U+2208 instead of 'in'
Originally I meant only the Python syntax which shouldn't change that
much. For some operators (arith, comparison) the toy language had the
same syntax as Python.
Btw, U+2208 would be a wonderful token... if only it was on standard
keyboards.
I don't think this is generally applicable.
Thinking about it, I think it is not really applicable. Mainly because
my examples were exclusively binary operators. What would be for unary
operators? Or enclosing operators (getitem)?
Why don't you attach the function to the +/-/in/... token instead? Then you
don't need the above table at all.
Could be. But I prefer settling the semantic parts the furthest possible
from the lexer. Not that I have strong arguments for that, it's religious.

Anyway, thanks for answering,
RB
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,770
Messages
2,569,583
Members
45,074
Latest member
StanleyFra

Latest Threads

Top