diff --git a/Python/1-closure.py b/Python/1-closure.py new file mode 100644 index 0000000..1933a5c --- /dev/null +++ b/Python/1-closure.py @@ -0,0 +1,15 @@ +import math + + +def create_log(base): + def log(n): + return math.log(n, base) + return log + + +if __name__ == '__main__': + lg = create_log(10) + ln = create_log(math.e) + + print('lg(100) = ', lg(100)) + print('ln(5) = ', ln(5)) diff --git a/Python/4-partial.py b/Python/4-partial.py new file mode 100644 index 0000000..1659e9b --- /dev/null +++ b/Python/4-partial.py @@ -0,0 +1,14 @@ + +def partial(fn, x): + return lambda *args: fn(x, *args) + + +def summary(a, b, c, d): + return a + b + c + d + + +if __name__ == '__main__': + f1 = partial(summary, 1) + f2 = partial(f1, 2) + f3 = partial(f2, 3) + print(f3(4)) diff --git a/Python/5-partial-ext.py b/Python/5-partial-ext.py new file mode 100644 index 0000000..258cb9f --- /dev/null +++ b/Python/5-partial-ext.py @@ -0,0 +1,18 @@ + +def partial(fn, *args): + return lambda *rest: fn(*(args + rest)) + + +def summary(a, b, c, d): + return a + b + c + d + + +if __name__ == '__main__': + f1 = partial(summary, 1) + f2 = partial(f1, 2) + f3 = partial(f2, 3) + print(f3(4)) + + f11 = partial(summary, 1, 2) + f12 = partial(f11, 3) + print(f12(4)) diff --git a/Python/7-curry.py b/Python/7-curry.py new file mode 100644 index 0000000..5eb366b --- /dev/null +++ b/Python/7-curry.py @@ -0,0 +1,29 @@ + +def curry(fn, *args, **kwargs): + def wrapper(*iargs, **ikwargs): + all_args = args + iargs + all_kwargs = {**kwargs, **ikwargs} + try: + return fn(*all_args, **all_kwargs) + except TypeError: + return curry(fn, *all_args, **all_kwargs) + return wrapper + + +def summary(a, b, c, d): + return a + b + c + d + + +if __name__ == '__main__': + + f = curry(summary) + + y1 = f(1, 2, 3, 4) + y2 = f(1, 2, 3)(4) + y3 = f(1, 2)(3)(4) + y4 = f(1)(2)(3)(4) + y5 = f(1)(2, 3, 4) + y6 = f(1)(2)(3, 4) + y7 = f(1, 2)(3, 4) + + print(y1, y2, y3, y4, y5, y6, y7)