1

Let's say we have a class which has an instance method that accepts another instance of that class, and then returns a new instance of that class.

An example of an this type of class is an integer. It has the __mul__ method, which accepts another integer and returns an integer, which is the product of both numbers.

Here's the problem. I have a class that implements a method like __mul__. I have a list of instances of this class, and I want to apply the aforementioned method of the last object to the object before it, then take the result of that and apply it to the one before it, etc., until we have processed the entire list, and have ourselves one object.

A concrete example looks like this. Imagine we have a list of objects...

my_objs = [do, re, me, fa, so, la, te, do]

... And imagine they have the "combine" method, which follows the pattern outlined above, and we want to apply the procedure I outlined to it. You might think of it like this ...

my_objs_together = do.combine(re.combine(me.combine(fa.combine(so.combine(la.combine(te.combine(do)))))))

That's pretty gnarly, obviously. This makes me want to write a generic function like this...

def together(list_of_objects, method_name):
    combined = list_of_objects[0]
    for obj in list_of_objects[1:]:
        combined = getattr(combined, method_name)(obj)
    return combined

...But it occurs to me that there's likely already a standard library function that does this, right?

1 Answer 1

4

It's reduce! (I was in the middle of writing the question when I found it :/)

https://docs.python.org/2/library/functions.html#reduce

Apply function of two arguments cumulatively to the items of iterable, from left to right, so as to reduce the iterable to a single value. For example, reduce(lambda x, y: x+y, [1, 2, 3, 4, 5]) calculates ((((1+2)+3)+4)+5).

Sign up to request clarification or add additional context in comments.

1 Comment

You might enjoy learning a functional programming language like Haskell. Reduce, map, and friends are functional constructs that Python happens to support. It's hard at first but once you learn the paradigm you will find a lot of neat things like this that you can do.

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.