Carl Witty wrote:
> On Sat, Mar 28, 2009 at 5:28 AM, Jason Grout
> <jason-s...@creativetrax.com> wrote:
>> Aha, the one custom infix operator that I know of in Sage.
>>
>> In the backslash operator and in the article posted, the rmul only
>> stored the argument and the __mul__ only performed the operation.  Are
>> you always guaranteed that __rmul__ will be called right before __mul__
>> for the same invocation of the operation?
> 
> Hmm... probably not.  Consider
>   A *emul* (B *emul* C)
> Since multiplication is left-associative, this is:
>   (A*emul)*((B*emul)*C)
> 
> This is probably (I don't know if Python guarantees left-to-right
> evaluation, but I'm guessing it does) evaluated in this order:
> 
> t1 = A*emul
> t2 = B*emul
> t3 = t2*C
> t4 = t1*t3
> 
> So for safe general-purpose use, A*emul needs to return a new object.
> 

Okay, how about this:

class inline_operator:
     def __init__(self, function, left=None, right=None):
         self.function = function
         self.left = left
         self.right = right

     def __rmul__(self, left):
         if self.right is None:
             return inline_operator(self.function, left=left)
         else:
             return self.function(left, self.right)

     def __mul__(self, right):
         if self.left is None:
             return inline_operator(self.function, right=right)
         else:
             return self.function(self.left, right)


# EXAMPLE

a=[1,2,3]
b=[3,4,5]

@inline_operator
def emul(a,b):
     return [i*j for i,j in zip(a,b)]

# Returns [3,8,15]
a *emul* b


Jason


--~--~---------~--~----~------------~-------~--~----~
To post to this group, send email to sage-devel@googlegroups.com
To unsubscribe from this group, send email to 
sage-devel-unsubscr...@googlegroups.com
For more options, visit this group at http://groups.google.com/group/sage-devel
URLs: http://www.sagemath.org
-~----------~----~----~----~------~----~------~--~---

Reply via email to