tags:

views:

83

answers:

5

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  A: 

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.

Ignacio Vazquez-Abrams
A: 

There's a good recipe for this here.

Alex Martelli
+2  A: 

I think you are looking for function composition in Python.

You can do this:

f = lambda x: f1(f2(x))
Mark Byers
+1  A: 
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]
sepp2k
+1  A: 
>>> import functional, functools, operator
>>> f1 = int
>>> f2 = functools.partial(operator.add, 1)
>>> f = functional.compose(f1, f2)
>>> x = map(f, ['1', '2', '3'])
ephemient