Skip to content

Instantly share code, notes, and snippets.

@hachibeeDI
Last active June 7, 2019 10:36
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 hachibeeDI/6028727 to your computer and use it in GitHub Desktop.
Save hachibeeDI/6028727 to your computer and use it in GitHub Desktop.
Pythonで関数合成と適用的な ref: https://qiita.com/hatchinee/items/ab208f0ce596964c1a31
def compose(f_t_u, f_u_r):
'''
:type f_t_u: t -> u
:type f_u_r: u -> r
:rtype: t -> r
>>> comp(lambda a: a + 'oppai', lambda b: b + 'hoge')('')
'oppaihoge'
>>> comp(comp(lambda a: a+'oppai', lambda b: b+ 'hoge'), lambda x: '[' + x + ']')('')
'[oppaihoge]'
'''
return lambda t: f_u_r(f_t_u(t))
class infix(object):
def __init__(self, function):
self.function = function
def __ror__(self, other):
self.left = other
return self
def __or__(self, other):
return self.function(self.left, other)
def __call__(self, value1, value2):
return self.function(value1, value2)
@infix
def c(f_t_u, f_u_r): return lambda t: f_u_r(f_t_u(t))
(str.upper |c| sorted |c| set)('abcdeabc')
# > set(['A', 'C', 'B', 'E', 'D'])
class Ap(object):
def __init__(self, val):
self.val=val
def __rshift__(self, func):
return func(self.val)
Ap('abcdeabc') >> (str.upper |c| sorted |c| set)
# > set(['A', 'C', 'B', 'E', 'D'])
class _Ap(object):
def __rlshift__(self, other):
self.value = other
return self
def __rshift__(self, other):
return other(self.value)
Ap = _Ap()
a = Ap
'abcdacb' <<a>> (str.upper |c| sorted)
#> ['A', 'A', 'B', 'B', 'C', 'C', 'D']
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment