Why functional Python matters

Dave Benjamin ramen at lackingtalent.com
Wed Apr 16 02:11:49 EDT 2003


In article <sggp9v8lpk0045klmquc8gec1ju7q4kmpe at 4ax.com>, Courageous wrote:
> Anonymous functions are occasionally useful, as in Java's anonymous
> class expressions, really used as a poor man's lambda of sorts. I've
> seen this overused, though, that's for sure.

How frequently a feature is useful depends on the problem domain. Java's
anonymous classes are a poor substitute because they carry so much baggage.
For comparison, here's an implementation and usage of map in Java:

static interface Functor {Object call(Object[] args);}

static Object[] map(Functor func, Object[] array) {
    Object[] result = new Object[array.length];
    for (int i = 0; i < array.length; i++) {
        result[i] = func.call(new Object[] {array[i]});
    }
    return result;
}

public static void main(String args[]) {
    System.out.println(Arrays.asList(map(
        new Functor() {
            public Object call(Object[] args) {
                return args[0] + ", world!";
            }
        }, new String[] {"Hello", "Goodbye"}
    )));    
}

And the same usage in Python:

>>> print map(lambda x: x + ', world!', ['Hello', 'Goodbye'])
['Hello, world!', 'Goodbye, world!']

This is why Java is IMHO unfit for common functional tasks where Python
shines with elegance. As to whether or not anonymous functions can be
overused, I think any feature can be overused. Classes, for one. In fact, in
my day to day work, I find the two of similar usefulness, but maybe it's
just because of the way I program. =)

Peace,
Dave




More information about the Python-list mailing list