[Edu-sig] @ for "complicated multiplication"

kirby urner kirby.urner at gmail.com
Thu Jun 2 11:29:02 EDT 2016


Thanks to Guido's keynote at Portland Pycon 2016,
I finally absorbed that @ had joined the ranks of
overloadable operators.

In reading up on the history of complex numbers
and such, and group theory especially (also
referenced by Guido in his keynote), I've found
how mathematicians exulted to discover that
multiplication could be so complex with such
encapsulated objects as matrices and quaternions.

A breakthrough.

In a way, they discovered object oriented programming
and operator overloading, or at least prefigured it.
Objects of complicated state (a matrix of 3 x 3 objects)
could come with their own behaviors when "multiplied".
Thanks to ideas about "inverse" and "identity", a certain
"design pattern" would hold.

Using this new operator @ to signify the more generic
forms of multiplication that go with abstract algebra,
makes sense.  We're thinking of @ in place of what
many texts use:  a little circle.

This new feature would suggest reworking the
curriculum around a Composable type to work with
@ instead of * (I might do that with Permutation
too).

Like this:

# -*- coding: utf-8 -*-
"""
Created on Thu Jun  2 08:02:28 2016

@author: K. Urner
(c) MIT License
"""

class Composer:

    def __init__(self, f):
        self.f = f

    def __call__(self, var):
        return self.f(var)

    def __matmul__(self, other):
        # "complicated multiplication"
        return Composer(lambda var: self.f(other.f(var)))

    def __repr__(self):
        return "Composer({}) at {}".format(id(self.f), id(self))

# demo
import math

def F(x):
    return 2*x + 2

def G(x):
    return math.sqrt(x)

f = Composer(F)
g = Composer(G)

h = f @ g
r = h(10)

try:
    assert f(g(10)) == h(10)  # <-- whistle blower
    print('(f @ g)(%s) = %s' % (10, r))
except AssertionError:        # <-- referee
    print("f @ g failed to meet expectations, sire")

h = g @ f
r = h(10)

try:
    assert g(f(10)) == h(10)  # <--- Quality & Assurance
    print('(g @ f)(%s) = %s' % (10, r))
except AssertionError:        # <-- provide feedback
    print("g @ f failed to meet expectations, sire")





 # Kirby
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/edu-sig/attachments/20160602/6a7bcaf5/attachment.html>


More information about the Edu-sig mailing list