Skip to content

Instantly share code, notes, and snippets.

@cheecheeo
Created June 4, 2014 21:11
Show Gist options
  • Save cheecheeo/9fe5d32a8fa14cbe5b18 to your computer and use it in GitHub Desktop.
Save cheecheeo/9fe5d32a8fa14cbe5b18 to your computer and use it in GitHub Desktop.
Either in Python
"""
Either in Python.
"""
def left(x):
"""
Haskell: Left 5
Python: left(5)
"""
return lambda left_f, junk: left_f(x)
def right(x):
"""
Haskell: Right True
Python: right(True)
"""
return lambda junk, right_f: right_f(x)
def either(f, g, e):
"""
Haskell: either f g e
Haskell: case e of
x -> f x
y -> g y
Python: either(f, g, e)
>>> x = left(42)
>>> y = right("hello")
>>> either(lambda x: x * 2, lambda x: len(x), x)
84
>>> either(lambda x: x * 2, lambda x: len(x), y)
5
"""
return e(f, g)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment