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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# /// script
|
2 |
+
# requires-python = ">=3.9"
|
3 |
+
# dependencies = [
|
4 |
+
# "marimo",
|
5 |
+
# ]
|
6 |
+
# ///
|
7 |
+
|
8 |
+
import marimo
|
9 |
+
|
10 |
+
__generated_with = "0.11.17"
|
11 |
+
app = marimo.App(app_title="Category Theory and Functors", css_file="")
|
12 |
+
|
13 |
+
|
14 |
+
@app.cell(hide_code=True)
|
15 |
+
def _(mo):
|
16 |
+
mo.md(
|
17 |
+
"""
|
18 |
+
# Category Theory and Functors
|
19 |
+
|
20 |
+
In this notebook, you will learn:
|
21 |
+
|
22 |
+
* Why `length` is a *functor* from the category of `list concatenation` to the category of `integer addition`
|
23 |
+
* How to *lift* an ordinary function into a specific *computational context*
|
24 |
+
* How to write an *adapter* between two categories
|
25 |
+
|
26 |
+
In short, a mathematical functor is a **mapping** between two categories in category theory. In practice, a functor represents a type that can be mapped over.
|
27 |
+
|
28 |
+
/// admonition | Intuitions
|
29 |
+
|
30 |
+
- A simple intuition is that a `Functor` represents a **container** of values, along with the ability to apply a function uniformly to every element in the container.
|
31 |
+
- Another intuition is that a `Functor` represents some sort of **computational context**.
|
32 |
+
- Mathematically, `Functors` generalize the idea of a container or a computational context.
|
33 |
+
///
|
34 |
+
|
35 |
+
We will start with intuition, introduce the basics of category theory, and then examine functors from a categorical perspective.
|
36 |
+
|
37 |
+
/// details | Notebook metadata
|
38 |
+
type: info
|
39 |
+
|
40 |
+
version: 0.1.0 | last modified: 2025-03-13 | author: [métaboulie](https://github.com/metaboulie)<br/>
|
41 |
+
reviewer: [Haleshot](https://github.com/Haleshot)
|
42 |
+
|
43 |
+
///
|
44 |
+
"""
|
45 |
+
)
|
46 |
+
return
|
47 |
+
|
48 |
+
|
49 |
+
@app.cell(hide_code=True)
|
50 |
+
def _(mo):
|
51 |
+
mo.md(
|
52 |
+
"""
|
53 |
+
# Functor as a Computational Context
|
54 |
+
|
55 |
+
A [**Functor**](https://wiki.haskell.org/Functor) is an abstraction that represents a computational context with the ability to apply a function to every value inside it without altering the structure of the context itself. This enables transformations while preserving the shape of the data.
|
56 |
+
|
57 |
+
To understand this, let's look at a simple example.
|
58 |
+
|
59 |
+
## [The One-Way Wrapper Design Pattern](http://blog.sigfpe.com/2007/04/trivial-monad.html)
|
60 |
+
|
61 |
+
Often, we need to wrap data in some kind of context. However, when performing operations on wrapped data, we typically have to:
|
62 |
+
|
63 |
+
1. Unwrap the data.
|
64 |
+
2. Modify the unwrapped data.
|
65 |
+
3. Rewrap the modified data.
|
66 |
+
|
67 |
+
This process is tedious and inefficient. Instead, we want to wrap data **once** and apply functions directly to the wrapped data without unwrapping it.
|
68 |
+
|
69 |
+
/// admonition | Rules for a One-Way Wrapper
|
70 |
+
|
71 |
+
1. We can wrap values, but we cannot unwrap them.
|
72 |
+
2. We should still be able to apply transformations to the wrapped data.
|
73 |
+
3. Any operation that depends on wrapped data should itself return a wrapped result.
|
74 |
+
///
|
75 |
+
|
76 |
+
Let's define such a `Wrapper` class:
|
77 |
+
|
78 |
+
```python
|
79 |
+
from dataclasses import dataclass
|
80 |
+
from typing import Callable, Generic, TypeVar
|
81 |
+
|
82 |
+
a = TypeVar("a")
|
83 |
+
b = TypeVar("b")
|
84 |
+
|
85 |
+
@dataclass
|
86 |
+
class Wrapper(Generic[a]):
|
87 |
+
value: a
|
88 |
+
```
|
89 |
+
|
90 |
+
Now, we can create an instance of wrapped data:
|
91 |
+
|
92 |
+
```python
|
93 |
+
wrapped = Wrapper(1)
|
94 |
+
```
|
95 |
+
|
96 |
+
### Mapping Functions Over Wrapped Data
|
97 |
+
|
98 |
+
To modify wrapped data while keeping it wrapped, we define an `fmap` method:
|
99 |
+
|
100 |
+
```python
|
101 |
+
@dataclass
|
102 |
+
class Wrapper(Generic[a]):
|
103 |
+
value: a
|
104 |
+
|
105 |
+
def fmap(self, func: Callable[[a], b]) -> "Wrapper[b]":
|
106 |
+
return Wrapper(func(self.value))
|
107 |
+
```
|
108 |
+
|
109 |
+
Now, we can apply transformations without unwrapping:
|
110 |
+
|
111 |
+
```python
|
112 |
+
>>> wrapped.fmap(lambda x: x + 1)
|
113 |
+
Wrapper(value=2)
|
114 |
+
|
115 |
+
>>> wrapped.fmap(lambda x: [x])
|
116 |
+
Wrapper(value=[1])
|
117 |
+
```
|
118 |
+
|
119 |
+
> Try using the `Wrapper` in the cell below.
|
120 |
+
"""
|
121 |
+
)
|
122 |
+
return
|
123 |
+
|
124 |
+
|
125 |
+
@app.cell
|
126 |
+
def _(Callable, Functor, Generic, a, b, dataclass):
|
127 |
+
@dataclass
|
128 |
+
class Wrapper(Functor, Generic[a]):
|
129 |
+
value: a
|
130 |
+
|
131 |
+
def fmap(self, func: Callable[[a], b]) -> "Wrapper[b]":
|
132 |
+
return Wrapper(func(self.value))
|
133 |
+
|
134 |
+
def __repr__(self):
|
135 |
+
return repr(self.value)
|
136 |
+
|
137 |
+
|
138 |
+
wrapper = Wrapper(1)
|
139 |
+
return Wrapper, wrapper
|
140 |
+
|
141 |
+
|
142 |
+
@app.cell(hide_code=True)
|
143 |
+
def _(mo):
|
144 |
+
mo.md(
|
145 |
+
"""
|
146 |
+
We can analyze the type signature of `fmap` for `Wrapper`:
|
147 |
+
|
148 |
+
* `self` is of type `Wrapper[a]`
|
149 |
+
* `func` is of type `Callable[[a], b]`
|
150 |
+
* The return value is of type `Wrapper[b]`
|
151 |
+
|
152 |
+
Thus, in Python's type system, we can express the type signature of `fmap` as:
|
153 |
+
|
154 |
+
```python
|
155 |
+
def fmap(self: Wrapper[a], func: Callable[[a], b]) -> Wrapper[b]:
|
156 |
+
```
|
157 |
+
|
158 |
+
Essentially, `fmap`:
|
159 |
+
|
160 |
+
1. Takes a `Wrapper[a]` instance and a function `Callable[[a], b]` as input.
|
161 |
+
2. Applies the function to the value inside the wrapper.
|
162 |
+
3. Returns a new `Wrapper[b]` instance with the transformed value, leaving the original wrapper and its internal data unmodified.
|
163 |
+
|
164 |
+
Now, let's examine `list` as a similar kind of wrapper.
|
165 |
+
"""
|
166 |
+
)
|
167 |
+
return
|
168 |
+
|
169 |
+
|
170 |
+
@app.cell(hide_code=True)
|
171 |
+
def _(mo):
|
172 |
+
mo.md(
|
173 |
+
"""
|
174 |
+
## The List Wrapper
|
175 |
+
|
176 |
+
We can define a `ListWrapper` class to represent a wrapped list that supports `fmap`:
|
177 |
+
"""
|
178 |
+
)
|
179 |
+
return
|
180 |
+
|
181 |
+
|
182 |
+
@app.cell
|
183 |
+
def _(Callable, Functor, Generic, a, b, dataclass):
|
184 |
+
@dataclass
|
185 |
+
class ListWrapper(Functor, Generic[a]):
|
186 |
+
value: list[a]
|
187 |
+
|
188 |
+
def fmap(self, func: Callable[[a], b]) -> "ListWrapper[b]":
|
189 |
+
return ListWrapper([func(x) for x in self.value])
|
190 |
+
|
191 |
+
def __repr__(self):
|
192 |
+
return repr(self.value)
|
193 |
+
|
194 |
+
|
195 |
+
list_wrapper = ListWrapper([1, 2, 3, 4])
|
196 |
+
return ListWrapper, list_wrapper
|
197 |
+
|
198 |
+
|
199 |
+
@app.cell
|
200 |
+
def _(ListWrapper, mo):
|
201 |
+
with mo.redirect_stdout():
|
202 |
+
print(ListWrapper(value=[2, 3, 4, 5]))
|
203 |
+
print(ListWrapper(value=[[1], [2], [3], [4]]))
|
204 |
+
return
|
205 |
+
|
206 |
+
|
207 |
+
@app.cell(hide_code=True)
|
208 |
+
def _(mo):
|
209 |
+
mo.md(
|
210 |
+
"""
|
211 |
+
### Extracting the Type of `fmap`
|
212 |
+
|
213 |
+
The type signature of `fmap` for `ListWrapper` is:
|
214 |
+
|
215 |
+
```python
|
216 |
+
def fmap(self: ListWrapper[a], func: Callable[[a], b]) -> ListWrapper[b]
|
217 |
+
```
|
218 |
+
|
219 |
+
Similarly, for `Wrapper`:
|
220 |
+
|
221 |
+
```python
|
222 |
+
def fmap(self: Wrapper[a], func: Callable[[a], b]) -> Wrapper[b]
|
223 |
+
```
|
224 |
+
|
225 |
+
Both follow the same pattern, which we can generalize as:
|
226 |
+
|
227 |
+
```python
|
228 |
+
def fmap(self: Functor[a], func: Callable[[a], b]) -> Functor[b]
|
229 |
+
```
|
230 |
+
|
231 |
+
where `Functor` can be `Wrapper`, `ListWrapper`, or any other wrapper type that follows the same structure.
|
232 |
+
|
233 |
+
### Functors in Haskell (optional)
|
234 |
+
|
235 |
+
In Haskell, the type of `fmap` is:
|
236 |
+
|
237 |
+
```haskell
|
238 |
+
fmap :: Functor f => (a -> b) -> f a -> f b
|
239 |
+
```
|
240 |
+
|
241 |
+
or equivalently:
|
242 |
+
|
243 |
+
```haskell
|
244 |
+
fmap :: Functor f => (a -> b) -> (f a -> f b)
|
245 |
+
```
|
246 |
+
|
247 |
+
This means that `fmap` **lifts** an ordinary function into the **functor world**, allowing it to operate within a computational context.
|
248 |
+
|
249 |
+
Now, let's define an abstract class for `Functor`.
|
250 |
+
"""
|
251 |
+
)
|
252 |
+
return
|
253 |
+
|
254 |
+
|
255 |
+
@app.cell(hide_code=True)
|
256 |
+
def _(mo):
|
257 |
+
mo.md(
|
258 |
+
"""
|
259 |
+
## Defining Functor
|
260 |
+
|
261 |
+
Recall that, a **Functor** is an abstraction that allows us to apply a function to values inside a computational context while preserving its structure.
|
262 |
+
|
263 |
+
To define `Functor` in Python, we use an abstract base class:
|
264 |
+
|
265 |
+
```python
|
266 |
+
from dataclasses import dataclass
|
267 |
+
from typing import Callable, Generic, TypeVar
|
268 |
+
from abc import ABC, abstractmethod
|
269 |
+
|
270 |
+
a = TypeVar("a")
|
271 |
+
b = TypeVar("b")
|
272 |
+
|
273 |
+
@dataclass
|
274 |
+
class Functor(ABC, Generic[a]):
|
275 |
+
@abstractmethod
|
276 |
+
def fmap(self, func: Callable[[a], b]) -> "Functor[b]":
|
277 |
+
raise NotImplementedError
|
278 |
+
```
|
279 |
+
|
280 |
+
We can now extend custom wrappers, containers, or computation contexts with this `Functor` base class, implement the `fmap` method, and apply any function.
|
281 |
+
|
282 |
+
Next, let's implement a more complex data structure: [RoseTree](https://en.wikipedia.org/wiki/Rose_tree).
|
283 |
+
"""
|
284 |
+
)
|
285 |
+
return
|
286 |
+
|
287 |
+
|
288 |
+
@app.cell(hide_code=True)
|
289 |
+
def _(mo):
|
290 |
+
mo.md(
|
291 |
+
"""
|
292 |
+
## Case Study: RoseTree
|
293 |
+
|
294 |
+
A **RoseTree** is a tree where:
|
295 |
+
|
296 |
+
- Each node holds a **value**.
|
297 |
+
- Each node has a **list of child nodes** (which are also RoseTrees).
|
298 |
+
|
299 |
+
This structure is useful for representing hierarchical data, such as:
|
300 |
+
|
301 |
+
- Abstract Syntax Trees (ASTs)
|
302 |
+
- File system directories
|
303 |
+
- Recursive computations
|
304 |
+
|
305 |
+
We can implement `RoseTree` by extending the `Functor` class:
|
306 |
+
|
307 |
+
```python
|
308 |
+
from dataclasses import dataclass
|
309 |
+
from typing import Callable, Generic, TypeVar
|
310 |
+
|
311 |
+
a = TypeVar("a")
|
312 |
+
b = TypeVar("b")
|
313 |
+
|
314 |
+
@dataclass
|
315 |
+
class RoseTree(Functor, Generic[a]):
|
316 |
+
value: a
|
317 |
+
children: list["RoseTree[a]"]
|
318 |
+
|
319 |
+
def fmap(self, func: Callable[[a], b]) -> "RoseTree[b]":
|
320 |
+
return RoseTree(
|
321 |
+
func(self.value), [child.fmap(func) for child in self.children]
|
322 |
+
)
|
323 |
+
|
324 |
+
def __repr__(self) -> str:
|
325 |
+
return f"RoseNode({self.value}, {self.children})"
|
326 |
+
```
|
327 |
+
|
328 |
+
- The function is applied **recursively** to each node's value.
|
329 |
+
- The tree structure **remains unchanged**.
|
330 |
+
- Only the values inside the tree are modified.
|
331 |
+
|
332 |
+
> Try using `RoseTree` in the cell below.
|
333 |
+
"""
|
334 |
+
)
|
335 |
+
return
|
336 |
+
|
337 |
+
|
338 |
+
@app.cell(hide_code=True)
|
339 |
+
def _(Callable, Functor, Generic, a, b, dataclass, mo):
|
340 |
+
@dataclass
|
341 |
+
class RoseTree(Functor, Generic[a]):
|
342 |
+
"""
|
343 |
+
### Doc: RoseTree
|
344 |
+
|
345 |
+
A Functor implementation of `RoseTree`, allowing transformation of values while preserving the tree structure.
|
346 |
+
|
347 |
+
**Attributes**
|
348 |
+
|
349 |
+
- `value (a)`: The value stored in the node.
|
350 |
+
- `children (list[RoseTree[a]])`: A list of child nodes forming the tree structure.
|
351 |
+
|
352 |
+
**Methods:**
|
353 |
+
|
354 |
+
- `fmap(func: Callable[[a], b]) -> RoseTree[b]`
|
355 |
+
```Python
|
356 |
+
def fmap(RoseTree[a], (a -> b)) -> RoseTree[b]
|
357 |
+
```
|
358 |
+
Applies a function to each value in the tree, producing a new `RoseTree[b]` with transformed values.
|
359 |
+
|
360 |
+
**Implementation logic:**
|
361 |
+
|
362 |
+
- The function `func` is applied to the root node's `value`.
|
363 |
+
- Each child in `children` recursively calls `fmap`, ensuring all values in the tree are mapped.
|
364 |
+
- The overall tree structure remains unchanged.
|
365 |
+
|
366 |
+
- `__repr__() -> str`: Returns a string representation of the node and its children.
|
367 |
+
"""
|
368 |
+
|
369 |
+
value: a
|
370 |
+
children: list["RoseTree[a]"]
|
371 |
+
|
372 |
+
def fmap(self, func: Callable[[a], b]) -> "RoseTree[b]":
|
373 |
+
return RoseTree(
|
374 |
+
func(self.value), [child.fmap(func) for child in self.children]
|
375 |
+
)
|
376 |
+
|
377 |
+
def __repr__(self) -> str:
|
378 |
+
return f"RoseNode({self.value}, {self.children})"
|
379 |
+
|
380 |
+
|
381 |
+
mo.md(RoseTree.__doc__)
|
382 |
+
return (RoseTree,)
|
383 |
+
|
384 |
+
|
385 |
+
@app.cell(hide_code=True)
|
386 |
+
def _(RoseTree, mo):
|
387 |
+
ftree = RoseTree(1, [RoseTree(2, []), RoseTree(3, [RoseTree(4, [])])])
|
388 |
+
|
389 |
+
with mo.redirect_stdout():
|
390 |
+
print(ftree)
|
391 |
+
print(ftree.fmap(lambda x: [x]))
|
392 |
+
print(ftree.fmap(lambda x: RoseTree(x, [])))
|
393 |
+
return (ftree,)
|
394 |
+
|
395 |
+
|
396 |
+
@app.cell(hide_code=True)
|
397 |
+
def _(mo):
|
398 |
+
mo.md(
|
399 |
+
"""
|
400 |
+
## Generic Functions that can be Used with Any Functor
|
401 |
+
|
402 |
+
One of the powerful features of functors is that we can write **generic functions** that can work with any functor.
|
403 |
+
|
404 |
+
Remember that in Haskell, the type of `fmap` can be written as:
|
405 |
+
|
406 |
+
```haskell
|
407 |
+
fmap :: Functor f => (a -> b) -> (f a -> f b)
|
408 |
+
```
|
409 |
+
|
410 |
+
Translating to Python, we get:
|
411 |
+
|
412 |
+
```python
|
413 |
+
def fmap(func: Callable[[a], b]) -> Callable[[Functor[a]], Functor[b]]
|
414 |
+
```
|
415 |
+
|
416 |
+
This means that `fmap`:
|
417 |
+
|
418 |
+
- Takes an **ordinary function** `Callable[[a], b]` as input.
|
419 |
+
- Outputs a function that:
|
420 |
+
- Takes a **functor** of type `Functor[a]` as input.
|
421 |
+
- Outputs a **functor** of type `Functor[b]`.
|
422 |
+
|
423 |
+
We can implement a similar idea in Python:
|
424 |
+
|
425 |
+
```python
|
426 |
+
# fmap(func: Callable[[a], b]) -> Callable[[Functor[a]], Functor[b]]
|
427 |
+
fmap = lambda func: lambda f: f.fmap(lambda x: func(x))
|
428 |
+
|
429 |
+
# inc([Functor[a]) -> Functor[b]
|
430 |
+
inc = fmap(lambda x: x + 1)
|
431 |
+
```
|
432 |
+
|
433 |
+
- **`fmap`**: Lifts an ordinary function (`lambda x: func(x)`) to the functor world, allowing the function to operate on the wrapped value inside the functor.
|
434 |
+
- **`inc`**: A specific instance of `fmap` that operates on any functor. It takes a functor, applies the function `lambda x: x + 1` to every value inside it, and returns a new functor with the updated values.
|
435 |
+
|
436 |
+
Thus, **`fmap`** transforms an ordinary function into a **function that operates on functors**, and **`inc`** is a specific case where it increments the value inside the functor.
|
437 |
+
|
438 |
+
### Applying the `inc` Function to Various Functors
|
439 |
+
|
440 |
+
You can now apply `inc` to any functor like `Wrapper`, `ListWrapper`, or `RoseTree`:
|
441 |
+
|
442 |
+
```python
|
443 |
+
# Applying `inc` to a Wrapper
|
444 |
+
wrapper = Wrapper(5)
|
445 |
+
inc(wrapper) # Wrapper(value=6)
|
446 |
+
|
447 |
+
# Applying `inc` to a ListWrapper
|
448 |
+
list_wrapper = ListWrapper([1, 2, 3])
|
449 |
+
inc(list_wrapper) # ListWrapper(value=[2, 3, 4])
|
450 |
+
|
451 |
+
# Applying `inc` to a RoseTree
|
452 |
+
tree = RoseTree(1, [RoseTree(2, []), RoseTree(3, [])])
|
453 |
+
inc(tree) # RoseTree(value=2, children=[RoseTree(value=3, children=[]), RoseTree(value=4, children=[])])
|
454 |
+
```
|
455 |
+
|
456 |
+
> Try using `fmap` in the cell below.
|
457 |
+
"""
|
458 |
+
)
|
459 |
+
return
|
460 |
+
|
461 |
+
|
462 |
+
@app.cell(hide_code=True)
|
463 |
+
def _(ftree, list_wrapper, mo, wrapper):
|
464 |
+
fmap = lambda func: lambda f: f.fmap(func)
|
465 |
+
inc = fmap(lambda x: x + 1)
|
466 |
+
with mo.redirect_stdout():
|
467 |
+
print(inc(wrapper))
|
468 |
+
print(inc(list_wrapper))
|
469 |
+
print(inc(ftree))
|
470 |
+
return fmap, inc
|
471 |
+
|
472 |
+
|
473 |
+
@app.cell(hide_code=True)
|
474 |
+
def _(mo):
|
475 |
+
mo.md(
|
476 |
+
"""
|
477 |
+
## Functor laws
|
478 |
+
|
479 |
+
In addition to providing a function `fmap` of the specified type, functors are also required to satisfy two equational laws:
|
480 |
+
|
481 |
+
```haskell
|
482 |
+
fmap id = id -- fmap preserves identity
|
483 |
+
fmap (g . h) = fmap g . fmap h -- fmap distributes over composition
|
484 |
+
```
|
485 |
+
|
486 |
+
1. `fmap` should preserve the **identity function**, in the sense that applying `fmap` to this function returns the same function as the result.
|
487 |
+
2. `fmap` should also preserve **function composition**. Applying two composed functions `g` and `h` to a functor via `fmap` should give the same result as first applying `fmap` to `g` and then applying `fmap` to `h`.
|
488 |
+
|
489 |
+
/// admonition |
|
490 |
+
- Any `Functor` instance satisfying the first law `(fmap id = id)` will automatically satisfy the [second law](https://github.com/quchen/articles/blob/master/second_functor_law.mo) as well.
|
491 |
+
///
|
492 |
+
|
493 |
+
### Functor Law Verification
|
494 |
+
|
495 |
+
We can add a helper function `check_functor_law` in the `Functor` class to verify that an instance satisfies the functor laws.
|
496 |
+
|
497 |
+
```Python
|
498 |
+
id = lambda x: x
|
499 |
+
|
500 |
+
@dataclass
|
501 |
+
class Functor(ABC, Generic[a]):
|
502 |
+
@abstractmethod
|
503 |
+
def fmap(self, func: Callable[[a], b]) -> "Functor[b]":
|
504 |
+
return NotImplementedError
|
505 |
+
|
506 |
+
def check_functor_law(self):
|
507 |
+
return repr(self.fmap(id)) == repr(self)
|
508 |
+
|
509 |
+
@abstractmethod
|
510 |
+
def __repr__(self):
|
511 |
+
return NotImplementedError
|
512 |
+
```
|
513 |
+
|
514 |
+
We can verify the functor we've defined.
|
515 |
+
"""
|
516 |
+
)
|
517 |
+
return
|
518 |
+
|
519 |
+
|
520 |
+
@app.cell
|
521 |
+
def _():
|
522 |
+
id = lambda x: x
|
523 |
+
compose = lambda f, g: lambda x: f(g(x))
|
524 |
+
return compose, id
|
525 |
+
|
526 |
+
|
527 |
+
@app.cell
|
528 |
+
def _(ftree, list_wrapper, mo, wrapper):
|
529 |
+
with mo.redirect_stdout():
|
530 |
+
print(wrapper.check_functor_law())
|
531 |
+
print(list_wrapper.check_functor_law())
|
532 |
+
print(ftree.check_functor_law())
|
533 |
+
return
|
534 |
+
|
535 |
+
|
536 |
+
@app.cell(hide_code=True)
|
537 |
+
def _(mo):
|
538 |
+
mo.md("""And here is an `EvilFunctor`. We can verify it's not a valid `Functor`.""")
|
539 |
+
return
|
540 |
+
|
541 |
+
|
542 |
+
@app.cell
|
543 |
+
def _(Callable, Functor, Generic, a, b, dataclass):
|
544 |
+
@dataclass
|
545 |
+
class EvilFunctor(Functor, Generic[a]):
|
546 |
+
value: list[a]
|
547 |
+
|
548 |
+
def fmap(self, func: Callable[[a], b]) -> "EvilFunctor[b]":
|
549 |
+
return (
|
550 |
+
EvilFunctor([self.value[0]] * 2 + list(map(func, self.value[1:])))
|
551 |
+
if self.value
|
552 |
+
else []
|
553 |
+
)
|
554 |
+
|
555 |
+
def __repr__(self):
|
556 |
+
return repr(self.value)
|
557 |
+
return (EvilFunctor,)
|
558 |
+
|
559 |
+
|
560 |
+
@app.cell
|
561 |
+
def _(EvilFunctor):
|
562 |
+
EvilFunctor([1, 2, 3, 4]).check_functor_law()
|
563 |
+
return
|
564 |
+
|
565 |
+
|
566 |
+
@app.cell(hide_code=True)
|
567 |
+
def _(mo):
|
568 |
+
mo.md(
|
569 |
+
"""
|
570 |
+
## Final definition of Functor
|
571 |
+
|
572 |
+
We can now draft the final definition of `Functor` with some utility functions.
|
573 |
+
|
574 |
+
```Python
|
575 |
+
@dataclass
|
576 |
+
class Functor(ABC, Generic[a]):
|
577 |
+
@abstractmethod
|
578 |
+
def fmap(self, func: Callable[[a], b]) -> "Functor[b]":
|
579 |
+
return NotImplementedError
|
580 |
+
|
581 |
+
def check_functor_law(self) -> bool:
|
582 |
+
return repr(self.fmap(id)) == repr(self)
|
583 |
+
|
584 |
+
def const_fmap(self, b) -> "Functor[b]":
|
585 |
+
return self.fmap(lambda _: b)
|
586 |
+
|
587 |
+
def void(self) -> "Functor[None]":
|
588 |
+
return self.const_fmap(None)
|
589 |
+
|
590 |
+
@abstractmethod
|
591 |
+
def __repr__(self):
|
592 |
+
return NotImplementedError
|
593 |
+
```
|
594 |
+
"""
|
595 |
+
)
|
596 |
+
return
|
597 |
+
|
598 |
+
|
599 |
+
@app.cell(hide_code=True)
|
600 |
+
def _(ABC, Callable, Generic, a, abstractmethod, b, dataclass, id, mo):
|
601 |
+
@dataclass
|
602 |
+
class Functor(ABC, Generic[a]):
|
603 |
+
"""
|
604 |
+
### Doc: Functor
|
605 |
+
|
606 |
+
A generic interface for types that support mapping over their values.
|
607 |
+
|
608 |
+
**Methods:**
|
609 |
+
|
610 |
+
- `fmap(func: Callable[[a], b]) -> Functor[b]`
|
611 |
+
Abstract method to apply a function `func` to transform the values inside the Functor.
|
612 |
+
|
613 |
+
- `check_functor_law() -> bool`
|
614 |
+
Verifies the identity law of functors: `fmap(id) == id`.
|
615 |
+
This ensures that applying `fmap` with the identity function does not alter the structure.
|
616 |
+
|
617 |
+
- `const_fmap(b) -> Functor[b]`
|
618 |
+
Replaces all values inside the Functor with a constant `b`, preserving the original structure.
|
619 |
+
|
620 |
+
- `void() -> Functor[None]`
|
621 |
+
Equivalent to `const_fmap(None)`, transforming all values into `None`.
|
622 |
+
|
623 |
+
- `__repr__()`
|
624 |
+
Abstract method to define a string representation of the Functor.
|
625 |
+
|
626 |
+
**Functor Laws:**
|
627 |
+
A valid Functor implementation must satisfy:
|
628 |
+
|
629 |
+
1. **Identity Law:** `F.fmap(id) == F`
|
630 |
+
2. **Composition Law:** `F.fmap(f).fmap(g) == F.fmap(lambda x: g(f(x)))`
|
631 |
+
"""
|
632 |
+
|
633 |
+
@abstractmethod
|
634 |
+
def fmap(self, func: Callable[[a], b]) -> "Functor[b]":
|
635 |
+
return NotImplementedError
|
636 |
+
|
637 |
+
def check_functor_law(self) -> bool:
|
638 |
+
return repr(self.fmap(id)) == repr(self)
|
639 |
+
|
640 |
+
def const_fmap(self, b) -> "Functor[b]":
|
641 |
+
return self.fmap(lambda _: b)
|
642 |
+
|
643 |
+
def void(self) -> "Functor[None]":
|
644 |
+
return self.const_fmap(None)
|
645 |
+
|
646 |
+
@abstractmethod
|
647 |
+
def __repr__(self):
|
648 |
+
return NotImplementedError
|
649 |
+
|
650 |
+
|
651 |
+
mo.md(Functor.__doc__)
|
652 |
+
return (Functor,)
|
653 |
+
|
654 |
+
|
655 |
+
@app.cell(hide_code=True)
|
656 |
+
def _(mo):
|
657 |
+
mo.md("""> Try with utility functions in the cell below""")
|
658 |
+
return
|
659 |
+
|
660 |
+
|
661 |
+
@app.cell(hide_code=True)
|
662 |
+
def _(ftree, list_wrapper, mo):
|
663 |
+
with mo.redirect_stdout():
|
664 |
+
print(ftree.const_fmap("λ"))
|
665 |
+
print(ftree.void())
|
666 |
+
print(list_wrapper.const_fmap("λ"))
|
667 |
+
print(list_wrapper.void())
|
668 |
+
return
|
669 |
+
|
670 |
+
|
671 |
+
@app.cell(hide_code=True)
|
672 |
+
def _(mo):
|
673 |
+
mo.md(
|
674 |
+
"""
|
675 |
+
## Functors for Non-Iterable Types
|
676 |
+
|
677 |
+
In the previous examples, we implemented functors for **iterables**, like `ListWrapper` and `RoseTree`, which are inherently **iterable types**. This is a natural fit for functors, as iterables can be mapped over.
|
678 |
+
|
679 |
+
However, **functors are not limited to iterables**. There are cases where we want to apply the concept of functors to types that are not inherently iterable, such as types that represent optional values, computations, or other data structures.
|
680 |
+
|
681 |
+
### The Maybe Functor
|
682 |
+
|
683 |
+
One example is the **`Maybe`** type from Haskell, which is used to represent computations that can either result in a value (`Just a`) or no value (`Nothing`).
|
684 |
+
|
685 |
+
We can define the `Maybe` functor as below:
|
686 |
+
"""
|
687 |
+
)
|
688 |
+
return
|
689 |
+
|
690 |
+
|
691 |
+
@app.cell
|
692 |
+
def _(Callable, Functor, Generic, a, b, dataclass):
|
693 |
+
@dataclass
|
694 |
+
class Just(Generic[a]):
|
695 |
+
value: a
|
696 |
+
|
697 |
+
def __init__(self, value: a):
|
698 |
+
# If the value is already a `Just`, we extract the value, else we wrap it
|
699 |
+
self.value = value.value if isinstance(value, Just) else value
|
700 |
+
|
701 |
+
def __repr__(self):
|
702 |
+
return f"Just {self.value}"
|
703 |
+
|
704 |
+
|
705 |
+
@dataclass
|
706 |
+
class Maybe(Functor, Generic[a]):
|
707 |
+
value: None | Just[a]
|
708 |
+
|
709 |
+
def fmap(self, func: Callable[[a], b]) -> "Maybe[b]":
|
710 |
+
# Apply the function to the value inside `Just`, or return `Nothing` if value is None
|
711 |
+
return (
|
712 |
+
Maybe(Just(func(self.value.value))) if self.value else Maybe(None)
|
713 |
+
)
|
714 |
+
|
715 |
+
def __repr__(self):
|
716 |
+
return repr(self.value) if self.value else "Nothing"
|
717 |
+
return Just, Maybe
|
718 |
+
|
719 |
+
|
720 |
+
@app.cell(hide_code=True)
|
721 |
+
def _(mo):
|
722 |
+
mo.md(
|
723 |
+
"""
|
724 |
+
- **`Just`** is a wrapper that holds a value. We use it to represent the presence of a value.
|
725 |
+
- **`Maybe`** is a functor that can either hold a `Just` value or be `Nothing` (equivalent to `None` in Python). The `fmap` method applies a function to the value inside the `Just` wrapper, if it exists. If the value is `None` (representing `Nothing`), `fmap` simply returns `Nothing`.
|
726 |
+
|
727 |
+
By using `Maybe` as a functor, we gain the ability to apply transformations (`fmap`) to potentially absent values, without having to explicitly handle the `None` case every time.
|
728 |
+
|
729 |
+
> Try using `Maybe` in the cell below.
|
730 |
+
"""
|
731 |
+
)
|
732 |
+
return
|
733 |
+
|
734 |
+
|
735 |
+
@app.cell
|
736 |
+
def _(Just, Maybe, ftree):
|
737 |
+
mftree = Maybe(Just(ftree))
|
738 |
+
mint = Maybe(Just(1))
|
739 |
+
mnone = Maybe(None)
|
740 |
+
return mftree, mint, mnone
|
741 |
+
|
742 |
+
|
743 |
+
@app.cell(hide_code=True)
|
744 |
+
def _(inc, mftree, mint, mnone, mo):
|
745 |
+
with mo.redirect_stdout():
|
746 |
+
print(mftree.check_functor_law())
|
747 |
+
print(mint.check_functor_law())
|
748 |
+
print(mnone.check_functor_law())
|
749 |
+
print(mftree.fmap(inc))
|
750 |
+
print(mint.fmap(lambda x: x + 1))
|
751 |
+
print(mnone.fmap(lambda x: x + 1))
|
752 |
+
return
|
753 |
+
|
754 |
+
|
755 |
+
@app.cell(hide_code=True)
|
756 |
+
def _(mo):
|
757 |
+
mo.md(
|
758 |
+
"""
|
759 |
+
## Limitations of Functor
|
760 |
+
|
761 |
+
Functors abstract the idea of mapping a function over each element of a structure. Suppose now that we wish to generalise this idea to allow functions with any number of arguments to be mapped, rather than being restricted to functions with a single argument. More precisely, suppose that we wish to define a hierarchy of `fmap` functions with the following types:
|
762 |
+
|
763 |
+
```haskell
|
764 |
+
fmap0 :: a -> f a
|
765 |
+
|
766 |
+
fmap1 :: (a -> b) -> f a -> f b
|
767 |
+
|
768 |
+
fmap2 :: (a -> b -> c) -> f a -> f b -> f c
|
769 |
+
|
770 |
+
fmap3 :: (a -> b -> c -> d) -> f a -> f b -> f c -> f d
|
771 |
+
```
|
772 |
+
|
773 |
+
And we have to declare a special version of the functor class for each case.
|
774 |
+
|
775 |
+
We will learn how to resolve this problem in the next notebook on `Applicatives`.
|
776 |
+
"""
|
777 |
+
)
|
778 |
+
return
|
779 |
+
|
780 |
+
|
781 |
+
@app.cell(hide_code=True)
|
782 |
+
def _(mo):
|
783 |
+
mo.md(
|
784 |
+
"""
|
785 |
+
# Introduction to Categories
|
786 |
+
|
787 |
+
A [category](https://en.wikibooks.org/wiki/Haskell/Category_theory#Introduction_to_categories) is, in essence, a simple collection. It has three components:
|
788 |
+
|
789 |
+
- A collection of **objects**.
|
790 |
+
- A collection of **morphisms**, each of which ties two objects (a _source object_ and a _target object_) together. If $f$ is a morphism with source object $C$ and target object $B$, we write $f : C → B$.
|
791 |
+
- A notion of **composition** of these morphisms. If $g : A → B$ and $f : B → C$ are two morphisms, they can be composed, resulting in a morphism $f ∘ g : A → C$.
|
792 |
+
|
793 |
+
## Category laws
|
794 |
+
|
795 |
+
There are three laws that categories need to follow.
|
796 |
+
|
797 |
+
1. The composition of morphisms needs to be **associative**. Symbolically, $f ∘ (g ∘ h) = (f ∘ g) ∘ h$
|
798 |
+
|
799 |
+
- Morphisms are applied right to left, so with $f ∘ g$ first $g$ is applied, then $f$.
|
800 |
+
|
801 |
+
2. The category needs to be **closed** under the composition operation. So if $f : B → C$ and $g : A → B$, then there must be some morphism $h : A → C$ in the category such that $h = f ∘ g$.
|
802 |
+
|
803 |
+
3. Given a category $C$ there needs to be for every object $A$ an **identity** morphism, $id_A : A → A$ that is an identity of composition with other morphisms. Put precisely, for every morphism $g : A → B$: $g ∘ id_A = id_B ∘ g = g$
|
804 |
+
|
805 |
+
/// attention | The definition of a category does not define:
|
806 |
+
|
807 |
+
- what `∘` is,
|
808 |
+
- what `id` is, or
|
809 |
+
- what `f`, `g`, and `h` might be.
|
810 |
+
|
811 |
+
Instead, category theory leaves it up to us to discover what they might be.
|
812 |
+
///
|
813 |
+
"""
|
814 |
+
)
|
815 |
+
return
|
816 |
+
|
817 |
+
|
818 |
+
@app.cell(hide_code=True)
|
819 |
+
def _(mo):
|
820 |
+
mo.md(
|
821 |
+
"""
|
822 |
+
## The Python category
|
823 |
+
|
824 |
+
The main category we'll be concerning ourselves with in this part is the Python category, or we can give it a shorter name: `Py`. `Py` treats Python types as objects and Python functions as morphisms. A function `def f(a: A) -> B` for types A and B is a morphism in Python.
|
825 |
+
|
826 |
+
Remember that we defined the `id` and `compose` function above as:
|
827 |
+
|
828 |
+
```Python
|
829 |
+
def id(x: Generic[a]) -> Generic[a]:
|
830 |
+
return x
|
831 |
+
|
832 |
+
def compose(f: Callable[[b], c], g: Callable[[a], b]) -> Callable[[a], c]:
|
833 |
+
return lambda x: f(g(x))
|
834 |
+
```
|
835 |
+
|
836 |
+
We can check second law easily.
|
837 |
+
|
838 |
+
For the first law, we have:
|
839 |
+
|
840 |
+
```python
|
841 |
+
# compose(f, g) = lambda x: f(g(x))
|
842 |
+
f ∘ (g ∘ h)
|
843 |
+
= compose(f, compose(g, h))
|
844 |
+
= lambda x: f(compose(g, h)(x))
|
845 |
+
= lambda x: f(lambda y: g(h(y))(x))
|
846 |
+
= lambda x: f(g(h(x)))
|
847 |
+
|
848 |
+
(f ∘ g) ∘ h
|
849 |
+
= compose(compose(f, g), h)
|
850 |
+
= lambda x: compose(f, g)(h(x))
|
851 |
+
= lambda x: lambda y: f(g(y))(h(x))
|
852 |
+
= lambda x: f(g(h(x)))
|
853 |
+
```
|
854 |
+
|
855 |
+
For the third law, we have:
|
856 |
+
|
857 |
+
```python
|
858 |
+
g ∘ id_A
|
859 |
+
= compose(g: Callable[[a], b], id: Callable[[a], a]) -> Callable[[a], b]
|
860 |
+
= lambda x: g(id(x))
|
861 |
+
= lambda x: g(x) # id(x) = x
|
862 |
+
= g
|
863 |
+
```
|
864 |
+
the similar proof can be applied to $id_B ∘ g =g$.
|
865 |
+
|
866 |
+
Thus `Py` is a valid category.
|
867 |
+
"""
|
868 |
+
)
|
869 |
+
return
|
870 |
+
|
871 |
+
|
872 |
+
@app.cell(hide_code=True)
|
873 |
+
def _(mo):
|
874 |
+
mo.md(
|
875 |
+
"""
|
876 |
+
# Functors, again
|
877 |
+
|
878 |
+
A functor is essentially a transformation between categories, so given categories $C$ and $D$, a functor $F : C → D$:
|
879 |
+
|
880 |
+
- Maps any object $A$ in $C$ to $F ( A )$, in $D$.
|
881 |
+
- Maps morphisms $f : A → B$ in $C$ to $F ( f ) : F ( A ) → F ( B )$ in $D$.
|
882 |
+
|
883 |
+
> Endofunctors are functors from a category to itself.
|
884 |
+
"""
|
885 |
+
)
|
886 |
+
return
|
887 |
+
|
888 |
+
|
889 |
+
@app.cell(hide_code=True)
|
890 |
+
def _(mo):
|
891 |
+
mo.md(
|
892 |
+
"""
|
893 |
+
## Functors on the category of Python
|
894 |
+
|
895 |
+
Remember that a functor has two parts: it maps objects in one category to objects in another and morphisms in the first category to morphisms in the second.
|
896 |
+
|
897 |
+
Functors in Python are from `Py` to `func`, where `func` is the subcategory of `Py` defined on just that functor's types. E.g. the RoseTree functor goes from `Py` to `RoseTree`, where `RoseTree` is the category containing only RoseTree types, that is, `RoseTree[T]` for any type `T`. The morphisms in `RoseTree` are functions defined on RoseTree types, that is, functions `RoseTree[T] -> RoseTree[U]` for types `T`, `U`.
|
898 |
+
|
899 |
+
Recall the definition of `Functor`:
|
900 |
+
|
901 |
+
```Python
|
902 |
+
@dataclass
|
903 |
+
class Functor(ABC, Generic[a])
|
904 |
+
```
|
905 |
+
|
906 |
+
And RoseTree:
|
907 |
+
|
908 |
+
```Python
|
909 |
+
@dataclass
|
910 |
+
class RoseTree(Functor, Generic[a])
|
911 |
+
```
|
912 |
+
|
913 |
+
**Here's the key part:** the _type constructor_ `RoseTree` takes any type `T` to a new type, `RoseTree[T]`. Also, `fmap` restricted to `RoseTree` types takes a function `a -> b` to a function `RoseTree[a] -> RoseTree[b]`.
|
914 |
+
|
915 |
+
But that's it. We've defined two parts, something that takes objects in `Py` to objects in another category (that of `RoseTree` types and functions defined on `RoseTree` types), and something that takes morphisms in `Py` to morphisms in this category. So `RoseTree` is a functor.
|
916 |
+
|
917 |
+
To sum up:
|
918 |
+
|
919 |
+
- We work in the category **Py** and its subcategories.
|
920 |
+
- **Objects** are types (e.g., `int`, `str`, `list`).
|
921 |
+
- **Morphisms** are functions (`Callable[[A], B]`).
|
922 |
+
- **Things that take a type and return another type** are type constructors (`RoseTree[T]`).
|
923 |
+
- **Things that take a function and return another function** are higher-order functions (`Callable[[Callable[[A], B]], Callable[[C], D]]`).
|
924 |
+
- **Abstract base classes (ABC)** and duck typing provide a way to express polymorphism, capturing the idea that in category theory, structures are often defined over multiple objects at once.
|
925 |
+
"""
|
926 |
+
)
|
927 |
+
return
|
928 |
+
|
929 |
+
|
930 |
+
@app.cell(hide_code=True)
|
931 |
+
def _(mo):
|
932 |
+
mo.md(
|
933 |
+
"""
|
934 |
+
## Functor laws, again
|
935 |
+
|
936 |
+
Once again there are a few axioms that functors have to obey.
|
937 |
+
|
938 |
+
1. Given an identity morphism $id_A$ on an object $A$, $F ( id_A )$ must be the identity morphism on $F ( A )$, i.e.: ${\displaystyle F(\operatorname {id} _{A})=\operatorname {id} _{F(A)}}$
|
939 |
+
2. Functors must distribute over morphism composition, i.e. ${\displaystyle F(f\circ g)=F(f)\circ F(g)}$
|
940 |
+
"""
|
941 |
+
)
|
942 |
+
return
|
943 |
+
|
944 |
+
|
945 |
+
@app.cell(hide_code=True)
|
946 |
+
def _(mo):
|
947 |
+
mo.md(
|
948 |
+
"""
|
949 |
+
Remember that we defined the `fmap` (not the `fmap` in `Functor` class) and `id` as
|
950 |
+
```python
|
951 |
+
# fmap :: Callable[[a], b] -> Callable[[Functor[a]], Functor[b]]
|
952 |
+
fmap = lambda func: lambda f: f.fmap(func)
|
953 |
+
id = lambda x: x
|
954 |
+
compose = lambda f, g: lambda x: f(g(x))
|
955 |
+
```
|
956 |
+
|
957 |
+
Let's prove that `fmap` is a functor.
|
958 |
+
|
959 |
+
First, let's define a `Category` for a specific `Functor`. We choose to define the `Category` for the `Wrapper` as `WrapperCategory` here for simplicity, but remember that `Wrapper` can be any `Functor`(i.e. `ListWrapper`, `RoseTree`, `Maybe` and more):
|
960 |
+
|
961 |
+
**Notice that** in this case, we can actually view `fmap` as:
|
962 |
+
```python
|
963 |
+
# fmap :: Callable[[a], b] -> Callable[[Wrapper[a]], Wrapper[b]]
|
964 |
+
fmap = lambda func: lambda wrapper: wrapper.fmap(func)
|
965 |
+
```
|
966 |
+
|
967 |
+
We define `WrapperCategory` as:
|
968 |
+
|
969 |
+
```python
|
970 |
+
@dataclass
|
971 |
+
class WrapperCategory():
|
972 |
+
@staticmethod
|
973 |
+
def id() -> Callable[[Wrapper[a]], Wrapper[a]]:
|
974 |
+
return lambda wrapper: Wrapper(wrapper.value)
|
975 |
+
|
976 |
+
@staticmethod
|
977 |
+
def compose(
|
978 |
+
f: Callable[[Wrapper[b]], Wrapper[c]],
|
979 |
+
g: Callable[[Wrapper[a]], Wrapper[b]],
|
980 |
+
) -> Callable[[Wrapper[a]], Wrapper[c]]:
|
981 |
+
return lambda wrapper: f(g(Wrapper(wrapper.value)))
|
982 |
+
```
|
983 |
+
|
984 |
+
And `Wrapper` is:
|
985 |
+
|
986 |
+
```Python
|
987 |
+
@dataclass
|
988 |
+
class Wrapper(Generic[a]):
|
989 |
+
value: a
|
990 |
+
|
991 |
+
def fmap(self, func: Callable[[a], b]) -> "Wrapper[b]":
|
992 |
+
return Wrapper(func(self.value))
|
993 |
+
```
|
994 |
+
"""
|
995 |
+
)
|
996 |
+
return
|
997 |
+
|
998 |
+
|
999 |
+
@app.cell(hide_code=True)
|
1000 |
+
def _(mo):
|
1001 |
+
mo.md(
|
1002 |
+
"""
|
1003 |
+
notice that
|
1004 |
+
|
1005 |
+
```python
|
1006 |
+
fmap(f)(wrapper) = wrapper.fmap(f)
|
1007 |
+
```
|
1008 |
+
|
1009 |
+
We can get:
|
1010 |
+
|
1011 |
+
```python
|
1012 |
+
fmap(id)
|
1013 |
+
= lambda wrapper: wrapper.fmap(id)
|
1014 |
+
= lambda wrapper: Wrapper(id(wrapper.value))
|
1015 |
+
= lambda wrapper: Wrapper(wrapper.value)
|
1016 |
+
= WrapperCategory.id()
|
1017 |
+
```
|
1018 |
+
And:
|
1019 |
+
```python
|
1020 |
+
fmap(compose(f, g))
|
1021 |
+
= lambda wrapper: wrapper.fmap(compose(f, g))
|
1022 |
+
= lambda wrapper: Wrapper(compose(f, g)(wrapper.value))
|
1023 |
+
= lambda wrapper: Wrapper(f(g(wrapper.value)))
|
1024 |
+
|
1025 |
+
WrapperCategory.compose(fmap(f), fmap(g))
|
1026 |
+
= lambda wrapper: fmap(f)(fmap(g)(wrapper))
|
1027 |
+
= lambda wrapper: fmap(f)(wrapper.fmap(g))
|
1028 |
+
= lambda wrapper: fmap(f)(Wrapper(g(wrapper.value)))
|
1029 |
+
= lambda wrapper: Wrapper(g(wrapper.value)).fmap(f)
|
1030 |
+
= lambda wrapper: Wrapper(f(Wrapper(g(wrapper.value)).value))
|
1031 |
+
= lambda wrapper: Wrapper(f(g(wrapper.value)))
|
1032 |
+
= fmap(compose(f, g))
|
1033 |
+
```
|
1034 |
+
|
1035 |
+
So our `Wrapper` is a valid `Functor`.
|
1036 |
+
|
1037 |
+
> Try validating functor laws for `Wrapper` below.
|
1038 |
+
"""
|
1039 |
+
)
|
1040 |
+
return
|
1041 |
+
|
1042 |
+
|
1043 |
+
@app.cell(hide_code=True)
|
1044 |
+
def _(Callable, Wrapper, a, b, c, dataclass):
|
1045 |
+
@dataclass
|
1046 |
+
class WrapperCategory:
|
1047 |
+
@staticmethod
|
1048 |
+
def id() -> Callable[[Wrapper[a]], Wrapper[a]]:
|
1049 |
+
return lambda wrapper: Wrapper(wrapper.value)
|
1050 |
+
|
1051 |
+
@staticmethod
|
1052 |
+
def compose(
|
1053 |
+
f: Callable[[Wrapper[b]], Wrapper[c]],
|
1054 |
+
g: Callable[[Wrapper[a]], Wrapper[b]],
|
1055 |
+
) -> Callable[[Wrapper[a]], Wrapper[c]]:
|
1056 |
+
return lambda wrapper: f(g(Wrapper(wrapper.value)))
|
1057 |
+
return (WrapperCategory,)
|
1058 |
+
|
1059 |
+
|
1060 |
+
@app.cell(hide_code=True)
|
1061 |
+
def _(WrapperCategory, compose, fmap, id, mo, wrapper):
|
1062 |
+
with mo.redirect_stdout():
|
1063 |
+
print(fmap(id)(wrapper) == id(wrapper))
|
1064 |
+
print(
|
1065 |
+
fmap(compose(lambda x: x + 1, lambda x: x * 2))(wrapper)
|
1066 |
+
== WrapperCategory.compose(
|
1067 |
+
fmap(lambda x: x + 1), fmap(lambda x: x * 2)
|
1068 |
+
)(wrapper)
|
1069 |
+
)
|
1070 |
+
return
|
1071 |
+
|
1072 |
+
|
1073 |
+
@app.cell(hide_code=True)
|
1074 |
+
def _(mo):
|
1075 |
+
mo.md(
|
1076 |
+
"""
|
1077 |
+
## Length as a Functor
|
1078 |
+
|
1079 |
+
Remember that a functor is a transformation between two categories. It is not only limited to a functor from `Py` to `func`, but also includes transformations between other mathematical structures.
|
1080 |
+
|
1081 |
+
Let’s prove that **`length`** can be viewed as a functor. Specifically, we will demonstrate that `length` is a functor from the **category of list concatenation** to the **category of integer addition**.
|
1082 |
+
|
1083 |
+
### Category of List Concatenation
|
1084 |
+
|
1085 |
+
First, let’s define the category of list concatenation:
|
1086 |
+
"""
|
1087 |
+
)
|
1088 |
+
return
|
1089 |
+
|
1090 |
+
|
1091 |
+
@app.cell
|
1092 |
+
def _(Generic, a, dataclass):
|
1093 |
+
@dataclass
|
1094 |
+
class ListConcatenation(Generic[a]):
|
1095 |
+
value: list[a]
|
1096 |
+
|
1097 |
+
@staticmethod
|
1098 |
+
def id() -> "ListConcatenation[a]":
|
1099 |
+
return ListConcatenation([])
|
1100 |
+
|
1101 |
+
@staticmethod
|
1102 |
+
def compose(
|
1103 |
+
this: "ListConcatenation[a]", other: "ListConcatenation[a]"
|
1104 |
+
) -> "ListConcatenation[a]":
|
1105 |
+
return ListConcatenation(this.value + other.value)
|
1106 |
+
return (ListConcatenation,)
|
1107 |
+
|
1108 |
+
|
1109 |
+
@app.cell(hide_code=True)
|
1110 |
+
def _(mo):
|
1111 |
+
mo.md(
|
1112 |
+
"""
|
1113 |
+
- **Identity**: The identity element is an empty list (`ListConcatenation([])`).
|
1114 |
+
- **Composition**: The composition of two lists is their concatenation (`this.value + other.value`).
|
1115 |
+
"""
|
1116 |
+
)
|
1117 |
+
return
|
1118 |
+
|
1119 |
+
|
1120 |
+
@app.cell(hide_code=True)
|
1121 |
+
def _(mo):
|
1122 |
+
mo.md(
|
1123 |
+
"""
|
1124 |
+
### Category of Integer Addition
|
1125 |
+
|
1126 |
+
Now, let's define the category of integer addition:
|
1127 |
+
"""
|
1128 |
+
)
|
1129 |
+
return
|
1130 |
+
|
1131 |
+
|
1132 |
+
@app.cell
|
1133 |
+
def _(dataclass):
|
1134 |
+
@dataclass
|
1135 |
+
class IntAddition:
|
1136 |
+
value: int
|
1137 |
+
|
1138 |
+
@staticmethod
|
1139 |
+
def id() -> "IntAddition":
|
1140 |
+
return IntAddition(0)
|
1141 |
+
|
1142 |
+
@staticmethod
|
1143 |
+
def compose(this: "IntAddition", other: "IntAddition") -> "IntAddition":
|
1144 |
+
return IntAddition(this.value + other.value)
|
1145 |
+
return (IntAddition,)
|
1146 |
+
|
1147 |
+
|
1148 |
+
@app.cell(hide_code=True)
|
1149 |
+
def _(mo):
|
1150 |
+
mo.md(
|
1151 |
+
"""
|
1152 |
+
- **Identity**: The identity element is `IntAddition(0)` (the additive identity).
|
1153 |
+
- **Composition**: The composition of two integers is their sum (`this.value + other.value`).
|
1154 |
+
"""
|
1155 |
+
)
|
1156 |
+
return
|
1157 |
+
|
1158 |
+
|
1159 |
+
@app.cell(hide_code=True)
|
1160 |
+
def _(mo):
|
1161 |
+
mo.md(
|
1162 |
+
"""
|
1163 |
+
### Defining the Length Functor
|
1164 |
+
|
1165 |
+
We now define the `length` function as a functor, mapping from the category of list concatenation to the category of integer addition:
|
1166 |
+
"""
|
1167 |
+
)
|
1168 |
+
return
|
1169 |
+
|
1170 |
+
|
1171 |
+
@app.cell
|
1172 |
+
def _(IntAddition):
|
1173 |
+
length = lambda l: IntAddition(len(l.value))
|
1174 |
+
return (length,)
|
1175 |
+
|
1176 |
+
|
1177 |
+
@app.cell(hide_code=True)
|
1178 |
+
def _(mo):
|
1179 |
+
mo.md("""This function takes an instance of `ListConcatenation`, computes its length, and returns an `IntAddition` instance with the computed length.""")
|
1180 |
+
return
|
1181 |
+
|
1182 |
+
|
1183 |
+
@app.cell(hide_code=True)
|
1184 |
+
def _(mo):
|
1185 |
+
mo.md(
|
1186 |
+
"""
|
1187 |
+
### Verifying Functor Laws
|
1188 |
+
|
1189 |
+
Now, let’s verify that `length` satisfies the two functor laws.
|
1190 |
+
|
1191 |
+
#### 1. **Identity Law**:
|
1192 |
+
The identity law states that applying the functor to the identity element of one category should give the identity element of the other category.
|
1193 |
+
"""
|
1194 |
+
)
|
1195 |
+
return
|
1196 |
+
|
1197 |
+
|
1198 |
+
@app.cell
|
1199 |
+
def _(IntAddition, ListConcatenation, length):
|
1200 |
+
length(ListConcatenation.id()) == IntAddition.id()
|
1201 |
+
return
|
1202 |
+
|
1203 |
+
|
1204 |
+
@app.cell(hide_code=True)
|
1205 |
+
def _(mo):
|
1206 |
+
mo.md("""This ensures that the length of an empty list (identity in the `ListConcatenation` category) is `0` (identity in the `IntAddition` category).""")
|
1207 |
+
return
|
1208 |
+
|
1209 |
+
|
1210 |
+
@app.cell(hide_code=True)
|
1211 |
+
def _(mo):
|
1212 |
+
mo.md(
|
1213 |
+
"""
|
1214 |
+
#### 2. **Composition Law**:
|
1215 |
+
The composition law states that the functor should preserve composition. Applying the functor to a composed element should be the same as composing the functor applied to the individual elements.
|
1216 |
+
"""
|
1217 |
+
)
|
1218 |
+
return
|
1219 |
+
|
1220 |
+
|
1221 |
+
@app.cell
|
1222 |
+
def _(ListConcatenation):
|
1223 |
+
lista = ListConcatenation([1, 2])
|
1224 |
+
listb = ListConcatenation([3, 4])
|
1225 |
+
return lista, listb
|
1226 |
+
|
1227 |
+
|
1228 |
+
@app.cell
|
1229 |
+
def _(IntAddition, ListConcatenation, length, lista, listb):
|
1230 |
+
length(ListConcatenation.compose(lista, listb)) == IntAddition.compose(
|
1231 |
+
length(lista), length(listb)
|
1232 |
+
)
|
1233 |
+
return
|
1234 |
+
|
1235 |
+
|
1236 |
+
@app.cell(hide_code=True)
|
1237 |
+
def _(mo):
|
1238 |
+
mo.md("""This ensures that the length of the concatenation of two lists is the same as the sum of the lengths of the individual lists.""")
|
1239 |
+
return
|
1240 |
+
|
1241 |
+
|
1242 |
+
@app.cell(hide_code=True)
|
1243 |
+
def _(mo):
|
1244 |
+
mo.md(
|
1245 |
+
"""
|
1246 |
+
# Further reading
|
1247 |
+
|
1248 |
+
- [The Trivial Monad](http://blog.sigfpe.com/2007/04/trivial-monad.html)
|
1249 |
+
- [Haskellwiki. Category Theory](https://en.wikibooks.org/wiki/Haskell/Category_theory)
|
1250 |
+
- [Haskellforall. The Category Design Pattern](https://www.haskellforall.com/2012/08/the-category-design-pattern.html)
|
1251 |
+
- [Haskellforall. The Functor Design Pattern](https://www.haskellforall.com/2012/09/the-functor-design-pattern.html)
|
1252 |
+
|
1253 |
+
/// attention | ATTENTION
|
1254 |
+
The functor design pattern doesn't work at all if you aren't using categories in the first place. This is why you should structure your tools using the compositional category design pattern so that you can take advantage of functors to easily mix your tools together.
|
1255 |
+
///
|
1256 |
+
|
1257 |
+
- [Haskellwiki. Functor](https://wiki.haskell.org/index.php?title=Functor)
|
1258 |
+
- [Haskellwiki. Typeclassopedia#Functor](https://wiki.haskell.org/index.php?title=Typeclassopedia#Functor)
|
1259 |
+
- [Haskellwiki. Typeclassopedia#Category](https://wiki.haskell.org/index.php?title=Typeclassopedia#Category)
|
1260 |
+
"""
|
1261 |
+
)
|
1262 |
+
return
|
1263 |
+
|
1264 |
+
|
1265 |
+
@app.cell(hide_code=True)
|
1266 |
+
def _():
|
1267 |
+
import marimo as mo
|
1268 |
+
return (mo,)
|
1269 |
+
|
1270 |
+
|
1271 |
+
@app.cell(hide_code=True)
|
1272 |
+
def _():
|
1273 |
+
from abc import abstractmethod, ABC
|
1274 |
+
return ABC, abstractmethod
|
1275 |
+
|
1276 |
+
|
1277 |
+
@app.cell(hide_code=True)
|
1278 |
+
def _():
|
1279 |
+
from dataclasses import dataclass
|
1280 |
+
from typing import Callable, Generic, TypeVar
|
1281 |
+
return Callable, Generic, TypeVar, dataclass
|
1282 |
+
|
1283 |
+
|
1284 |
+
@app.cell(hide_code=True)
|
1285 |
+
def _(TypeVar):
|
1286 |
+
a = TypeVar("a")
|
1287 |
+
b = TypeVar("b")
|
1288 |
+
c = TypeVar("c")
|
1289 |
+
return a, b, c
|
1290 |
+
|
1291 |
+
|
1292 |
+
if __name__ == "__main__":
|
1293 |
+
app.run()
|
functional_programming/CHANGELOG.md
ADDED
@@ -0,0 +1,11 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# Changelog of the functional-programming course
|
2 |
+
|
3 |
+
## 2025-03-11
|
4 |
+
|
5 |
+
* Demo version of notebook `05_functors.py`
|
6 |
+
|
7 |
+
## 2025-03-13
|
8 |
+
|
9 |
+
* `0.1.0` version of notebook `05_functors`
|
10 |
+
|
11 |
+
Thank [Akshay](https://github.com/akshayka) and [Haleshot](https://github.com/Haleshot) for reviewing
|
functional_programming/README.md
ADDED
@@ -0,0 +1,61 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# Learn Functional Programming
|
2 |
+
|
3 |
+
_🚧 This collection is a
|
4 |
+
[work in progress](https://github.com/marimo-team/learn/issues/51)._
|
5 |
+
|
6 |
+
This series of marimo notebooks introduces the powerful paradigm of functional
|
7 |
+
programming through Python. Taking inspiration from Haskell and Category Theory,
|
8 |
+
we'll build a strong foundation in FP concepts that can transform how you
|
9 |
+
approach software development.
|
10 |
+
|
11 |
+
## What You'll Learn
|
12 |
+
|
13 |
+
**Using only Python's standard library**, we'll construct functional programming
|
14 |
+
concepts from first principles.
|
15 |
+
|
16 |
+
Topics include:
|
17 |
+
|
18 |
+
- Recursion and higher-order functions
|
19 |
+
- Category theory fundamentals
|
20 |
+
- Functors, applicatives, and monads
|
21 |
+
- Composable abstractions for robust code
|
22 |
+
|
23 |
+
## Timeline & Collaboration
|
24 |
+
|
25 |
+
I'm currently studying functional programming and Haskell, estimating about 2
|
26 |
+
months or even longer to complete this series. The structure may evolve as the
|
27 |
+
project develops.
|
28 |
+
|
29 |
+
If you're interested in collaborating or have questions, please reach out to me
|
30 |
+
on Discord (@eugene.hs).
|
31 |
+
|
32 |
+
**Running notebooks.** To run a notebook locally, use
|
33 |
+
|
34 |
+
```bash
|
35 |
+
uvx marimo edit <URL>
|
36 |
+
```
|
37 |
+
|
38 |
+
For example, run the `Functor` tutorial with
|
39 |
+
|
40 |
+
```bash
|
41 |
+
uvx marimo edit https://github.com/marimo-team/learn/blob/main/Functional_programming/05_functors.py
|
42 |
+
```
|
43 |
+
|
44 |
+
You can also open notebooks in our online playground by appending `marimo.app/`
|
45 |
+
to a notebook's URL:
|
46 |
+
[marimo.app/github.com/marimo-team/learn/blob/main/functional_programming/05_functors.py](https://marimo.app/https://github.com/marimo-team/learn/blob/main/functional_programming/05_functors.py).
|
47 |
+
|
48 |
+
# Description of notebooks
|
49 |
+
|
50 |
+
Check [here](https://github.com/marimo-team/learn/issues/51) for current series
|
51 |
+
structure.
|
52 |
+
|
53 |
+
| Notebook | Description | References |
|
54 |
+
| ----------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
55 |
+
| [05. Category and Functors](https://github.com/marimo-team/learn/blob/main/Functional_programming/05_functors.py) | Learn why `len` is a _Functor_ from `list concatenation` to `integer addition`, how to _lift_ an ordinary function into a _computation context_, and how to write an _adapter_ between two categories. | - [The Trivial Monad](http://blog.sigfpe.com/2007/04/trivial-monad.html) <br> - [Haskellwiki. Category Theory](https://en.wikibooks.org/wiki/Haskell/Category_theory) <br> - [Haskellforall. The Category Design Pattern](https://www.haskellforall.com/2012/08/the-category-design-pattern.html) <br> - [Haskellforall. The Functor Design Pattern](https://www.haskellforall.com/2012/09/the-functor-design-pattern.html) <br> - [Haskellwiki. Functor](https://wiki.haskell.org/index.php?title=Functor) <br> - [Haskellwiki. Typeclassopedia#Functor](https://wiki.haskell.org/index.php?title=Typeclassopedia#Functor) <br> - [Haskellwiki. Typeclassopedia#Category](https://wiki.haskell.org/index.php?title=Typeclassopedia#Category) |
|
56 |
+
|
57 |
+
**Authors.**
|
58 |
+
|
59 |
+
Thanks to all our notebook authors!
|
60 |
+
|
61 |
+
- [métaboulie](https://github.com/metaboulie)
|