幾個 Python 語法糖的實現
阿新 • • 發佈:2019-02-04
1. compose
實現compose
函式,滿足如下操作:
f = lambda x: x**2 + 1
g = lambda x: 2*x - 1
h = lambda x: -2 * x**3 + 3
fgh = compose(f, g, h)
# equivalent to `f(g(h(n)))`
print fgh(5) # 245026
我們可以讓compose
返回一個函式,這個函式倒序遍歷compose
中的引數,並對輸入引數呼叫該引數。
def compose(*args):
def retFunc(x):
i = len(args) - 1
while i >= 0:
func = args[i]
assert(func.__call__)
x = func(x)
i -= 1
return x
return retFunc
2. composable
實現composable
函式,滿足如下操作:
@composable
def add2(x):
return x + 2
@composable
def mul3(x):
return x * 3
@composable
def pow2(x):
return x ** 2
fn = add2 * mul3 * pow2
# equivalent to `add2(mul3(pow2(n)))`
print fn(5) # 77
composable
函式接受一個函式,返回一個封裝後的東西讓其可以通過*
來複合。那我們就建立一個類來封裝這些東西好了。
class Composable(object):
def __init__(self, *args):
object.__init__(self)
for f in args:
assert (f.__call__)
self.func = args
def __call__(self, x):
i = len(self.func) - 1
while i >= 0:
func = self.func[i]
assert(func.__call__)
x = func(x)
i -= 1
return x
def __mul__(self, rv):
assert(isinstance(rv, Composable))
return Composable(*(self.func + rv.func))
composable = Composable
3.infix
實現infix
,滿足:
@infix
def plus(a, b):
return a + b
print 1 /plus/ 2
# equivalent to `plus(1, 2)`
print 1 /of/ int
# equivalent to `isinstance(1, int)`
print 1 /to/ 10
# equivalent to `range(1, 11)`
我們可以看到,infix
函式接受一個函式,並把這個函式變成中綴。of
可以看做isinstance
的中綴,to
可以看做range
的中綴(需要微調)。
我們先把後兩個定義出來:
of = infix(isinstance)
to = infix(lambda x, y: range(x, y + 1))
然後實現infix
:
class Infix(object):
def __init__(self, f):
object.__init__(self)
assert(f.__call__)
self.func = f
self.set = False
def __rdiv__(self, i):
assert(not self.set)
r = Infix(self.func)
r.set = True
r.left = i
return r
def __div__(self, t):
assert(self.set)
r = self.func(self.left, t)
self.set = False
return r
def __call__(self, *args, **kwargs):
return self.f(*args, **kwargs)
infix = Infix