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

I

Ian Kelly

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
 
D

Devin Jeanpierre

Your fmap is a special case of reduce.

So is map.

def map(f, seq):
return reduce(
lambda rseq, newpre:
rseq.append(f(newpre)) or rseq,
seq,
[])

"X is a special case of reduce" is basically the same as saying "X can
be implemented using a for loop". If it's meant as a complaint, it's a
poor one.

-- Devin
 
D

Devin Jeanpierre

I realize that. My point is that the function *feels* more like a
variant of reduce than of map.


It's not.

Fair enough all around. Sorry for misunderstanding.

-- Devin
 
V

vasudevram

Thanks to all who replied. Always good to learn something new.

P.S. A reader posted a good comment with Scala as well as Python code for a compose function (basically same functionality as fmap, or more - the compose once, run many times thing). It's the 4th comment on my blog post.

- Vasudev
 
V

vasudevram

Thanks to all who replied. Always good to learn something new.

P.S. A reader posted a good comment with Scala as well as Python code for a compose function (basically same functionality as fmap, or more - the compose once, run many times thing). It's the 4th comment on my blog post.

- Vasudev
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,744
Messages
2,569,484
Members
44,903
Latest member
orderPeak8CBDGummies

Latest Threads

Top