2

Haskell provides the feature something like f = f1 . f2

How can I mimic that with Python?

For example, if I have to do the 'map' operation two times, is there any way to do something like map . map in Python?

x = ['1','2','3'] 
x = map(int,x) 
x = map(lambda i:i+1, x) 
1
  • It isn't the answer you're looking for, but your example could be condensed to x = map(lambda i:int(i)+1, x) Commented Mar 11, 2010 at 22:09

5 Answers 5

2

I think you are looking for function composition in Python.

You can do this:

f = lambda x: f1(f2(x))
Sign up to request clarification or add additional context in comments.

Comments

1

There have been several proposals for a compose operation, but none have been formalized. In the meantime it is possible to use a list comprehension or a generator expression to apply complex transformations to a sequence.

Comments

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

def inc(x): return x+1

map(compose(inc, int), ['1', '2', '3'])
# [2, 3, 4]

Comments

1
>>> import functional, functools, operator
>>> f1 = int
>>> f2 = functools.partial(operator.add, 1)
>>> f = functional.compose(f1, f2)
>>> x = map(f, ['1', '2', '3'])

Comments

0

There's a good recipe for this here.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.