1

Does anyone know how to translate this HOF from previous version of Python to Python 3?

apply_each = lambda fns, args=[]: map(apply, fns, [args]*len(fns))

This comes from the book titled: Text Processing in Python by David Mertz. I'm not able to use the apply function in Python 3 since it has been deprecated. I've tried using func(*args, **kwargs) instead of apply(func, args, kwargs), but I get this TypeError: 'float' object is not iterable. I've also found those notes which show what the function is supposed to return: https://wiki.python.org/moin/TextProcessingInPython

here's my try at the code:

apply_each = lambda fns, args=[]: map(fns, *args)
args = [5.4, 6.3, 6.3]
print(list(apply_each(approx, args)))
0

1 Answer 1

1

You can define your own .apply:

>>> def apply(f, args):
...     return f(*args)
...
>>> apply_each = lambda fns, args=[]: map(apply, fns, [args]*len(fns))

Or all in one go:

apply_each = lambda fns, args=[]: map(lambda f, args: f(*args), fns, [args]*len(fns))

But this is poor style, the only advantage of a lambda is that it is anonymous, if you are going to assign it to a name, that defeats the purpose. This is better style:

def apply(f, args):
    return f(*args)

def apply_each(fns, args=()):
    return map(apply, fns, [args]*len(fns))

So:

>>> import operator as op
>>> list(apply_each([op.add, op.sub, op.mul, op.truediv], args=[1,2]))
[3, -1, 2, 0.5]
Sign up to request clarification or add additional context in comments.

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.