The Try Monad¶
smonad.types.ftry - The Try Monad.
-
class
smonad.types.ftry.Failure(value)[source]¶ Bases:
smonad.types.ftry.TryFailure of
Try.
-
class
smonad.types.ftry.Success(value)[source]¶ Bases:
smonad.types.ftry.TrySuccess of
Try.
-
class
smonad.types.ftry.Try(value)[source]¶ Bases:
smonad.types.monad.Monad,smonad.mixins.ContextManager,smonad.mixins.OrdThe Either Monad by a different name
Represents values/computations with two possibilities.
>>> Success(42) Success(42) >>> Success([1, 2, 3]) Success([1, 2, 3]) >>> Failure('Error') Failure('Error') >>> Success(Failure('Error')) Success(Failure('Error')) >>> isinstance(Success(1), Try) True >>> isinstance(Failure(None), Try) True >>> saving = 100 >>> broke = Failure('I am broke') >>> spend = lambda cost: broke if cost > saving else Success(saving - cost) >>> spend(90) Success(10) >>> spend(120) Failure('I am broke') >>> safe_div = lambda a, b: Failure(str(a) + '/0') if b == 0 else Success(a / b) >>> safe_div(12.0, 6) Success(2.0) >>> safe_div(12.0, 0) Failure('12.0/0')
Bind operation with
>>>>> inc = lambda n: Success(n + 1) if type(n) is int else Failure('Type error') >>> Success(0) Success(0) >>> Success(0) >> inc Success(1) >>> Success(0) >> inc >> inc Success(2) >>> Success('zero') >> inc Failure('Type error')
Comparison with
==, as long as they are the same type and what’s wrapped inside are comparable.>>> Failure(42) == Failure(42) True >>> Success(42) == Success(42) True >>> Failure(42) == Success(42) False
A
Failureis less than aSuccess, or compare the two by the values inside if thay are of the same type.>>> Failure(42) < Success(42) True >>> Success(0) > Failure(100) True >>> Failure('Error message') > Success(42) False >>> Failure(100) > Failure(42) True >>> Success(-2) < Success(-1) True
-
bind(function)[source]¶ The bind operation of
Try.Applies function to the value if and only if this is a
Success.
-
match(failure_handler, right_handler=None)[source]¶ Given two mapping functions (one from an Failure to a value, one from a Success to a Value), unwrap the value stored in this Try, apply the appropriate mapping function, and return the result.
If the right_handler is None and self is an instance of Success, the wrapped value is returned
-
recover(recovery_fn)[source]¶ “Recover” from a left value by applying a recovery_fn to the wrapped value and returning it in the case of a left value; otherwise, return the wrapped right value.
-
unit= <smonad.types.monadic.Monadic object>¶
-