Advertisement
HasteBin0

Python 3.10+ Two Function Complete Monad Library! V2!

Sep 18th, 2023
3,016
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 2.26 KB | Software | 0 0
  1. # Python 3.10+ Two Function Complete Monad Library! :: https://pastebin.com/JP0tdf4s  #python #python3 #mod #monad
  2.  
  3.  
  4. # py_struct = NamedTuple
  5. class CompareResult(py_struct):
  6.     les: bool
  7.     equ: bool
  8.     gtr: bool
  9.  
  10.  
  11. cmp_str_input_t = NewType('cmp_str_input_t', Iterable[SupportsBytes and SupportsIndex and SupportsInt])
  12.  
  13.  
  14. def cmp_iter_str(si1: cmp_str_input_t, si2: cmp_str_input_t) -> CompareResult:
  15.     it1 = iter(si1)
  16.     it2 = iter(si2)
  17.     while True:
  18.         c1 = next(it1, None)
  19.         c2 = next(it2, None)
  20.         n1 = c1 is None
  21.         n2 = c2 is None
  22.         if n1 and n2:
  23.             return CompareResult(False, True, False)
  24.         elif n1 ^ n2:
  25.             return CompareResult(n1, False, n2)
  26.         elif c1 != c2:
  27.             return CompareResult(c1 < c2, False, c1 > c2)
  28.  
  29.  
  30. class monad_attr_err_spec_t(py_struct):
  31.     obj_type: Type[Any]
  32.     attr_name: str
  33.     fxn_triggered: callable
  34.  
  35.  
  36. def monad(call_function: callable, *op_types: monad_attr_err_spec_t, pass_types: bool = False) -> callable:
  37.     def _i(*args, **kwargs):
  38.         try:
  39.             if pass_types:
  40.                 return call_function(*args, op_types = op_types, **kwargs)
  41.             return call_function(*args, **kwargs)
  42.         except AttributeError as attr_err:  # https://docs.python.org/3.11/library/exceptions.html#AttributeError
  43.             if attr_err.obj is None:
  44.                 return
  45.             ae_obj, ae_name = attr_err.obj, attr_err.name  # Changed in version 3.10: Added the name and obj attributes.
  46.             x: monad_attr_err_spec_t
  47.             for x in op_types:
  48.                 if x.obj_type is type(ae_obj) and ae_name == x.attr_name:
  49.                     return x.fxn_triggered(*args, ae_obj = ae_obj, ae_name = ae_name, **kwargs)
  50.    
  51.     return _i
  52.  
  53.  
  54. py_curry_fxn_arg_t = TypeVar('py_curry_fxn_arg_t')
  55. py_curry_fxn_closure_t = NewType('py_curry_fxn_closure_t', Callable[[py_curry_fxn_arg_t, ...], py_curry_fxn_arg_t])
  56.  
  57.  
  58. def py_curry(fxn: py_curry_fxn_closure_t, *args: py_curry_fxn_arg_t, **kwargs: py_curry_fxn_arg_t) -> py_curry_fxn_closure_t:  # Keep It Simple, Stupid!
  59.     return lambda *args2, **kwargs2: fxn(*args, *args2, **kwargs, **kwargs2)  # pass new args2 after old (earlier curried) args and update (earlier) kwargs with kwargs2.
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement