Last active
December 20, 2021 21:41
-
-
Save 3noch/eef18dba108be7db0441 to your computer and use it in GitHub Desktop.
Functors 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 types | |
| global fmap_vtable | |
| fmap_vtable = {} | |
| def fmap_for(type): | |
| def register_fmap(func): | |
| fmap_vtable[type] = func | |
| return func | |
| return register_fmap | |
| def fmap(fn, data): | |
| return fmap_vtable[type(data)](fn, data) | |
| apply = lambda fn, data: fn(data) | |
| fmap_for(types.NoneType)(lambda fn, data: None) | |
| fmap_for(int)(apply) | |
| fmap_for(str)(apply) | |
| fmap_for(float)(apply) | |
| fmap_for(bool)(apply) | |
| fmap_for(list)(map) | |
| fmap_for(dict)(lambda fn, data: { key: fn(value) for key, value in data.iteritems() }) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Followup: https://github.com/xtofl/fmappy/blob/c2b1248becbe6378b15ce3a161439defa0f64cb4/README.md