[Python-ideas] Infix application of binary functions (original) (raw)

Carl M. Johnson cmjohnson.mailinglist at gmail.com
Thu Jul 22 06:22:58 CEST 2010


Last time, I swear! I caught a bug in the last version. Since I mutated my instances (not very Haskell-like!!), you couldn’t use the same function more than once. Here’s a new version that lets you use the same function again:

class InfixArity(object): def init(self, arity): self.arity = arity

def __call__(self, func):
    self.func = func
    return self

def __add__(self, arg):
    return InfixHelper(self.func, self.arity, arg)

__radd__ = __add__
__floordiv__ = __rfloordiv__ = __add__
__truediv__ = __rtruediv__ = __add__

class InfixHelper(object): def init(self, func, arity, firstarg): self.func = func self.arity = arity self.args = [firstarg]

def __add__(self, arg):
    self.args.append(arg)
    if len(self.args) < self.arity:
        return self
    else:
        return self.func(*self.args)

__radd__ = __add__
__floordiv__ = __rfloordiv__ = __add__
__truediv__ = __rtruediv__ = __add__

Infix = lambda func: InfixArity(2)(func)

I imagine it would be possible to make an n-arity class that could work like “average // 1 // 2 // 3 // 4 // done” or maybe one that has you use a different operator for the last argument, but I leave that as an exercise for the reader.

-- Carl Johnson

On Wed, Jul 21, 2010 at 5:49 PM, Carl M. Johnson <cmjohnson.mailinglist at gmail.com> wrote:

Thought about it some more. Here’s a more general formula:

class InfixArity(object):  def init(self, arity):  self.arity = arity  self.args = []

 def call(self, func):  self.func = func  return self  def add(self, arg):  self.args.append(arg)  if len(self.args) < self.arity:  return self  else:  return self.func(*self.args)  radd_ = _add Infix = lambda func: InfixArity(2)(func) And of course, one can use mul or div or whatever to taste. "1 // add // 2” doesn’t make me instantly vomit in my mouth. ;-) -- Carl Johnson



More information about the Python-ideas mailing list