metaboulie commited on
Commit
8b10f04
Β·
1 Parent(s): 9b7fd9a

Demo version of 05_functors.py

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