0

Could you please help me? I would like to write function which successively applies several functions to some iterable object and return list of results. I do not want to create temporary list object on each iteration step. Goal is to use lazy evaluation.

def applay(iterable, functions):
    res = iterable
    for f in functions:
        res = (f(i) for i in res)

    return list(res)

print applay([1,2,3], [lambda x: x+1, lambda y: y+2])

This does not work as f inside of each generator bind to the last function from function list. Can I avoid this python feature?

Look like I have found solution:

from itertools import repeat
from functools import partial

def applay(iterable, functions):

    res = arg_to_iter(iterable)
    for cur_f in functions:
        res = (f(r) for r, f in zip(res, partial(repeat, cur_f)()))

    return list(res)

print applay([1,2,3], [lambda x: x+1, lambda y: y+2])
  • This isn't a problem with the generator.. it's a problem with your lambda. Try just: ```funcs = [lambda x: x+i for i in range(3)]; print funcs[1](3); print funcs[2](3)``` – Chad S. Sep 09 '15 at 18:59
  • Yes. Thank you. I agree with you. My functions list was not created correctly. But I have updated it but original problem is still exist. – Mikhail Lyundin Sep 09 '15 at 19:31
  • I found this works:: def applay(it, funcs): r = []; for f in funcs: r += [f(i) for i in it]; return r --- sorry about the format but answers have been disabled –  Sep 09 '15 at 20:19
  • Maybe it works. but I am looking for solution without temporary list objects – Mikhail Lyundin Sep 09 '15 at 20:30

0 Answers0