[Tutor] apply()

Danny Yoo dyoo@hkn.eecs.berkeley.edu
Wed, 24 Jan 2001 13:58:11 -0800 (PST)


On Wed, 24 Jan 2001, kevin parks wrote:

> I don't really understand when to use apply, when it is needed or
> useful. Can anyone think of a good example of when to use apply or a
> task that requires it. For some strange reason i can't seem to get my
> head around it and what it is used for.

To tell the truth, I haven't used apply() too often myself.  apply()'s
used in code that's very dynamic in nature (for example, interpreters), so
examples that use it are usually complicated.  I'm trying to think of an
interesting program that could naturally use apply.  Hmmm.

Let's say we want to make a small calculator program.  I'll pretend that
it works already, and give a brief "simulation" of how I think it would
work:

###
square 5
25

add 4 7
Result: 11

quit
bye
###

So this calculator will make it easy to play around with functions, and
depending on the function, it will either take in one or two arguments,
and apply that function on the arguments.

How could we write this?  Let's try it:


###
from sys import exit

def add(x, y): return x + y
def square(x): return x * x
def divide(x, y): return x / y
def quit():
    print "bye"
    exit()

class Calculator:
    def __init__(self):
        self.operations = {}

    def addOperation(self, name, function):
        self.operations[name] = function

    def execute(self, line):
        name, arguments = line.split()[0], map(float, line.split()[1:])
        function = self.operations[name]
        return apply(function, arguments)

if __name__ == '__main__':
    calc = Calculator()
    calc.addOperation('add', add)
    calc.addOperation('square', square)
    calc.addOperation('divide', divide)
    calc.addOperation('quit', quit)
    # we could add more if we wanted to ...

    try:
        while 1:
            print calc.execute(raw_input()), "\n"
    except KeyboardInterrupt: pass
###

The program is simpler than it looks: the reason why apply() is used is
because we need to call a function, but we don't know in advance how many
arguments the user will input.  We'll use apply(), which will take a
function and a list, and use the list elements as the function's
arguments.  That way, we place very few restrictions on what our
"calculator" can do.

I hope that this made some sense; For me, it's hard to write a small
example that uses apply().