Last active
September 21, 2016 16:32
-
-
Save dwickstrom/48f45bdfa13b2330191313365ca3a74c to your computer and use it in GitHub Desktop.
Some sort of fmap implementation in Python
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import inspect | |
def fmap(f, functor): | |
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 | |
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) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment