Last active
November 13, 2017 12:53
-
-
Save fevral13/d9b1da3b7be0eade41b6f3335064486c to your computer and use it in GitHub Desktop.
Python implementation of LISP's comp function
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
| from functools import reduce, partial | |
| def comp(func1, *others): | |
| """ | |
| Inspired by Clojure function (comp) | |
| Accepts positional arguments - functions | |
| Creates functional composition of functions. Allows to pack nested functions call to single function: | |
| result = f1(f2(f3(f4(args, kwargs)))) | |
| equivalent to | |
| result = comp(f4, f3, f2, f1)(args, kwargs) | |
| People blame LISPs for too many parentheses. Python's version has 4 as much than functional styled. | |
| """ | |
| def wrapper(*args, **kwargs): | |
| return reduce(lambda result, func: func(result), | |
| others, | |
| func1(*args, **kwargs)) | |
| return wrapper | |
| def add_one(arg): | |
| return arg + 1 | |
| def div_by_two(arg): | |
| return arg / 2.0 | |
| map_func = comp(add_one, div_by_two) | |
| map_and_list = comp(map, list) | |
| mapper = partial(map_and_list, map_func) | |
| mapper([1,2,3]) | |
| # [1.0, 1.5, 2.0] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment