Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Looking for a fold-like idiom

So my friend presented a problem for me to solve, and I'm currently writing a solution in functional-style Python. The problem itself isn't my question; I'm looking for a possible idiom that I can't find at the moment.

What I need is a fold, but instead of using the same function for every one of it's applications, it would do a map-like exhaustion of another list containing functions. For example, given this code:

nums = [1, 2, 3]
funcs = [add, sub]
special_foldl(nums, funcs)

the function (special_foldl) would fold the number list down with ((1 + 2) - 3). Is there a function/idiom that elegantly does this, or should I just roll my own?

like image 645
Dutch Avatar asked Jan 22 '26 22:01

Dutch


1 Answers

There is no such function in the Python standard library. You'll have to roll you own, perhaps something like this:

import operator
import functools

nums = [1, 2, 3]
funcs = iter([operator.add, operator.sub])

def special_foldl(nums, funcs):
    return functools.reduce(lambda x,y: next(funcs)(x,y), nums)

print(special_foldl(nums, funcs))
# 0
like image 159
unutbu Avatar answered Jan 24 '26 12:01

unutbu



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!