[Python-Dev] a different kind of reduce...
Paul Moore
p.f.moore at gmail.com
Mon Oct 31 23:29:30 CET 2005
On 10/31/05, Martin Blais <blais at furius.ca> wrote:
> I'm always--literally every time-- looking for a more functional form,
> something that would be like this:
>
> # apply dirname() 3 times on its results, initializing with p
> ... = repapply(dirname, 3, p)
[...]
> Just wondering, does anybody know how to do this nicely? Is there an
> easy form that allows me to do this?
FWIW, something like this works:
>>> def fpow(f, n):
... def res(*args, **kw):
... nn = n
... while nn > 0:
... args = [f(*args, **kw)]
... kw = {}
... nn -= 1
... return args[0]
... return res
...
>>> fn = r'a\b\c\d\e\f\g'
>>> d3 = fpow(os.path.dirname, 3)
>>> d3(fn)
'a\\b\\c\\d'
You can vary this a bit - the handling of keyword arguments is an
obvious place where I've picked a very arbitrary approach - but you
get the idea. This *may* be a candidate for addition to the new
"functional" module, but I'd be surprised if it got added without
proving itself "in the wild" first. More likely, it should go in a
local "utilities" module.
Paul.
More information about the Python-Dev
mailing list