python hack of the day -- "listable" functions

Michael Vanier mvanier at bbb.caltech.edu
Wed May 12 19:30:34 EDT 1999


Having nothing better to do one day, I whipped up a quick class that
transforms functions into "listable" functions i.e. functions that
automatically map themselves over a sequence.  The idea was stolen from
Mathematica, but it's amazing how easy it is to implement this in python.

Function-objects--is-there-anything-they-can't-do?-ly y'rs,

Mike

-------------------------------------------------------------------------
Mike Vanier	mvanier at bbb.caltech.edu
Department of Computation and Neural Systems, Caltech 216-76
Will optimize nonlinear functions with complex parameter spaces for food.


------------------------- Python code follows -------------------------
#! /usr/bin/env python
# -*- python -*-
#
# listable.py: convert functions to "listable" functions, which
#              are functions which automatically map themselves
#              over a sequence.  This idea is borrowed from
#              Mathematica.
#

class listable:
    """Make a function into a listable function."""
    
    def __init__(self, f):
        self.func  = f

    def __call__(self, *args):
        # Argument cases.
        # Is first argument a sequence?  If so, assume they
        # all are; otherwise wrap them in a tuple.
        try:
            first = args[0][0] # OK if it's a sequence
        except TypeError: # Not subscriptable; not a sequence.
            # Make args into a tuple:
            args = (args,)

        # Construct a tuple for the argument list.  It must have
        # the form: (func, <sequence>).
        arglist = (self.func,) + args
        result = apply(map, arglist)

        # Return the results; a sequence if there's more than one,
        # else a scalar.
        if len(result) == 1:
            return result[0]
        else:
            return result


if __name__ == '__main__':
    from math import sin
    Sin = listable(sin)
    print "sin(1.3) = %g" % sin(1.3)
    print "Sin(1.3) = %g" % Sin(1.3)
    print "Sin([1.3, 1.4, 1.5]) = %s" % Sin([1.3, 1.4, 1.5])
    # You can leave out the square brackets if it's all one sequence:
    print "Sin(1.3, 1.4, 1.5) = %s" % Sin(1.3, 1.4, 1.5)
# ----------------------- Python code ends here -------------------------







More information about the Python-list mailing list