Last active
August 17, 2021 09:48
-
-
Save kitsuyui/b74b2f146e46f2ab20ece4f8d8176944 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from functools import reduce | |
identity = lambda x: x | |
tranceduce_as_map = lambda mapper: lambda concat: lambda xs, x: concat(xs, mapper(x)) | |
tranceduce_as_filter = lambda predicate: lambda concat: lambda xs, x: concat(xs, x) if predicate(x) else xs | |
compose = lambda f, g: lambda x: f(g(x)) | |
compose_n = lambda *fns: reduce(compose, fns, identity) | |
is_not_zero = lambda n: n != 0 | |
is_multiple_of_3 = lambda x: x % 3 == 0 | |
is_multiple_of_5 = lambda x: x % 5 == 0 | |
minus_one = lambda n: n - 1 | |
plus_two = lambda n: n + 2 | |
def concat_list(xs, x): | |
xs.append(x) | |
return xs | |
def concat_tuple(xs, x): | |
return xs + (x,) | |
def concat_generator(xs, x): | |
yield from xs | |
yield x | |
def main(): | |
target_list = range(0, 100) | |
answer = [1, 16, 31, 46, 61, 76, 91] | |
original_version = map(plus_two, | |
map(minus_one, | |
filter(is_multiple_of_5, | |
filter(is_multiple_of_3, | |
target_list)))) | |
composed = compose_n( | |
tranceduce_as_filter(is_multiple_of_3), | |
tranceduce_as_filter(is_multiple_of_5), | |
tranceduce_as_map(minus_one), | |
tranceduce_as_map(plus_two), | |
) | |
tranceduce_list_version = reduce(composed(concat_list), target_list, []) | |
tranceduce_tuple_version = reduce(composed(concat_tuple), target_list, ()) | |
tranceduce_generator_version = reduce(composed(concat_generator), target_list, iter(())) | |
assert list(answer) == list(original_version) | |
assert list(answer) == list(tranceduce_list_version) | |
assert list(answer) == list(tranceduce_tuple_version) | |
assert list(answer) == list(tranceduce_generator_version) | |
if __name__ == '__main__': | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment