The Either Monad¶
monad.types.either - The Either Monad.
- class monad.types.either.Either(value)[source]¶
Bases: monad.types.monad.Monad, monad.mixins.ContextManager, monad.mixins.Ord
The Either Monad.
Represents values/computations with two possibilities.
>>> Right(42) Right(42) >>> Right([1, 2, 3]) Right([1, 2, 3]) >>> Left('Error') Left('Error') >>> Right(Left('Error')) Right(Left('Error')) >>> isinstance(Right(1), Either) True >>> isinstance(Left(None), Either) True >>> saving = 100 >>> broke = Left('I am broke') >>> spend = lambda cost: broke if cost > saving else Right(saving - cost) >>> spend(90) Right(10) >>> spend(120) Left('I am broke') >>> safe_div = lambda a, b: Left(str(a) + '/0') if b == 0 else Right(a / b) >>> safe_div(12.0, 6) Right(2.0) >>> safe_div(12.0, 0) Left('12.0/0')
Bind operation with >>
>>> inc = lambda n: Right(n + 1) if type(n) is int else Left('Type error') >>> Right(0) Right(0) >>> Right(0) >> inc Right(1) >>> Right(0) >> inc >> inc Right(2) >>> Right('zero') >> inc Left('Type error')
Comparison with ==, as long as they are the same type and what’s wrapped inside are comparable.
>>> Left(42) == Left(42) True >>> Right(42) == Right(42) True >>> Left(42) == Right(42) False
A Left is less than a Right, or compare the two by the values inside if thay are of the same type.
>>> Left(42) < Right(42) True >>> Right(0) > Left(100) True >>> Left('Error message') > Right(42) False >>> Left(100) > Left(42) True >>> Right(-2) < Right(-1) True
- bind(function)[source]¶
The bind operation of Either.
Applies function to the value if and only if this is a Right.
- unit = <monad.types.monadic.Monadic object at 0x7ff2a08c4f50>¶
- class monad.types.either.Left(value)[source]¶
Bases: monad.types.either.Either
Left of Either.
- class monad.types.either.Right(value)[source]¶
Bases: monad.types.either.Either
Right of Either.