Ask Your Question
0

Delayed evaluation without all the parenthesis?

asked 2011-11-10 04:28:18 +0200

Alister gravatar image

updated 2011-11-10 16:04:02 +0200

Is there a way to have delayed evaluation without having unnecessary parenthesis. For example,

(x.add(x, hold = True)).add(x, hold = True)

gives

(x + x) + x

not

x + x + x

Thanks

EDIT:

Great answer burcin! I was hoping to be able to it in more of a binary way though, so that I could use the Infix hack from http://code.activestate.com/recipes/3....

I wanted to make a binary operator which is still delayed. Defined here

class Infix(object):
    def __init__(self, function):
        self.function = function
    def __ror__(self, other):
        return Infix(lambda x: self.function(other, x))
    def __or__(self, other):
        return self.function(other)

p=Infix(lambda x,y: x.add(y, hold=True))

Usage is

x |p| x |p| x
edit retag flag offensive close merge delete

2 Answers

Sort by ยป oldest newest most voted
2

answered 2011-11-10 08:12:47 +0200

Is this what you need?

sage: x.add(x,x,hold=True)
x + x + x
edit flag offensive delete link more
0

answered 2011-11-10 18:05:50 +0200

Jason Grout gravatar image

Sage already has an infix_operator decorator:

sage: @infix_operator('or')
....: def f(x,y): return x.add(y, hold=True)
....: 
sage: x |f| x |f| x
(x + x) + x

See http://sagemath.org/doc/reference/sag...

edit flag offensive delete link more

Comments

Nice! But that still leaves some unnecessary parenthesis.

Alister gravatar imageAlister ( 2011-11-10 19:09:30 +0200 )edit

Does your infix operator not have the parentheses? The parentheses are showing exactly what you typed, using order of operations, using a *binary* addition operator.

Jason Grout gravatar imageJason Grout ( 2011-11-10 19:49:41 +0200 )edit

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account.

Add Answer

Question Tools

Stats

Asked: 2011-11-10 04:28:18 +0200

Seen: 408 times

Last updated: Nov 10 '11