Guest User

Untitled

a guest
Oct 18th, 2018
87
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.84 KB | None | 0 0
  1. #-*- coding:utf-8 -*-
  2. u'''
  3. 関数合成みたいな何か
  4. '''
  5.  
  6.  
  7. class Composable(object):
  8. u'''
  9. 合成可能
  10. '''
  11.  
  12. def __init__(self, funcs):
  13.  
  14. self.functions = funcs
  15.  
  16.  
  17. def __and__(self, func):
  18.  
  19. return Composable(self.functions+[func])
  20.  
  21.  
  22. def __call__(self, *args, **argd):
  23.  
  24. rev = list(reversed(self.functions))
  25.  
  26. car = rev[0]
  27. cdr = rev[1:]
  28.  
  29. return reduce(lambda x, y: y(x),
  30. cdr, car(*args, **argd))
  31.  
  32.  
  33. def composable(f):
  34. u'''
  35. デコレータちゃん
  36. '''
  37.  
  38. return Composable([f])
  39.  
  40.  
  41.  
  42. if __name__ == '__main__':
  43.  
  44.  
  45. @composable
  46. def add1(v):
  47. return v + 1
  48.  
  49. @composable
  50. def mul2(v):
  51. return v * 2
  52.  
  53. print (mul2 & add1 & add1 & add1)(10) # (10 + 1 + 1 +1) * 2
  54. print (add1 & add1 & add1 & mul2)(10) # 10 * 2 + 1 + 1 + 1
Add Comment
Please, Sign In to add comment