Last active
August 30, 2016 10:31
-
-
Save kureta/d37e8cd934cb9412f726e45bff3bec8a to your computer and use it in GitHub Desktop.
Example of function composition 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
def compose(*funs): | |
""" Takes functions as arguments and their composition as a single function. """ | |
def compose2(f, g): | |
return lambda x: f(g(x)) | |
return reduce(compose2, funs, lambda x: x) | |
def curry(func): | |
""" Currying decorator. """ | |
def curried(*args, **kwargs): | |
if len(args) + len(kwargs) >= func.__code__.co_argcount: | |
return func(*args, **kwargs) | |
return (lambda *args2, **kwargs2: | |
curried(*(args + args2), **dict(kwargs, **kwargs2))) | |
return curried | |
def memoize(f): | |
""" Memoization decorator for functions taking one or more arguments. | |
:param f: a function | |
""" | |
class MemoDict(dict): | |
def __init__(self, f_, **kwargs): | |
super().__init__(**kwargs) | |
self.f = f_ | |
def __call__(self, *args): | |
return self[args] | |
def __missing__(self, key): | |
ret = self[key] = self.f(*key) | |
return ret | |
return MemoDict(f) | |
def pmap(*args): | |
""" Multiprocess map. """ | |
with Pool(cpu_count()) as p: | |
return p.map(*args) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment