fptools.either

class pythonic_fp.fptools.either.Either(value: L, side: Truth)
class pythonic_fp.fptools.either.Either(value: R, side: Lie)

Either monad, data structure semantically containing either a left or a right value, but not both.

Implements a left biased Either Monad.

  • Either(value: +L, LEFT) produces a left Either

  • Either(value: +L, RIGHT) produces a right Either

In a Boolean context

  • True if a left Either

  • False if a right Either

Two Either objects compare as equal when

  • both are left values or both are right values whose values

    • are the same object

    • compare as equal

Immutable, an Either does not change after being created. Therefore map & bind return new instances

Warning

The contained value need not be immutable, therefore not hashable if value is mutable.

Note

Either(value: +L, side: Left): Either[+L, +R] -> left: Either[+L, +R] Either(value: +R, side: Right): Either[+L, +R] -> right: Either[+L, +R]

bind(f: Callable[[L], Either[U, R]]) Either[U, R]

Flatmap over the left value, propagate right values.

bind_except(f: Callable[[L], Either[U, R]], fallback_right: R) Either[U, R]

Flatmap Either with function f with fallback right

Warning

Swallows exceptions.

Parameters:

fallback_right – fallback value if exception thrown

get() L | Never

Get value if a left.

Warning

Unsafe method get. Will raise ValueError if Either is a right. Best practice is to first check the Either in a boolean context.

Returns:

its value if a Left

Return type:

+L

Raises:

ValueError – if not a left

get_left() MayBe[L]

Get value of Either if a left. Safer version of get method.

  • if Either contains a left value, return it wrapped in a MayBe

  • if Either contains a right value, return MayBe()

get_right() MayBe[R]

Get value of Either if a right

  • if Either contains a right value, return it wrapped in a MayBe

  • if Either contains a left value, return MayBe()

map(f: Callable[[L], U]) Either[U, R]

Map over if a left value. Return new instance.

map_except(f: Callable[[L], U], fallback_right: R) Either[U, R]

Map over if a left value - with fallback upon exception.

  • if Either is a left then map f over its value

    • if f successful return a left Either[+U, +R]

    • if f unsuccessful return right Either[+U, +R]

      • swallows many exceptions f may throw at run time

  • if Either is a right

    • return new Either(right=self._right): Either[+U, +R]

map_right(f: Callable[[R], V]) Either[L, V]

Construct new Either with a different right.

static sequence(sequence_xor_uv: Sequence[Either]) Either[Sequence, V]

Sequence an indexable of type Either[~U, ~V]

If the iterated Either values are all lefts, then return an Either of an iterable of the left values. Otherwise return a right Either containing the first right encountered.