Skip to content

Instantly share code, notes, and snippets.

@3noch
Last active December 20, 2021 21:41
Show Gist options
  • Select an option

  • Save 3noch/eef18dba108be7db0441 to your computer and use it in GitHub Desktop.

Select an option

Save 3noch/eef18dba108be7db0441 to your computer and use it in GitHub Desktop.
Functors in Python
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() })
@xtofl

xtofl commented Dec 18, 2021

Copy link
Copy Markdown

@3noch

3noch commented Dec 20, 2021

Copy link
Copy Markdown
Author

Cool! Thank you.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment