Array of Functions
Ian Kelly
ian.g.kelly at gmail.com
Fri Nov 14 17:50:42 EST 2014
On Fri, Nov 14, 2014 at 3:17 PM, Richard Riehle <rriehle at itu.edu> wrote:
> In C, C++, Ada, and functional languages, I can create an array of functions, albeit with the nastiness of pointers in the C family. For example, an array of functions where each function is an active button, or an array of functions that behave like formulae in a spreadsheet. I am finding this a bit challenging in Python.
>
> Example:
>
> r1c1 r1c2 r1c3
> r2c1 r2c2 r2c3
> r3c1 r3c2 r3c3
>
> where r1 is row 1 and c1 is column 1. Suppose I want an array where the colum three is a set of functions that operates on the other two columns, depending on the values I set for those rows and columns? As noted, I can do this pretty easily in most languages (well, except for Java which does not support any kind of functional programming capability), even if I have to use pointers.
>
> I think my difficulty is related to the REPL nature of Python. However, I am sure some clever Pythonista has found a way to do this.
>>> list_of_functions = [lambda x=x: x + 4 for x in range(3)]
>>> list_of_functions[0]()
4
>>> list_of_functions[1]()
5
>>> list_of_functions[2]()
6
If you want more help, you'll have to be more specific about the
problem you're encountering. Since you didn't go into any detail, I'm
just going to assume that it's the common pitfall of variable scoping
in functions defined in a loop and point you to this FAQ answer:
https://docs.python.org/3/faq/programming.html#why-do-lambdas-defined-in-a-loop-with-different-values-all-return-the-same-result
More information about the Python-list
mailing list