-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmonads.py
More file actions
27 lines (19 loc) · 799 Bytes
/
monads.py
File metadata and controls
27 lines (19 loc) · 799 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
from typing import Callable, Tuple, Any, TypeVar, Generic
ST = TypeVar('ST') # State type
class StateMonad(Generic[ST]):
def __init__(self, run: Callable[[ST], Tuple[Any, ST]]):
self.run = run
def then(self, action: Callable[[Any], 'StateMonad[ST]']) -> 'StateMonad[ST]':
def _run_state(state):
result, new_state = self.run(state)
monad = action(result)
return monad.run(new_state)
return StateMonad(_run_state)
@staticmethod
def get() -> 'StateMonad[ST]':
def _get(state: ST) -> tuple[ST, ST]:
return (state, state)
return StateMonad(_get)
@staticmethod
def modify(func: Callable[['ST'], 'ST']) -> 'StateMonad[ST]':
return StateMonad(lambda state: (None, func(state)))