On Thursday, July 17, 2014 10:35:32 PM UTC-7, Robert Bradshaw wrote: > I'm not sure multimethods alone are enough to solve issues with Sage's > type system (e.g. coercion, where the result of a+b may happen in a > completely new domain) but they could certainly help. >
Indeed. If you want multiple dispatch in python you can have it: class multi_dispatch(object): def __init__(self): self.dispatch = [] def register_function(self,signature,function): self.dispatch.append( (signature,function) ) def register(self,*signature): def register_decorator(function): self.register_function(signature,function) return function return register_decorator def __call__(self,*args): for sig in self.dispatch: if len(args) == len(sig) and all(isinstance(a,b) for a,b in zip( args,sig[0])): return sig[1](*args) raise TypeError("Signature not implemented") With this it is now quite straightforward to write multiple dispatch at the cost of using a decorator: T = multi_dispatch() @T.register(int,int) def int_int(a,b): return "called with integers (%d,%d)"%(a,b) @T.register(int,float) def int_float(a,b): return "called with integer and float (%d,%f)"%(a,b) @T.register(float,float) def float_float(a,b): return "called with floats (%f,%f)"%(a,b) You can then just call T: >>> T(1,2) 'called with integers (1,2)' >>> T(1,2.0) 'called with integer and float (1,2.000000)' >>> T(1.0,2.0) 'called with floats (1.000000,2.000000)' >>> T(1.0,2) Traceback (most recent call last): File "<stdin>", line 1, in <module> File "dispatch.py", line 15, in __call__ raise TypeError("Signature not implemented") TypeError: Signature not implemented The key is in optimizing the signature lookup (and the kind of lookup can definitely be refined a *lot* in the above implementation--linear search by registration order is probably not optimal) and finding a useful way of describing signatures and properly prioritizing which signature should get precedence (if you think C3 is complicated for multiple inheritance, brace yourself for multiple dispatch). In a dynamically typed language, multiple dispatch has a rather high cost. LISP MOP implementations have a lot of experience. In the end it's just a little helper tool, though. It doesn't really do things you can't otherwise do. -- You received this message because you are subscribed to the Google Groups "sage-devel" group. To unsubscribe from this group and stop receiving emails from it, send an email to sage-devel+unsubscr...@googlegroups.com. To post to this group, send email to sage-devel@googlegroups.com. Visit this group at http://groups.google.com/group/sage-devel. For more options, visit https://groups.google.com/d/optout.