Advertisement
Guest User

Untitled

a guest
Aug 26th, 2016
56
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.03 KB | None | 0 0
  1. import inspect
  2.  
  3. def _dict_map(f, functor):
  4. result = {}
  5. for key, value in functor.items():
  6. result[key] = f(value)
  7. return result
  8.  
  9. def _object_map(f, functor):
  10. map_method = getattr(functor, "map", None)
  11. if callable(map_method):
  12. return functor.map(f)
  13.  
  14. attributes = inspect.getmembers(functor, lambda a:not(inspect.isroutine(a)))
  15. user_attrs = [a for a in attributes if not(a[0].startswith('__') and a[0].endswith('__'))]
  16. new_functor = functor.__class__()
  17. for a in user_attrs:
  18. setattr(new_functor, a[0], f(a[1]))
  19. return new_functor
  20.  
  21. def _list_map(f, functor):
  22. idx = 0
  23. length = len(functor)
  24. result = []
  25. while idx < length:
  26. result.append(f(functor[idx]))
  27. idx += 1
  28. return result
  29.  
  30. def fmap(f, functor):
  31. if isinstance(functor, list):
  32. return _list_map(f, functor)
  33.  
  34. elif isinstance(functor, dict):
  35. return _dict_map(f, functor)
  36.  
  37. elif isinstance(functor, object):
  38. return _object_map(f, functor)
  39.  
  40. else:
  41. return map(f, functor)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement