faqts : Computers : Programming : Languages : Python : Snippets

+ Search
Add Entry AlertManage Folder Edit Entry Add page to http://del.icio.us/
Did You Find This Entry Useful?

2 of 3 people (67%) answered Yes
Recently 1 of 1 people (100%) answered Yes

Entry

"listable" functions

Jul 5th, 2000 10:01
Nathan Wallace, Hans Nowak, Snippet 213, Michael Vanier


"""
Packages: basic_datatypes.lists;functional_programming
"""
"""
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
"""
#! /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 -------------------------