fmap(), "inverse" of Python map() function

Ian Kelly ian.g.kelly at gmail.com
Fri Oct 5 17:43:31 EDT 2012


On Fri, Oct 5, 2012 at 3:31 PM, Ian Kelly <ian.g.kelly at gmail.com> wrote:
> On Fri, Oct 5, 2012 at 2:19 PM, vasudevram <vasudevram at gmail.com> wrote:
>>
>> http://jugad2.blogspot.in/2012/10/fmap-inverse-of-python-map-function.html
>
> Your fmap is a special case of reduce.
>
> def fmap(functions, argument):
>     return reduce(lambda result, func: func(result), functions, argument)

In a more functional style, you could also use reduce to compose the
functions before applying them:

def compose(f, g):
    return lambda x: f(g(x))

def fmap(functions):
    return reduce(compose, reversed(functions))

# Allowing you to then do:
result = fmap(functions)(argument)

Cheers,
Ian



More information about the Python-list mailing list