some more on parser

This commit is contained in:
Ruediger Ludwig 2022-12-07 20:52:42 +01:00
parent b711075a30
commit 82c7745b47

View file

@ -63,18 +63,11 @@ class P(Generic[T]):
@staticmethod @staticmethod
def pure(value: T) -> P[T]: def pure(value: T) -> P[T]:
def inner(parserPos: ParserInput) -> ParserResult[T]: return P(lambda pp: iter([(pp, value)]))
yield (parserPos, value)
return P(inner)
@staticmethod @staticmethod
def fail() -> P[Any]: def fail() -> P[Any]:
def inner(_: ParserInput) -> ParserResult[Any]: return P(lambda _: iter([]))
if False:
yield
pass
return P(inner)
@staticmethod @staticmethod
def _fix(p1: Callable[[P[Any]], P[T]]) -> P[T]: def _fix(p1: Callable[[P[Any]], P[T]]) -> P[T]:
@ -97,12 +90,14 @@ class P(Generic[T]):
return P(inner) return P(inner)
def safe_fmap(self, map_func: Callable[[T], TR]) -> P[TR]: def safe_fmap(self, map_func: Callable[[T], TR]) -> P[TR]:
def inner(value: T) -> P[TR]: def inner(parserPos: ParserInput) -> ParserResult[TR]:
for pp, v in self.func(parserPos):
try: try:
return P.pure(map_func(value)) yield pp, map_func(v)
except Exception: except Exception:
return P.fail() pass
return self.bind(inner)
return P(inner)
def replace(self, value: TR) -> P[TR]: def replace(self, value: TR) -> P[TR]:
return self.fmap(lambda _: value) return self.fmap(lambda _: value)