Using functional tools

Patrick W quitelikely at yahoo.com.au
Sat May 4 09:19:10 EDT 2002


Alex Martelli <aleax at aleax.it> writes:

> List comprehensions are an eminently "(functional)" way -- consider that
> Python took them from Haskell, surely a contender for "most functional
> of functional languages":-).  However, Python's syntax for them was
> indeed adapted to be more Pythonic, and in particular to use the
> keyword 'for'.  Therefore, it's hard to say whether a list comprehension
> meets your requirements, or not!
> 
> With a list comprehension, I'd do something like:
> 
> def feedOneOfN(sequence, function, N):
>     def identity(x): return x
>     funs = [identity]*(N-1) + [function]
>     return [funs[i%N](x) for x in sequence]

Too clever by half here Alex ;-) The 'i' in the last line is unbound,
but if it's meant to be an x, it won't work correctly because you'd be
selecting a function based on the _value_ of x in sequence rather than
the _position_ of x in sequence.

A similar approach with list comprehensions, but easier to understand
IMO, would be something like:

def do_every_nth(seq, func, n):
    def transform(item, index):
        if index % n == n - 1: return func(item)
        else: return item
    return [transform(seq[x], x) for x in range(len(seq))]




More information about the Python-list mailing list