Last active
August 29, 2015 14:06
-
-
Save davidallsopp/49b399d786561ce9994d to your computer and use it in GitHub Desktop.
Flipping lines of text in a functional style, in Python 2. E.g. for reflecting ASCII art left-to-right.
This file contains hidden or 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
| import functools | |
| def compose(*functions): | |
| "Compose multiple functions together. See https://mathieularose.com/function-composition-in-python/" | |
| return functools.reduce(lambda f, g: lambda x: f(g(x)), functions) | |
| # More limited case of just two functions: | |
| #def compose2(f, g): | |
| # return lambda x: f(g(x)) | |
| def flip(text): | |
| return "\n".join(map(compose("".join, reversed), text.split('\n'))) | |
| # or without using function composition: | |
| #def flip2(text): | |
| # return "\n".join(["".join(reversed(line)) for line in text.split('\n')]) | |
| flip("foo\nbar") | |
| # 'oof\nrab' |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment