Making things more functional in Python

Dave Benjamin ramen at lackingtalent.com
Sat Mar 5 08:28:19 CET 2005


On Sat, 2005-03-05 at 00:00 -0700, Dave Benjamin wrote:
> On Fri, 2005-03-04 at 08:36 -0800, gf gf wrote:
> > Is there a better, more FP style, more Pythonic way to
> > write this:
> > 
> > def compute_vectors(samples, dset):
> > 	vectors = {}
> > 	for d in dset:
> > 		vectors[d] = [sample.get_val(d) for sample in
> > samples]
> > 	return vectors
> 
> You could use reduce:
> 
> def compute_vectors(samples, dset):
>     def add_entry(vectors, d):
>         vectors[d] = [sample.get_val(d) for sample in samples]
>         return vectors
>     return reduce(add_entry, dset, {})

This could be further generalized:

def compute(xs, ys, f):
    def add_entry(result, y):
        result[y] = [f(x, y) for x in xs]
        return result
    return reduce(add_entry, ys, {})

Now, compute_vectors is just:

compute(samples, dset, lambda x, y: x.get_val(y))

You could even abstract the method call:

def method(name):
    def _method(obj, *args, **kwds):
        return getattr(obj, name)(*args, **kwds)
    return _method

compute(samples, dset, method('get_val'))

Dave





More information about the Python-list mailing list