monadspy 1.0.2__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,37 @@
1
+ from typing import TypeVar, Callable
2
+
3
+ I = TypeVar("I")
4
+ O = TypeVar("O")
5
+
6
+ Function = Callable[[I], O]
7
+ """
8
+ Represents a function that takes an input of type `I` and returns an output of type `O`.
9
+
10
+ Example:
11
+ def square(x: int) -> int:
12
+ return x * x
13
+
14
+ f: Function[int, int] = square
15
+ """
16
+
17
+ Predicate = Callable[[I], bool]
18
+ """
19
+ Represents a boolean-valued function (predicate) that takes an input of type `I`.
20
+
21
+ Example:
22
+ def is_even(x: int) -> bool:
23
+ return x % 2 == 0
24
+
25
+ p: Predicate[int] = is_even
26
+ """
27
+
28
+ Supplier = Callable[[], I]
29
+ """
30
+ Represents a function that takes no arguments and supplies a value of type `I`.
31
+
32
+ Example:
33
+ def supply_five() -> int:
34
+ return 5
35
+
36
+ s: Supplier[int] = supply_five
37
+ """
monads/monad.py ADDED
@@ -0,0 +1,139 @@
1
+ from abc import ABC, abstractmethod
2
+ from typing import Generic, Iterable, Self, Iterator, TypeVar
3
+
4
+ from .functional_types import Predicate, Function
5
+
6
+ I = TypeVar('I') # Input value
7
+ O = TypeVar('O') # Output value
8
+ U = TypeVar('U') # Unused value
9
+
10
+
11
+ class Monad(Generic[I], ABC, Iterable[I]):
12
+ """
13
+ Base interface for all monadic structures.
14
+
15
+ A Monad wraps a value and provides a functional API based on:
16
+ - mapping a function over the value
17
+ - chaining computations
18
+ - safe extraction
19
+ - optional filtering
20
+ - iteration over the contained value (0 or 1 element)
21
+
22
+ This interface is inspired by the Scala `Monad` type class and is meant
23
+ to be implemented by concrete monads such as `Option`, `Try`, etc.
24
+ """
25
+
26
+ @abstractmethod
27
+ def for_each(self, fn: Function[I, U]) -> None:
28
+ """
29
+ Applies a function for its side effects to the wrapped value.
30
+
31
+ If the monad contains a value, `fn(value)` is executed.
32
+ If it contains no value (e.g., Nothing, Failure), nothing happens.
33
+
34
+ Equivalent to Scala's `foreach`.
35
+
36
+ Example:
37
+ Option.of(10).for_each(print) # prints 10
38
+ """
39
+ pass
40
+
41
+ @abstractmethod
42
+ def map(self, mapping_fn: Function[I, O]) -> "Monad[O]":
43
+ """
44
+ Transforms the wrapped value using the provided function.
45
+
46
+ - If the monad contains a value -> returns a monad containing mapping_fn(value)
47
+ - If the monad is empty or failed -> returns the same empty/failure monad
48
+
49
+ This operation does NOT flatten nested monads.
50
+
51
+ Example:
52
+ Option.of(10).map(lambda x: x * 2) # Some(20)
53
+ """
54
+ pass
55
+
56
+ @abstractmethod
57
+ def flat_map(self, mapping_fn: Function[I, "Monad[O]"]) -> "Monad[O]":
58
+ """
59
+ Applies a function returning a monad and flattens the result.
60
+
61
+ - Used for chaining monadic operations
62
+ - Behaves like `map` but avoids nested monads (Monad[Monad[T]])
63
+
64
+ Equivalent to Scala's `flatMap`.
65
+
66
+ Example:
67
+ def safe_div(x):
68
+ return Try.of(lambda: 10 / x)
69
+
70
+ Try.of(lambda: 2).flat_map(safe_div) # Success(5)
71
+ """
72
+ pass
73
+
74
+ @abstractmethod
75
+ def get_or_else(self, default: I) -> I:
76
+ """
77
+ Extracts the contained value or returns the provided default.
78
+
79
+ - For monads with a value -> returns the value
80
+ - For empty/failure monads -> returns `default`
81
+
82
+ Example:
83
+ Option.of(None).get_or_else(99) # 99
84
+ """
85
+ pass
86
+
87
+ @abstractmethod
88
+ def or_else(self, default: "Monad[I]") -> "Monad[I]":
89
+ """
90
+ Returns this monad if it contains a value, otherwise returns the fallback monad.
91
+
92
+ - Useful for specifying fallback computations
93
+ - Does not unwrap values
94
+
95
+ Example:
96
+ Option.of(None).or_else(Option.of(5)) # Some(5)
97
+ """
98
+ pass
99
+
100
+ @abstractmethod
101
+ def filter(self, predicate: Predicate[I]) -> "Monad[I]":
102
+ """
103
+ Retains the value only if it satisfies the predicate.
104
+
105
+ - If the monad contains a value and predicate(value) is True → return the monad
106
+ - Otherwise → return an empty/failure monad
107
+
108
+ Example:
109
+ Option.of(10).filter(lambda x: x > 5) # Some(10)
110
+ Option.of(3).filter(lambda x: x > 5) # Nothing
111
+ """
112
+ pass
113
+
114
+ @abstractmethod
115
+ def flatten(self) -> "Monad[I]":
116
+ """
117
+ Removes one level of monadic nesting.
118
+
119
+ - If the monad wraps another monad (e.g., Some(Some(x))) → returns inner monad
120
+ - Otherwise → returns itself
121
+
122
+ Example:
123
+ Option.of(Option.of(10)).flatten() # Some(10)
124
+ """
125
+ pass
126
+
127
+ @abstractmethod
128
+ def __iter__(self) -> Iterator[I]:
129
+ """
130
+ Allows the monad to be iterated over like a container with 0 or 1 element.
131
+
132
+ - Monads with a value → yield that value
133
+ - Empty/failure monads → yield nothing
134
+
135
+ Enables:
136
+ for x in Option.of(10):
137
+ print(x) # prints 10
138
+ """
139
+ pass
monads/option_monad.py ADDED
@@ -0,0 +1,229 @@
1
+ from abc import ABC, abstractmethod
2
+ from typing import Iterator, Callable, Any
3
+
4
+ from monads.functional_types import Predicate, Function
5
+ from monads.monad import Monad, I, O, U
6
+
7
+
8
+ class Option(Monad[I], ABC):
9
+ """
10
+ Represents an optional value: either Some(value) or Nothing.
11
+
12
+ Use `Option.of(value)` to create an Option that is Some if value is not None,
13
+ or Nothing if value is None.
14
+
15
+ This is inspired by Scala's Option monad.
16
+ """
17
+
18
+ @staticmethod
19
+ def of(value: I) -> "Option[I]":
20
+ """
21
+ Creates an Option wrapping the given value.
22
+
23
+ Returns:
24
+ Some(value) if value is not None,
25
+ Nothing if value is None.
26
+ """
27
+ return Nothing if value is None else Some(value)
28
+
29
+ @property
30
+ @abstractmethod
31
+ def is_empty(self) -> bool:
32
+ """
33
+ Returns True if this Option is empty (Nothing).
34
+ """
35
+ pass
36
+
37
+ @property
38
+ @abstractmethod
39
+ def is_defined(self) -> bool:
40
+ """
41
+ Returns True if this Option contains a value (Some).
42
+ """
43
+ pass
44
+
45
+ @abstractmethod
46
+ def fold(self, default: O, mapping_fn: Function[I, O]) -> O:
47
+ """
48
+ Extracts a value from this Option by applying one of two cases:
49
+
50
+ - If Some(value), applies `mapping_fn(value)`.
51
+ - If Nothing, returns `default`.
52
+
53
+ Args:
54
+ default: The fallback value if empty.
55
+ mapping_fn: Function to apply if value is present.
56
+
57
+ Returns:
58
+ Result of type O.
59
+ """
60
+ pass
61
+
62
+
63
+ class Some(Option[I]):
64
+ """
65
+ Represents an Option containing a non-None value.
66
+ """
67
+
68
+ def __init__(self, value: I):
69
+ if value is None:
70
+ raise ValueError("value cannot be None")
71
+ self._value: I = value
72
+
73
+ @property
74
+ def is_empty(self) -> bool:
75
+ return False
76
+
77
+ @property
78
+ def is_defined(self) -> bool:
79
+ return True
80
+
81
+ def for_each(self, fn: Function[I, U]) -> None:
82
+ """
83
+ Applies `fn` for side effects on the contained value.
84
+ """
85
+ fn(self._value)
86
+
87
+ def flatten(self) -> "Option[I]":
88
+ """
89
+ If the contained value is itself an Option, returns it (flatten one level).
90
+ Otherwise returns self.
91
+ """
92
+ return self._value if isinstance(self._value, Option) else self
93
+
94
+ def map(self, mapping_fn: Function[I, O]) -> "Option[O]":
95
+ """
96
+ Transforms the contained value using `mapping_fn`, returning an Option.
97
+ """
98
+ return Option.of(mapping_fn(self._value))
99
+
100
+ def flat_map(self, mapping_fn: Function[I, "Option[O]"]) -> "Option[O]":
101
+ """
102
+ Applies a function returning an Option to the contained value, flattening the result.
103
+ """
104
+ return mapping_fn(self._value)
105
+
106
+ def get_or_else(self, default: I) -> I:
107
+ """
108
+ Returns the contained value.
109
+ """
110
+ return self._value
111
+
112
+ def or_else(self, default: "Option[I]") -> "Option[I]":
113
+ """
114
+ Returns self, ignoring the provided default Option.
115
+ """
116
+ return self
117
+
118
+ def fold(self, default: O, mapping_fn: Function[I, O]) -> O:
119
+ """
120
+ Applies `mapping_fn` to the contained value.
121
+ """
122
+ return mapping_fn(self._value)
123
+
124
+ def filter(self, predicate: Predicate[I]) -> "Option[I]":
125
+ """
126
+ Returns self if the predicate holds for the value, otherwise Nothing.
127
+ """
128
+ return self if predicate(self._value) else Nothing
129
+
130
+ def __iter__(self) -> Iterator[I]:
131
+ """
132
+ Iterates over the contained value.
133
+ """
134
+ yield self._value
135
+
136
+
137
+ class _Nothing(Option[None]):
138
+ """
139
+ Represents an empty Option (no value).
140
+ """
141
+
142
+ @property
143
+ def is_empty(self) -> bool:
144
+ return True
145
+
146
+ @property
147
+ def is_defined(self) -> bool:
148
+ return False
149
+
150
+ def for_each(self, fn: Function[I, U]) -> None:
151
+ """
152
+ Does nothing because there is no value.
153
+ """
154
+ return
155
+
156
+ def map(self, mapping_fn: Function[I, O]) -> "_Nothing":
157
+ """
158
+ Returns Nothing unchanged.
159
+ """
160
+ return Nothing
161
+
162
+ def flatten(self) -> "Option[I]":
163
+ """
164
+ Returns Nothing unchanged.
165
+ """
166
+ return Nothing
167
+
168
+ def flat_map(self, mapping_fn: Function[I, "Option[O]"]) -> "Option[I]":
169
+ """
170
+ Returns Nothing unchanged.
171
+ """
172
+ return Nothing
173
+
174
+ def get_or_else(self, default: I) -> I:
175
+ """
176
+ Returns the provided default value.
177
+ """
178
+ return default
179
+
180
+ def or_else(self, default: "Option[I]") -> "Option[I]":
181
+ """
182
+ Returns the provided fallback Option.
183
+ """
184
+ return default
185
+
186
+ def fold(self, default: O, mapping_fn: Function[I, O]) -> O:
187
+ """
188
+ Returns the default value.
189
+ """
190
+ return default
191
+
192
+ def filter(self, predicate: Predicate[I]) -> "Option[I]":
193
+ """
194
+ Returns Nothing unchanged.
195
+ """
196
+ return Nothing
197
+
198
+ def __iter__(self) -> Iterator[I]:
199
+ """
200
+ Yields nothing because there is no value.
201
+ """
202
+ return iter([])
203
+
204
+
205
+ Nothing = _Nothing()
206
+
207
+
208
+ def to_option(fn: Callable[..., Any]) -> Callable[..., "Option[Any]"]:
209
+ """
210
+ Decorator that wraps a function's return value into an Option.
211
+
212
+ Usage:
213
+
214
+ @to_option
215
+ def maybe_get_value():
216
+ # returns a value or None
217
+ return compute_something()
218
+
219
+ maybe_get_value() # Some(value) or Nothing
220
+
221
+ Args:
222
+ fn: The function to wrap.
223
+
224
+ Returns:
225
+ A function returning Option wrapping the original function's output.
226
+ """
227
+ def wrapper(*args, **kwargs) -> "Option[Any]":
228
+ return Option.of(fn(*args, **kwargs))
229
+ return wrapper
monads/try_monad.py ADDED
@@ -0,0 +1,271 @@
1
+ from abc import ABC, abstractmethod
2
+ from typing import Iterator, Self, Callable, Any
3
+
4
+ from monads.functional_types import Predicate, Function, O
5
+ from .functional_types import Supplier
6
+ from .monad import Monad, I, O, U
7
+ from .option_monad import Option, Nothing
8
+
9
+
10
+ class Try(Monad[I], ABC):
11
+ """
12
+ Monad representing a computation that may either result in a value (Success)
13
+ or an exception (Failure).
14
+
15
+ Use `Try.of(supplier)` to safely execute a computation and capture exceptions.
16
+
17
+ This is inspired by Scala's `Try` monad.
18
+ """
19
+
20
+ @staticmethod
21
+ def of(supplier: Supplier[I]) -> "Try[I]":
22
+ """
23
+ Executes the given supplier function and wraps the result in a Try.
24
+
25
+ - If the function executes without raising an exception, returns Success(value).
26
+ - If an exception is raised, returns Failure(exception).
27
+
28
+ Args:
29
+ supplier: A no-argument callable that produces a value of type I.
30
+
31
+ Returns:
32
+ Try[I]: Success or Failure.
33
+ """
34
+ try:
35
+ return Success(supplier())
36
+ except Exception as e:
37
+ return Failure(e)
38
+
39
+ @property
40
+ @abstractmethod
41
+ def is_success(self) -> bool:
42
+ """
43
+ Returns True if this Try is a Success.
44
+ """
45
+ pass
46
+
47
+ @property
48
+ @abstractmethod
49
+ def is_failure(self) -> bool:
50
+ """
51
+ Returns True if this Try is a Failure.
52
+
53
+ """
54
+ pass
55
+
56
+ @abstractmethod
57
+ def fold(self, default: Function[Exception, O], mapping_fn: Function[I, O]) -> O:
58
+ """
59
+ Extracts a value from this Try by applying one of two functions:
60
+
61
+ - If Success, applies `mapping_fn` to the contained value.
62
+ - If Failure, applies `default` to the exception.
63
+
64
+ Args:
65
+ default: Function to handle exceptions.
66
+ mapping_fn: Function to handle the successful value.
67
+
68
+ Returns:
69
+ O: Result of either function.
70
+ """
71
+ pass
72
+
73
+ @abstractmethod
74
+ def to_option(self) -> Option[I]:
75
+ """
76
+ Converts this Try into an Option:
77
+
78
+ - Success(value) -> Some(value)
79
+ - Failure(_) -> Nothing
80
+
81
+ Returns:
82
+ Option[I]
83
+ """
84
+ pass
85
+
86
+
87
+ class Success(Try[I]):
88
+ """
89
+ Represents a successful computation containing a value.
90
+ """
91
+
92
+ def __init__(self, value: I):
93
+ self._value: I = value
94
+
95
+ @property
96
+ def is_success(self) -> bool:
97
+ return True
98
+
99
+ @property
100
+ def is_failure(self) -> bool:
101
+ return False
102
+
103
+ def for_each(self, fn: Function[I, U]) -> None:
104
+ """
105
+ Executes `fn` for side effects on the contained value.
106
+ """
107
+ fn(self._value)
108
+
109
+ def map(self, mapping_fn: Function[I, O]) -> Try[O]:
110
+ """
111
+ Transforms the contained value using `mapping_fn`, returning a new Try.
112
+ """
113
+ return Try.of(lambda: mapping_fn(self._value))
114
+
115
+ def flatten(self) -> Try[I]:
116
+ """
117
+ If the contained value is itself a Try, returns it to remove nesting.
118
+ Otherwise, returns self.
119
+ """
120
+ return self._value if isinstance(self._value, Try) else self
121
+
122
+ def flat_map(self, mapping_fn: Function[I, Try[O]]) -> Try[O]:
123
+ """
124
+ Applies a function returning a Try to the contained value, flattening the result.
125
+ """
126
+ try:
127
+ return mapping_fn(self._value)
128
+ except Exception as e:
129
+ return Failure(e)
130
+
131
+ def get_or_else(self, default: I) -> I:
132
+ """
133
+ Returns the contained value.
134
+ """
135
+ return self._value
136
+
137
+ def or_else(self, default: Try[I]) -> Try[I]:
138
+ """
139
+ Returns self, ignoring the provided default.
140
+ """
141
+ return self
142
+
143
+ def fold(self, default: Function[Exception, O], mapping_fn: Function[I, O]) -> O:
144
+ """
145
+ Applies `mapping_fn` to the contained value.
146
+ """
147
+ return mapping_fn(self._value)
148
+
149
+ def filter(self, predicate: Predicate[I]) -> Try[I]:
150
+ """
151
+ Returns self if predicate(value) is True, otherwise Failure.
152
+ """
153
+ if predicate(self._value):
154
+ return self
155
+ else:
156
+ return Failure(ValueError(f"Predicate does not hold for {self._value!r}"))
157
+
158
+ def to_option(self) -> Option[I]:
159
+ """
160
+ Converts to Some(value).
161
+ """
162
+ return Option.of(self._value)
163
+
164
+ def __iter__(self) -> Iterator[I]:
165
+ """
166
+ Iterates over the contained value.
167
+ """
168
+ yield self._value
169
+
170
+
171
+ class Failure(Try[I]):
172
+ """
173
+ Represents a failed computation containing an Exception.
174
+ """
175
+
176
+ def __init__(self, value: Exception):
177
+ if not isinstance(value, Exception):
178
+ raise ValueError('value must be an Exception')
179
+ self._value: Exception = value
180
+
181
+ @property
182
+ def is_success(self) -> bool:
183
+ return False
184
+
185
+ @property
186
+ def is_failure(self) -> bool:
187
+ return True
188
+
189
+ def for_each(self, fn: Function[I, U]) -> None:
190
+ """
191
+ Does nothing because there is no value.
192
+ """
193
+ return
194
+
195
+ def map(self, mapping_fn: Function[I, O]) -> Try[O]:
196
+ """
197
+ Returns self without applying the mapping function.
198
+ """
199
+ return self
200
+
201
+ def flat_map(self, mapping_fn: Function[I, Try[O]]) -> Try[O]:
202
+ """
203
+ Returns self without applying the flat mapping function.
204
+ """
205
+ return self
206
+
207
+ def get_or_else(self, default: I) -> I:
208
+ """
209
+ Returns the provided default value.
210
+ """
211
+ return default
212
+
213
+ def or_else(self, default: Try[I]) -> Try[I]:
214
+ """
215
+ Returns the provided fallback Try.
216
+ """
217
+ return default
218
+
219
+ def fold(self, default: Function[Exception, O], mapping_fn: Function[I, O]) -> O:
220
+ """
221
+ Applies `default` to the contained exception.
222
+ """
223
+ return default(self._value)
224
+
225
+ def filter(self, predicate: Predicate[I]) -> Try[I]:
226
+ """
227
+ Returns self unchanged because there is no value to filter.
228
+ """
229
+ return self
230
+
231
+ def flatten(self) -> Try[I]:
232
+ """
233
+ Returns self unchanged.
234
+ """
235
+ return self
236
+
237
+ def to_option(self) -> Option[I]:
238
+ """
239
+ Converts to Nothing.
240
+ """
241
+ return Nothing
242
+
243
+ def __iter__(self) -> Iterator[I]:
244
+ """
245
+ Yields nothing because there is no value.
246
+ """
247
+ return iter([])
248
+
249
+
250
+ def to_try(fn: Callable[..., Any]) -> Callable[..., Try[Any]]:
251
+ """
252
+ Decorator that wraps function execution into a Try, capturing exceptions.
253
+
254
+ Usage:
255
+
256
+ @to_try
257
+ def divide(a, b):
258
+ return a / b
259
+
260
+ divide(4, 2) # Success(2.0)
261
+ divide(1, 0) # Failure(ZeroDivisionError)
262
+
263
+ Args:
264
+ fn: The function to wrap.
265
+
266
+ Returns:
267
+ A function that returns a Try wrapping the original function's result or exception.
268
+ """
269
+ def wrapper(*args, **kwargs) -> Try[Any]:
270
+ return Try.of(lambda: fn(*args, **kwargs))
271
+ return wrapper
@@ -0,0 +1,204 @@
1
+ Metadata-Version: 2.4
2
+ Name: monadspy
3
+ Version: 1.0.2
4
+ Summary: Option and Try monads implementation in pure Python code
5
+ Requires-Python: >=3.14
6
+ Description-Content-Type: text/markdown
7
+ License-File: LICENSE
8
+ Dynamic: license-file
9
+
10
+ # Option and Try Monads for Python
11
+ Functional programming utilities inspired by Scala.
12
+
13
+ ---
14
+
15
+ # Option Monad
16
+
17
+ `Option` represents a value that may or may not exist.
18
+
19
+ - `Some(value)` — a present value
20
+ - `Nothing` — absence of a value
21
+
22
+ This eliminates manual `None` checks and enables functional pipelines.
23
+
24
+ ## Creating Options
25
+
26
+ ```python
27
+ Option.of(10) # Some(10)
28
+ Option.of(None) # Nothing
29
+ ```
30
+
31
+ ## Properties
32
+
33
+ | Property | Some | Nothing |
34
+ |----------|------|---------|
35
+ | `is_defined` | True | False |
36
+ | `is_empty` | False | True |
37
+
38
+ ## Methods
39
+
40
+ ### `map(fn)`
41
+ Transforms the wrapped value if present.
42
+
43
+ ```python
44
+ Option.of(10).map(lambda x: x * 2) # Some(20)
45
+ Option.of(None).map(lambda x: x * 2) # Nothing
46
+ ```
47
+
48
+ ### `flat_map(fn)`
49
+ Chaining operations that return `Option`.
50
+
51
+ ```python
52
+ def safe_div(a, b):
53
+ return Option.of(a / b if b != 0 else None)
54
+
55
+ Option.of(10).flat_map(lambda x: safe_div(x, 2)) # Some(5)
56
+ ```
57
+
58
+ ### `filter(predicate)`
59
+ Keeps the value only if it satisfies the predicate.
60
+
61
+ ```python
62
+ Option.of(10).filter(lambda x: x > 5) # Some(10)
63
+ Option.of(3).filter(lambda x: x > 5) # Nothing
64
+ ```
65
+
66
+ ### `get_or_else(default)`
67
+ ```python
68
+ Option.of(None).get_or_else(99) # 99
69
+ ```
70
+
71
+ ### `fold(default, mapping_fn)`
72
+ Useful for extraction.
73
+
74
+ ```python
75
+ Option.of(20).fold(0, lambda x: x * 2) # 40
76
+ ```
77
+
78
+ ### `or_else(other_option)`
79
+ ```python
80
+ Option.of(None).or_else(Option.of(5)) # Some(5)
81
+ ```
82
+
83
+ ### `flatten()`
84
+ ```python
85
+ Option.of(Option.of(10)).flatten() # Some(10)
86
+ ```
87
+
88
+ ### Iteration
89
+ ```python
90
+ for value in Option.of(10):
91
+ print(value) # 10
92
+ ```
93
+
94
+ ## Decorator: `@to_option`
95
+
96
+ Converts function output into `Option`.
97
+
98
+ ```python
99
+ @to_option
100
+ def compute(x):
101
+ return x * 2
102
+
103
+ compute(10) # Some(20)
104
+ ```
105
+
106
+ ---
107
+
108
+ # Try Monad
109
+
110
+ `Try` models computations that may throw exceptions.
111
+
112
+ - `Success(value)`
113
+ - `Failure(exception)`
114
+
115
+ It removes the need for `try/except` in functional code.
116
+
117
+ ## Creating Try Values
118
+
119
+ ```python
120
+ Try.of(lambda: 10 / 2) # Success(5.0)
121
+ Try.of(lambda: 10 / 0) # Failure(ZeroDivisionError)
122
+ ```
123
+
124
+ ## Properties
125
+
126
+ | Property | Success | Failure |
127
+ |----------|---------|---------|
128
+ | `is_success` | True | False |
129
+ | `is_failure` | False | True |
130
+
131
+ ## Methods
132
+
133
+ ### `map(fn)`
134
+ Only applied if successful.
135
+
136
+ ```python
137
+ Try.of(lambda: 5).map(lambda x: x + 1) # Success(6)
138
+ Try.of(lambda: 1/0).map(lambda x: x + 1) # Failure(...)
139
+ ```
140
+
141
+ ### `flat_map(fn)`
142
+ Chaining computations that return `Try`.
143
+
144
+ ```python
145
+ def parse_int(s: str):
146
+ return Try.of(lambda: int(s))
147
+
148
+ Try.of(lambda: "123").flat_map(parse_int) # Success(123)
149
+ ```
150
+
151
+ ### `filter(predicate)`
152
+ ```python
153
+ Try.of(lambda: 10).filter(lambda x: x > 5) # Success(10)
154
+ Try.of(lambda: 3).filter(lambda x: x > 5) # Failure(ValueError)
155
+ ```
156
+
157
+ ### `get_or_else(default)`
158
+ ```python
159
+ Try.of(lambda: 10/0).get_or_else(99) # 99
160
+ ```
161
+
162
+ ### `or_else(default_try)`
163
+ ```python
164
+ Try.of(lambda: 10/0).or_else(Success(5)) # Success(5)
165
+ ```
166
+
167
+ ### `fold(default_fn, mapping_fn)`
168
+ ```python
169
+ Try.of(lambda: 10 / 0).fold(
170
+ default=lambda ex: f"Error: {ex}",
171
+ mapping_fn=lambda x: x * 2
172
+ )
173
+ # "Error: division by zero"
174
+ ```
175
+
176
+ ### `flatten()`
177
+ ```python
178
+ Try.of(lambda: Success(10)).flatten() # Success(10)
179
+ ```
180
+
181
+ ### Converting to Option
182
+ ```python
183
+ Try.of(lambda: 10).to_option() # Some(10)
184
+ Try.of(lambda: 1/0).to_option() # Nothing
185
+ ```
186
+
187
+ ### Iteration
188
+ ```python
189
+ for v in Try.of(lambda: 10):
190
+ print(v)
191
+ ```
192
+
193
+ ## Decorator: `@to_try`
194
+
195
+ Automatically wraps exceptions into a `Try`.
196
+
197
+ ```python
198
+ @to_try
199
+ def divide(a, b):
200
+ return a / b
201
+
202
+ divide(10, 2) # Success(5.0)
203
+ divide(10, 0) # Failure(ZeroDivisionError)
204
+ ```
@@ -0,0 +1,9 @@
1
+ monads/functional_types.py,sha256=PQ7aHAJiJJaukNNdu_JVBcMXjjtvUNW3h8H0xmVp-m0,730
2
+ monads/monad.py,sha256=kHpDxSybmzXfhH1fPVt5s3OcylSvGm67ou1aEMPF5A4,4101
3
+ monads/option_monad.py,sha256=1PpDMxd7Czao97Onm3GXMVYysebgqwTN-EkrpPP0SiE,5755
4
+ monads/try_monad.py,sha256=vSI8ceAFbPHfcuocv_KOoFPpA81pGcslg7Ac_OT8qM8,7022
5
+ monadspy-1.0.2.dist-info/licenses/LICENSE,sha256=xx0jnfkXJvxRnG63LTGOxlggYnIysveWIZ6H3PNdCrQ,11357
6
+ monadspy-1.0.2.dist-info/METADATA,sha256=QAnxJiQ4SxNzXTObmr3bQnmLRxOyLT3WeKcnG9Ua-qo,3786
7
+ monadspy-1.0.2.dist-info/WHEEL,sha256=_zCd3N1l69ArxyTb8rzEoP9TpbYXkqRFSNOD5OuxnTs,91
8
+ monadspy-1.0.2.dist-info/top_level.txt,sha256=R2DeUjfIvNDKrSjJ8KdqWKx85tLqF2EO8BfNfatKkWQ,7
9
+ monadspy-1.0.2.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (80.9.0)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
@@ -0,0 +1 @@
1
+ monads