def optional(self) -> None: a = 'a' b = 'b' Right(a).to_maybe.should.just_contain(a) Left(a).to_maybe.should.be.a(Empty) Right(a).to_either(b).should.equal(Right(a)) Left(a).to_either(b).should.equal(Left(a))
def map(self) -> None: a = 'a' b = 'b' Right(a).map(_ + b).value.should.equal(a + b) Left(a).map(_ + b).value.should.equal(a)
def f(z: int, a: int) -> Either[str, int]: return Right(z + a) if a < 5 else Left('too large')
def traverse(self) -> None: a = 'a' Right(Just(a)).sequence(Maybe).should.equal(Just(Right(a))) Left(Just(a)).sequence(Maybe).should.equal(Just(Left(Just(a)))) List(Right(a)).sequence(Either).should.equal(Right(List(a))) List(Right(a), Left(a)).sequence(Either).should.equal(Left(a))
def flat_e(self, l, r): return call_by_name(r) if self else Left(call_by_name(l))
def flat_either_call(self, l, r): return r() if self else Left(l)
def e(self, l, r): return Right(call_by_name(r)) if self else Left(call_by_name(l))
def list_flat_map(self) -> None: (List(Right(1), Left(2), Right(3)).join).should.equal(List(1, 3))
def either_call(self, l, r): return Right(r()) if self else Left(l)
def to_either(self, fa: Maybe[A], left: Union[B, Callable[[], B]]) -> either.Either[A, B]: from amino.either import Left, Right return fa.cata(Right, lambda: Left(call_by_name(left)))
def e(self, f: A, t: B) -> Either[A, B]: return Right(call_by_name(t)) if self else Left(call_by_name(f))
def filter(self, fa: Either[A, B], f: Callable[[B], bool]) -> Either[Any, B]: return fa // (lambda a: Right(a) if f(a) else Left('filtered'))
def traverse(self, fa: Either[A, B], f: Callable, tpe: type) -> Any: monad = Applicative.fatal(tpe) r = lambda a: monad.map(f(a), Right) return fa.cata(lambda a: monad.pure(Left(a)), r)
def absent(self, msg: str) -> Either[str, B]: return Left(msg or 'not found')