[Tutor] Apply()

Danny Yoo dyoo@hkn.eecs.berkeley.edu
Thu Feb 6 02:46:02 2003


On Wed, 5 Feb 2003, Erik Price wrote:

> > Instead of a series of if ... elif statements you use apply to "apply"
> > the chosen function to the arguments.
>
> That's nifty ... thanks for explaining.  But I don't see it in the index
> of the Python docs on the web site.  Is that something that isn't in
> Python yet, or... ?


Hi Eric,


Ok, found it!  Here you go:

    http://www.python.org/doc/lib/built-in-funcs.html#l2h-4

apply() is one of those functions that you might see in a lot of
functional programming, but it's not as common in Python because there's
an alternative syntax for it.


Rather than explain it, here's an example that shows it.  *grin*

###
>>> def add(*args):
...     sum = 0
...     for num in args:
...         sum = sum + num
...     return sum
...
>>> def neg(x):
...     return -x
...
>>> import sys
>>> cmds = { 'add' : add,
...          'neg' : neg,
...          'quit' : sys.exit }
>>> def loop():
...     while 1:
...         statement = raw_input("> ")
...         (c, rest) = (statement.split()[0],
...                      map(float, statement.split()[1:]))
...         print cmds[c](*rest)
...
>>> loop()
> add 3 4 5 6 7 8 9 10
52.0
> neg 42
-42.0
> quit 0
0.0
###



The part that would normally involve 'apply()' is the line:

    print cmds[c](*rest)


With apply(), that might look like:

    print apply(cmds[c], rest)



Hope this helps!