The Maybe Monad¶
monad.types.maybe - The Maybe Monad.
-
monad.types.maybe.
Just
¶ alias of
monad.types.maybe.Maybe
-
class
monad.types.maybe.
Maybe
(value)[source]¶ Bases:
monad.types.monadplus.MonadPlus
,monad.mixins.ContextManager
,monad.mixins.Ord
The Maybe Monad.
Representing values/computations that may fail.
>>> Just(42) Just(42) >>> Just([1, 2, 3]) Just([1, 2, 3]) >>> Just(Nothing) Just(Nothing) >>> Just(Just(2)) Just(Just(2)) >>> isinstance(Just(1), Maybe) True >>> isinstance(Nothing, Maybe) True >>> saving = 100 >>> spend = lambda cost: Nothing if cost > saving else Just(saving - cost) >>> spend(90) Just(10) >>> spend(120) Nothing >>> safe_div = lambda a, b: Nothing if b == 0 else Just(a / b) >>> safe_div(12.0, 6) Just(2.0) >>> safe_div(12.0, 0) Nothing
Bind operation with
>>
>>> inc = lambda n: Just(n + 1) if isinstance(n, int) else Nothing >>> Just(0) Just(0) >>> Just(0) >> inc Just(1) >>> Just(0) >> inc >> inc Just(2) >>> Just('zero') >> inc Nothing
Comparison with
==
, as long as what’s wrapped inside are comparable.>>> Just(42) == Just(42) True >>> Just(42) == Nothing False >>> Nothing == Nothing True
-
bind
(function)[source]¶ The bind operation of
Maybe
.Applies function to the value if and only if this is a
Just
.
-