Functional languages have functions such as foldr and foldl that do things like collapse an array. So, recently I wondered if there was a similar implementation in Python, but I realized that there was something called reduse.
For example, if you want to guarantee that everything is True in an array consisting of only Booleans, if you do not use reduse, you may end up with the following dirty writing style.
python
def check_all_true(check_array):
result = True
for elem in check_array:
result = result and elem
return result
if __name__ == '__main__':
print check_all_true([True, True, True])
print check_all_true([True, False, True])
If you rewrite this to reduce, it will look refreshing as shown below.
python
def check_all_true(check_array):
return reduce(lambda prev, nxt: prev and nxt, check_array)
if __name__ == '__main__':
print check_all_true([True, True, True])
print check_all_true([True, False, True])
However, the substance of reduce seems to be foldl, so if you want to operate like foldr, you need to devise a little.
Recommended Posts