#6245: make a custom infix operator decorator
-------------------------+--------------------------------------------------
Reporter: jason | Owner: cwitty
Type: enhancement | Status: new
Priority: major | Milestone: sage-4.0.2
Component: misc | Keywords:
Reviewer: | Author:
Merged: |
-------------------------+--------------------------------------------------
Changes (by jason):
* cc: cwitty, hivert (added)
Comment:
For reference, the code is:
{{{
class infix_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:
if self.left is None:
return infix_operator(self.function, left=left)
else:
raise SyntaxError, "Infix operator already has its left
argument"
else:
return self.function(left, self.right)
def __mul__(self, right):
if self.left is None:
if self.right is None:
return infix_operator(self.function, right=right)
else:
raise SyntaxError, "Infix operator already has its right
argument"
else:
return self.function(self.left, right)
}}}
And several examples (doctests?) are:
{{{
# This emul operator returns the element-wise product of two lists...
@infix_operator
def emul(a,b):
return [i*j for i,j in zip(a,b)]
a=[1,2,3]
b=[3,4,5]
# Returns [3,8,15]
a *emul* b
@infix_operator
def hadamard_product(a, b):
if a.nrows()!=b.nrows() or a.ncols()!=b.ncols():
raise ValueError, "Matrices must have the same dimensions in a
Hadamard product"
return matrix(a.nrows(), a.ncols(), [x*y for x, y in zip(a.list(),
b.list())])
A=random_matrix(ZZ,3)
B=random_matrix(ZZ,3)
A *hadamard_product* B
}}}
--
Ticket URL: <http://trac.sagemath.org/sage_trac/ticket/6245#comment:1>
Sage <http://sagemath.org/>
Sage: Creating a Viable Open Source Alternative to Magma, Maple, Mathematica,
and MATLAB
--~--~---------~--~----~------------~-------~--~----~
You received this message because you are subscribed to the Google Groups
"sage-trac" group.
To post to this group, send email to [email protected]
To unsubscribe from this group, send email to
[email protected]
For more options, visit this group at
http://groups.google.com/group/sage-trac?hl=en
-~----------~----~----~----~------~----~------~--~---