Skip to content

Instantly share code, notes, and snippets.

@davidallsopp
Last active August 29, 2015 14:06
Show Gist options
  • Select an option

  • Save davidallsopp/49b399d786561ce9994d to your computer and use it in GitHub Desktop.

Select an option

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.
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