Last active
January 8, 2022 20:54
-
-
Save asukaminato0721/9df278cbb8952baac74a6edd7dbfedc0 to your computer and use it in GitHub Desktop.
Clojure's -> and ->> operator 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
""" | |
This mimic the behavior of clojure's Thread-end ->> | |
""" | |
from functools import reduce, wraps | |
from typing import Callable | |
def double_rightarrow_decorator(f: Callable): | |
""" | |
f(..., a,b,c) -> f(..., a,b)(c) | |
""" | |
@wraps(f) | |
def decorated(*args): | |
@wraps(f) | |
def after(first): | |
return f(*args, first) | |
return after | |
return decorated | |
def apply(x, f: Callable): | |
return f(x) | |
def rightarrow(var, *funcs: Callable): | |
return reduce(apply, funcs, var) | |
@double_rightarrow_decorator | |
def f1(x, y): | |
""" | |
this accepts two arguments and returns a list | |
""" | |
print(x, y) | |
return [x, y] | |
rightarrow(1, f1(2), f1(3), f1(4), f1(5)) |
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
""" | |
This mimic the behavior of Clojure's Thread-first -> | |
""" | |
from functools import reduce, wraps | |
from typing import Callable | |
def rightarrow_decorator(f: Callable): | |
""" | |
f(a,b,c,...) -> f(b,c,...)(a) | |
""" | |
@wraps(f) | |
def decorated(*args, **kwargs): | |
@wraps(f) | |
def after(first): | |
return f(first, *args, **kwargs) | |
return after | |
return decorated | |
def apply(x, f: Callable): | |
return f(x) | |
def rightarrow(var, *funcs: Callable): | |
return reduce(apply, funcs, var) | |
@rightarrow_decorator | |
def f1(x, y): | |
""" | |
this accepts two arguments and returns a list | |
""" | |
print(x, y) | |
return [x, y] | |
rightarrow(1, f1(2), f1(3), f1(4), f1(5)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment