Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import inspect
- def _dict_map(f, functor):
- result = {}
- for key, value in functor.items():
- result[key] = f(value)
- return result
- def _object_map(f, functor):
- map_method = getattr(functor, "map", None)
- if callable(map_method):
- return functor.map(f)
- attributes = inspect.getmembers(functor, lambda a:not(inspect.isroutine(a)))
- user_attrs = [a for a in attributes if not(a[0].startswith('__') and a[0].endswith('__'))]
- new_functor = functor.__class__()
- for a in user_attrs:
- setattr(new_functor, a[0], f(a[1]))
- return new_functor
- def _list_map(f, functor):
- idx = 0
- length = len(functor)
- result = []
- while idx < length:
- result.append(f(functor[idx]))
- idx += 1
- return result
- def fmap(f, functor):
- if isinstance(functor, list):
- return _list_map(f, functor)
- elif isinstance(functor, dict):
- return _dict_map(f, functor)
- elif isinstance(functor, object):
- return _object_map(f, functor)
- else:
- return map(f, functor)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement