Skip to content

Instantly share code, notes, and snippets.

@podhmo
Created June 4, 2014 07:31
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save podhmo/5d5c6ba2245a5d232da0 to your computer and use it in GitHub Desktop.
Save podhmo/5d5c6ba2245a5d232da0 to your computer and use it in GitHub Desktop.
# -*- coding:utf-8 -*-
class pipe(object):
def __init__(self, fn):
self.fn = fn
def __ror__(self, other):
return self.fn(other)
def __call__(self, *args, **kwargs):
def wrap(x):
return self.fn(x, *args, **kwargs)
return self.__class__(wrap)
@pipe
def inc(x):
return x + 1
def add(x):
return pipe(lambda y: x + y)
print(10) # => 10
print(10 | inc) # => 11
print(10 | inc | add(10)) # => 21
class maybe(object):
def __init__(self, fn):
self.fn = fn
def __ror__(self, other):
if other is None:
return None
return self.fn(other)
def __call__(self, *args, **kwargs):
def wrap(x):
return self.fn(x, *args, **kwargs)
return self.__class__(wrap)
@maybe
def inc2(x):
return x + 1
def add2(x):
return maybe(lambda y: x + y)
print(10) # => 10
print(10 | inc2) # => 11
print(10 | inc2 | add2(10)) # => 21
print(None | inc2 | add2(10)) # => None
def to_maybe(o):
return MaybeWrap(o)
class MaybeWrap(object):
def __init__(self, o):
self.value = o
def apply(self, fn):
if self.value is None:
return Nothing
return self.__class__(fn(self.value))
Nothing = MaybeWrap(None)
class pipe2(object):
def __init__(self, fn):
self.fn = fn
def __ror__(self, other):
return other.apply(self.fn)
def __call__(self, *args, **kwargs):
def wrap(x):
return self.fn(x, *args, **kwargs)
return self.__class__(wrap)
@pipe2
def inc3(x):
return x + 1
def add3(x):
return pipe2(lambda y: x + y)
@pipe2
def fail(x):
return None
print(to_maybe(10).value) # => 10
print((to_maybe(10) | inc3).value) # => 11
print((to_maybe(10) | inc3 | add3(10)).value) # => 31
print((to_maybe(None) | inc3 | add3(10)).value) # => None
print((to_maybe(10) | inc3 | fail | add3(10)).value) # => None
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment