From 8092d46899d4b75d4f36f13c7eea2ac62f4d599f Mon Sep 17 00:00:00 2001 From: Andrey Nikiforov Date: Thu, 10 Oct 2024 09:12:56 -0700 Subject: [PATCH] add flip, compact2, expand2, pipe2 --- src/foundation/core/__init__.py | 47 +++++++++++++++++++++++++++++++++ 1 file changed, 47 insertions(+) diff --git a/src/foundation/core/__init__.py b/src/foundation/core/__init__.py index efc2f980d..912cb59f8 100644 --- a/src/foundation/core/__init__.py +++ b/src/foundation/core/__init__.py @@ -144,3 +144,50 @@ def snd(t: Tuple[_Tin, _Tin2]) -> _Tin2: True """ return t[1] + + +def flip(func: Callable[[_Tin, _Tin2], _Tout]) -> Callable[[_Tin2, _Tin], _Tout]: + """flips params + >>> def minus(a: int, b: int) -> int: + ... return a - b + >>> minus(5, 3) == 2 + True + >>> flip(minus)(5, 3) == -2 + True + """ + + def _intern(input2: _Tin2, input: _Tin) -> _Tout: + return func(input, input2) + + return _intern + + +def compact2(func: Callable[[_Tin, _Tin2], _Tout]) -> Callable[[Tuple[_Tin, _Tin2]], _Tout]: + """Compacts two parameters into one tuple""" + + def _intern(input: Tuple[_Tin, _Tin2]) -> _Tout: + return func(fst(input), snd(input)) + + return _intern + + +def expand2(func: Callable[[Tuple[_Tin, _Tin2]], _Tout]) -> Callable[[_Tin, _Tin2], _Tout]: + def _intern(input: _Tin, input2: _Tin2) -> _Tout: + return func((input, input2)) + + return _intern + + +def pipe2( + f: Callable[[_Tin, _Tin2], _Tinter], g: Callable[[_Tinter], _Tout] +) -> Callable[[_Tin, _Tin2], _Tout]: + """ + `g after f` composition of functions (reverse of compose). f takes 2 params + >>> def mul(a: int, b: int) -> int: + ... return a * b + >>> def add5(a: int) -> int: + ... return a + 5 + >>> pipe2(mul, add5)(2, 3) == 11 + True + """ + return expand2(pipe(compact2(f), g))