[Tutor] What Eval() Hath Men Wrought
Danny Yoo
dyoo at hkn.eecs.berkeley.edu
Thu Jun 24 13:38:32 EDT 2004
On Tue, 22 Jun 2004, Theresa Robinson wrote:
> For example, we'll want to write a function to minimize the return value
> of another function by varying the latter function's vector argument.
>
> The C way to do it is to pass in a pointer to a function. This is good
> because C nicely checks that the function 1) is actually a function 2)
> takes the right arguments 3) returns the right type.
Hi Theresa,
It's perfectly possible to do something similar here in Python, since
functions can take functions as arguments very easily. For example:
###
>>> def find_fixed_point(some_function, initial_guess, tolerance):
... """Tries to find the fixed point of a function within a certain
... tolerance."""
... x = initial_guess
... while True:
... new_x = some_function(x)
... if abs(new_x - x) < tolerance:
... return new_x
... x = new_x
...
>>> import math
>>> find_fixed_point(math.cos, 1.0, 0.0000001)
0.73908516994455442
###
> The Matlab way to do it is to pass a string that contains the function
> name, and to use the Matlab feval function, which is similar to the
> Python eval but nicer since you don't have to construct the whole string
> yourself, but instead can use the form feval('function_name',argument).
> This works but is bad because you get weird errors if the function name
> is wrong, or if the function takes an unexpected kind of argument or
> returns an unexpected type.
Right. Don't use eval() for this purpose in Python. *grin* Just pass the
function value around as an argument, and you should be fine.
Python's approach, in allowing us to pass around and construct functions,
is similar to that of Scheme. You may find the "Structure and
Interpretation of Computer Programs":
http://mitpress.mit.edu/sicp/full-text/book/book.html
very useful in learning this technique of treating functions as passable
values. Even though the book uses a different programming language, most
of the concepts map very closely to Python.
We can take an example from:
http://mitpress.mit.edu/sicp/full-text/book/book-Z-H-12.html#%_sec_1.3.1
like this one:
;;;;;; Scheme
(define (sum term a next b)
(if (> a b)
0
(+ (term a)
(sum term (next a) next b))))
;;;;;;
This Scheme SUM function calculates the sum of a bunch of terms. It takes
in two functions: a TERM and a NEXT. A Python adaptation might look
something like this:
###
def sum(term, a, next, b):
result = 0
while a <= b:
result += term(a)
a = next(a)
return result
###
Here's how it might work:
###
>>> def square(x): return x * x
...
>>> def inc(x): return x + 1
...
>>> sum(square, 1, inc, 5) ## [This calculates 1 + 4 + 9 + 16 + 25]
55
###
I hope this gives a taste of what we can do with function passing. If you
have more questions, please feel free to ask on the Tutor list. Good
luck!
More information about the Tutor
mailing list