File size: 40,408 Bytes
463e388
 
 
 
 
 
bfe46e3
8b10f04
 
 
d417768
8b10f04
 
 
6b8214a
 
 
 
8b10f04
6b8214a
8b10f04
6b8214a
 
 
8b10f04
6b8214a
8b10f04
6b8214a
8b10f04
6b8214a
 
 
 
8b10f04
6b8214a
8b10f04
6b8214a
 
8b10f04
d417768
bfe46e3
8b10f04
6b8214a
 
 
 
8b10f04
 
6b8214a
 
 
 
 
8b10f04
6b8214a
8b10f04
6b8214a
8b10f04
6b8214a
8b10f04
6b8214a
8b10f04
6b8214a
 
 
8b10f04
6b8214a
8b10f04
6b8214a
8b10f04
6b8214a
 
 
 
8b10f04
6b8214a
8b10f04
6b8214a
 
 
8b10f04
d417768
 
8b10f04
6b8214a
d417768
 
6b8214a
8b10f04
6b8214a
8b10f04
6b8214a
 
 
8b10f04
6b8214a
8b10f04
6b8214a
8b10f04
6b8214a
 
d417768
 
8b10f04
d417768
 
 
6b8214a
8b10f04
6b8214a
8b10f04
6b8214a
d417768
6b8214a
8b10f04
d417768
6b8214a
 
c6fe084
6b8214a
 
 
 
c6fe084
 
 
d417768
8b10f04
d417768
 
8b10f04
d417768
 
 
8b10f04
 
 
d417768
 
 
8b10f04
 
 
 
6b8214a
 
 
 
8b10f04
d417768
 
 
8b10f04
6b8214a
8b10f04
6b8214a
d417768
6b8214a
8b10f04
6b8214a
8b10f04
d417768
6b8214a
d417768
8b10f04
6b8214a
 
 
8b10f04
 
 
 
6b8214a
 
 
 
8b10f04
d417768
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6b8214a
 
8b10f04
 
 
c6fe084
d417768
8b10f04
d417768
 
8b10f04
d417768
 
 
8b10f04
 
d417768
 
 
 
c6fe084
 
8b10f04
6b8214a
 
 
 
8b10f04
d417768
8b10f04
6b8214a
d417768
6b8214a
8b10f04
6b8214a
8b10f04
6b8214a
d417768
6b8214a
8b10f04
6b8214a
8b10f04
6b8214a
d417768
6b8214a
8b10f04
d417768
8b10f04
6b8214a
8b10f04
6b8214a
8b10f04
6b8214a
 
 
8b10f04
6b8214a
8b10f04
6b8214a
 
 
8b10f04
6b8214a
8b10f04
6b8214a
 
 
8b10f04
 
 
 
6b8214a
 
 
 
8b10f04
6b8214a
8b10f04
6b8214a
8b10f04
6b8214a
 
 
 
8b10f04
d417768
 
8b10f04
6b8214a
d417768
 
6b8214a
d417768
6b8214a
 
8b10f04
6b8214a
8b10f04
6b8214a
 
 
8b10f04
 
 
 
6b8214a
 
 
 
8b10f04
6b8214a
8b10f04
6b8214a
 
8b10f04
6b8214a
bfe46e3
6b8214a
 
 
8b10f04
6b8214a
8b10f04
6b8214a
 
 
8b10f04
d417768
 
8b10f04
6b8214a
 
d417768
 
 
8b10f04
d417768
 
6b8214a
d417768
6b8214a
8b10f04
6b8214a
d417768
6b8214a
8b10f04
6b8214a
 
 
8b10f04
6b8214a
 
 
8b10f04
 
 
 
d417768
8b10f04
d417768
8b10f04
 
 
 
 
 
 
d417768
 
8b10f04
 
 
d417768
 
 
8b10f04
 
 
d417768
8b10f04
 
 
 
d417768
 
8b10f04
d417768
 
8b10f04
d417768
8b10f04
 
 
d417768
8b10f04
 
6b8214a
8b10f04
 
 
d417768
 
 
c6fe084
d417768
 
 
 
c6fe084
 
8b10f04
6b8214a
 
 
 
8b10f04
6b8214a
8b10f04
6b8214a
8b10f04
6b8214a
 
 
8b10f04
6b8214a
8b10f04
6b8214a
d417768
6b8214a
8b10f04
6b8214a
8b10f04
d417768
6b8214a
d417768
 
8b10f04
6b8214a
8b10f04
6b8214a
d417768
 
6b8214a
8b10f04
d417768
6b8214a
8b10f04
6b8214a
8b10f04
6b8214a
8b10f04
d417768
8b10f04
6b8214a
 
 
 
8b10f04
d417768
 
 
8b10f04
6b8214a
 
 
 
8b10f04
6b8214a
 
 
8b10f04
 
 
d417768
 
 
 
 
 
 
 
8b10f04
 
 
 
6b8214a
 
 
 
8b10f04
6b8214a
8b10f04
6b8214a
 
 
 
8b10f04
6b8214a
 
8b10f04
6b8214a
 
 
8b10f04
6b8214a
8b10f04
d417768
8b10f04
d417768
6b8214a
d417768
 
8b10f04
d417768
8b10f04
d417768
 
6b8214a
8b10f04
6b8214a
 
 
8b10f04
 
 
 
 
 
 
 
 
 
 
d417768
 
 
 
 
 
 
 
 
 
8b10f04
 
 
6b8214a
d417768
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8b10f04
 
 
c6fe084
d417768
8b10f04
d417768
 
8b10f04
d417768
 
 
 
8b10f04
d417768
 
8b10f04
 
 
 
d417768
 
8b10f04
 
 
6b8214a
 
 
bfe46e3
8b10f04
bfe46e3
8b10f04
6b8214a
d417768
6b8214a
d417768
6b8214a
8b10f04
d417768
 
 
8b10f04
d417768
 
 
6b8214a
 
 
8b10f04
 
 
 
d417768
8b10f04
d417768
8b10f04
 
 
 
 
 
 
d417768
 
8b10f04
d417768
 
8b10f04
d417768
 
8b10f04
 
d417768
8b10f04
d417768
8b10f04
 
d417768
 
 
8b10f04
d417768
 
 
8b10f04
 
6b8214a
8b10f04
 
 
 
6b8214a
 
8b10f04
 
 
d417768
 
 
 
 
 
8b10f04
 
 
 
6b8214a
 
 
 
8b10f04
d417768
8b10f04
6b8214a
8b10f04
6b8214a
8b10f04
d417768
8b10f04
6b8214a
d417768
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6b8214a
 
c6fe084
8b10f04
c6fe084
 
d417768
8b10f04
d417768
 
8b10f04
d417768
 
 
8b10f04
 
d417768
 
8b10f04
c6fe084
 
6b8214a
 
 
d417768
8b10f04
6b8214a
8b10f04
6b8214a
 
 
8b10f04
 
 
463e388
d417768
 
463e388
 
d417768
 
 
8b10f04
 
 
6b8214a
 
 
 
8b10f04
6b8214a
8b10f04
6b8214a
 
8b10f04
6b8214a
8b10f04
6b8214a
8b10f04
6b8214a
 
8b10f04
6b8214a
8b10f04
6b8214a
 
 
8b10f04
 
 
 
6b8214a
 
 
 
8b10f04
6b8214a
8b10f04
6b8214a
 
 
8b10f04
6b8214a
8b10f04
6b8214a
8b10f04
6b8214a
c6fe084
6b8214a
8b10f04
6b8214a
8b10f04
6b8214a
8b10f04
6b8214a
8b10f04
6b8214a
 
 
8b10f04
6b8214a
 
 
 
8b10f04
 
 
 
6b8214a
 
 
 
8b10f04
6b8214a
8b10f04
6b8214a
8b10f04
6b8214a
d417768
6b8214a
8b10f04
d417768
6b8214a
 
8b10f04
6b8214a
8b10f04
6b8214a
8b10f04
6b8214a
 
 
 
 
 
 
8b10f04
6b8214a
 
 
 
 
 
8b10f04
6b8214a
8b10f04
6b8214a
 
 
 
 
 
 
 
8b10f04
6b8214a
 
 
 
8b10f04
 
6b8214a
 
 
 
 
8b10f04
6b8214a
8b10f04
6b8214a
 
8b10f04
d417768
 
 
 
 
6b8214a
 
8b10f04
 
 
 
6b8214a
 
 
 
8b10f04
6b8214a
8b10f04
d417768
8b10f04
6b8214a
8b10f04
6b8214a
 
d417768
6b8214a
8b10f04
6b8214a
8b10f04
6b8214a
 
d417768
6b8214a
8b10f04
d417768
8b10f04
6b8214a
8b10f04
6b8214a
8b10f04
6b8214a
 
 
 
 
 
 
 
 
8b10f04
 
6b8214a
 
 
 
 
8b10f04
6b8214a
 
 
 
 
 
8b10f04
 
 
 
6b8214a
 
 
d417768
6b8214a
d417768
6b8214a
 
 
 
 
 
d417768
6b8214a
 
 
d417768
6b8214a
 
 
 
 
 
d417768
6b8214a
d417768
 
6b8214a
 
 
d417768
 
 
 
 
6b8214a
 
 
 
 
 
d417768
 
6b8214a
d417768
 
 
6b8214a
 
 
 
 
 
 
 
 
 
d417768
6b8214a
 
d417768
 
 
 
 
6b8214a
d417768
6b8214a
d417768
 
 
 
 
 
 
 
 
 
 
 
6b8214a
 
 
 
 
 
 
8b10f04
 
 
d417768
 
8b10f04
 
 
d417768
 
8b10f04
 
 
d417768
 
 
 
 
8b10f04
 
 
d417768
 
 
8b10f04
 
 
 
6b8214a
 
 
 
8b10f04
6b8214a
8b10f04
6b8214a
8b10f04
6b8214a
8b10f04
6b8214a
d417768
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6b8214a
 
c6fe084
8b10f04
c6fe084
 
d417768
8b10f04
d417768
 
8b10f04
 
d417768
bfe46e3
8b10f04
 
 
d417768
bfe46e3
 
 
8b10f04
c6fe084
 
6b8214a
 
 
 
 
 
 
c6fe084
8b10f04
c6fe084
 
6b8214a
 
 
 
8b10f04
6b8214a
d417768
 
 
 
 
 
 
 
 
 
 
 
 
 
6b8214a
 
c6fe084
8b10f04
c6fe084
 
 
8b10f04
 
 
 
 
 
 
 
 
 
 
c6fe084
8b10f04
c6fe084
 
6b8214a
 
 
 
 
 
 
c6fe084
8b10f04
c6fe084
 
6b8214a
 
 
 
8b10f04
6b8214a
d417768
 
 
 
6b8214a
 
c6fe084
8b10f04
c6fe084
d417768
c6fe084
8b10f04
c6fe084
 
8b10f04
c6fe084
6b8214a
 
c6fe084
 
8b10f04
c6fe084
6b8214a
 
 
 
8b10f04
6b8214a
8b10f04
6b8214a
 
d417768
 
 
 
 
6b8214a
 
8b10f04
 
 
 
6b8214a
 
c6fe084
8b10f04
 
 
6b8214a
 
 
 
 
8b10f04
d417768
 
 
 
 
 
 
 
 
8b10f04
463e388
c6fe084
 
 
6b8214a
 
8b10f04
 
 
d417768
 
 
 
 
 
 
 
 
 
 
 
8b10f04
6b8214a
 
 
 
8b10f04
6b8214a
 
 
 
8b10f04
6b8214a
 
 
8b10f04
6b8214a
 
 
 
 
8b10f04
 
 
 
 
 
463e388
8b10f04
 
 
 
 
c6fe084
8b10f04
 
 
6b8214a
 
 
d417768
 
463e388
6b8214a
463e388
 
d417768
 
 
 
8b10f04
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
# /// script
# requires-python = ">=3.9"
# dependencies = [
#     "marimo",
# ]
# ///

import marimo

__generated_with = "0.11.17"
app = marimo.App(app_title="Category Theory and Functors")


@app.cell(hide_code=True)
def _(mo):
    mo.md(
        """
        # Category Theory and Functors

        In this notebook, you will learn:

        * Why `length` is a *functor* from the category of `list concatenation` to the category of `integer addition`
        * How to *lift* an ordinary function into a specific *computational context*
        * How to write an *adapter* between two categories

        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.

        /// admonition | Intuitions 

        - 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.
        - Another intuition is that a `Functor` represents some sort of **computational context**.
        - Mathematically, `Functors` generalize the idea of a container or a computational context.
        ///

        We will start with intuition, introduce the basics of category theory, and then examine functors from a categorical perspective.

        /// details | Notebook metadata
            type: info

        version: 0.1.1 | last modified: 2025-03-16 | author: [mΓ©taboulie](https://github.com/metaboulie)<br/>
        reviewer: [Haleshot](https://github.com/Haleshot)

        ///
        """
    )
    return


@app.cell(hide_code=True)
def _(mo):
    mo.md(
        """
        # Functor as a Computational Context

        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.

        To understand this, let's look at a simple example.

        ## [The One-Way Wrapper Design Pattern](http://blog.sigfpe.com/2007/04/trivial-monad.html)

        Often, we need to wrap data in some kind of context. However, when performing operations on wrapped data, we typically have to:

        1. Unwrap the data.
        2. Modify the unwrapped data.
        3. Rewrap the modified data.

        This process is tedious and inefficient. Instead, we want to wrap data **once** and apply functions directly to the wrapped data without unwrapping it.

        /// admonition | Rules for a One-Way Wrapper

        1. We can wrap values, but we cannot unwrap them.
        2. We should still be able to apply transformations to the wrapped data.
        3. Any operation that depends on wrapped data should itself return a wrapped result.
        ///

        Let's define such a `Wrapper` class:

        ```python
        from dataclasses import dataclass
        from typing import Callable, Generic, TypeVar

        A = TypeVar("A")
        B = TypeVar("B")

        @dataclass
        class Wrapper(Generic[A]):
            value: A
        ```

        Now, we can create an instance of wrapped data:

        ```python
        wrapped = Wrapper(1)
        ```

        ### Mapping Functions Over Wrapped Data

        To modify wrapped data while keeping it wrapped, we define an `fmap` method:

        ```python
        @dataclass
        class Wrapper(Functor, Generic[A]):
            value: A

            @classmethod
            def fmap(cls, f: Callable[[A], B], a: "Wrapper[A]") -> "Wrapper[B]":
                return Wrapper(f(a.value))
        ```

        Now, we can apply transformations without unwrapping:

        ```python
        >>> Wrapper.fmap(lambda x: x + 1, wrapper)
        Wrapper(value=2)

        >>> Wrapper.fmap(lambda x: [x], wrapper)
        Wrapper(value=[1])
        ```

        > Try using the `Wrapper` in the cell below.
        """
    )
    return


@app.cell
def _(A, B, Callable, Functor, Generic, dataclass, pp):
    @dataclass
    class Wrapper(Functor, Generic[A]):
        value: A

        @classmethod
        def fmap(cls, f: Callable[[A], B], a: "Wrapper[A]") -> "Wrapper[B]":
            return Wrapper(f(a.value))


    wrapper = Wrapper(1)

    pp(Wrapper.fmap(lambda x: x + 1, wrapper))
    pp(Wrapper.fmap(lambda x: [x], wrapper))
    return Wrapper, wrapper


@app.cell(hide_code=True)
def _(mo):
    mo.md(
        """
        We can analyze the type signature of `fmap` for `Wrapper`:

        * `f` is of type `Callable[[A], B]`
        * `a` is of type `Wrapper[A]`
        * The return value is of type `Wrapper[B]`

        Thus, in Python's type system, we can express the type signature of `fmap` as:

        ```python
        fmap(f: Callable[[A], B], a: Wrapper[A]) -> Wrapper[B]:
        ```

        Essentially, `fmap`:

        1. Takes a function `Callable[[A], B]` and a `Wrapper[A]` instance as input.
        2. Applies the function to the value inside the wrapper.
        3. Returns a new `Wrapper[B]` instance with the transformed value, leaving the original wrapper and its internal data unmodified.

        Now, let's examine `list` as a similar kind of wrapper.
        """
    )
    return


@app.cell(hide_code=True)
def _(mo):
    mo.md(
        """
        ## The List Wrapper

        We can define a `List` class to represent a wrapped list that supports `fmap`:

        ```python
        @dataclass
        class List(Functor, Generic[A]):
            value: list[A]

            @classmethod
            def fmap(cls, f: Callable[[A], B], a: "List[A]") -> "List[B]":
                return List([f(x) for x in a.value])
        ```

        Now, we can apply transformations:

        ```python
        >>> flist = List([1, 2, 3, 4])
        >>> List.fmap(lambda x: x + 1, flist)
        List(value=[2, 3, 4, 5])
        >>> List.fmap(lambda x: [x], flist)
        List(value=[[1], [2], [3], [4]])
        ```
        """
    )
    return


@app.cell
def _(A, B, Callable, Functor, Generic, dataclass, pp):
    @dataclass
    class List(Functor, Generic[A]):
        value: list[A]

        @classmethod
        def fmap(cls, f: Callable[[A], B], a: "List[A]") -> "List[B]":
            return List([f(x) for x in a.value])


    flist = List([1, 2, 3, 4])
    pp(List.fmap(lambda x: x + 1, flist))
    pp(List.fmap(lambda x: [x], flist))
    return List, flist


@app.cell(hide_code=True)
def _(mo):
    mo.md(
        """
        ### Extracting the Type of `fmap`

        The type signature of `fmap` for `List` is:

        ```python
        fmap(f: Callable[[A], B], a: List[A]) -> List[B]
        ```

        Similarly, for `Wrapper`:

        ```python
        fmap(f: Callable[[A], B], a: Wrapper[A]) -> Wrapper[B]
        ```

        Both follow the same pattern, which we can generalize as:

        ```python
        fmap(f: Callable[[A], B], a: Functor[A]) -> Functor[B]
        ```

        where `Functor` can be `Wrapper`, `List`, or any other wrapper type that follows the same structure.

        ### Functors in Haskell (optional)

        In Haskell, the type of `fmap` is:

        ```haskell
        fmap :: Functor f => (a -> b) -> f a -> f b
        ```

        or equivalently:

        ```haskell
        fmap :: Functor f => (a -> b) -> (f a -> f b)
        ```

        This means that `fmap` **lifts** an ordinary function into the **functor world**, allowing it to operate within a computational context.

        Now, let's define an abstract class for `Functor`.
        """
    )
    return


@app.cell(hide_code=True)
def _(mo):
    mo.md(
        """
        ## Defining Functor

        Recall that, a **Functor** is an abstraction that allows us to apply a function to values inside a computational context while preserving its structure. 

        To define `Functor` in Python, we use an abstract base class:

        ```python
        from dataclasses import dataclass
        from typing import Callable, Generic, TypeVar
        from abc import ABC, abstractmethod

        A = TypeVar("A")
        B = TypeVar("B")

        @dataclass
        class Functor(ABC, Generic[A]):
            @classmethod
            @abstractmethod
            def fmap(f: Callable[[A], B], a: "Functor[A]") -> "Functor[B]":
                raise NotImplementedError
        ```

        We can now extend custom wrappers, containers, or computation contexts with this `Functor` base class, implement the `fmap` method, and apply any function.

        Next, let's implement a more complex data structure: [RoseTree](https://en.wikipedia.org/wiki/Rose_tree).
        """
    )
    return


@app.cell(hide_code=True)
def _(mo):
    mo.md(
        """
        ## Case Study: RoseTree

        A **RoseTree** is a tree where:

        - Each node holds a **value**.
        - Each node has a **list of child nodes** (which are also RoseTrees).

        This structure is useful for representing hierarchical data, such as:

        - Abstract Syntax Trees (ASTs)
        - File system directories
        - Recursive computations

        We can implement `RoseTree` by extending the `Functor` class:

        ```python
        from dataclasses import dataclass
        from typing import Callable, Generic, TypeVar

        A = TypeVar("A")
        B = TypeVar("B")

        @dataclass
        class RoseTree(Functor, Generic[a]):
    
            value: A
            children: list["RoseTree[A]"]

            @classmethod
            def fmap(cls, f: Callable[[A], B], a: "RoseTree[A]") -> "RoseTree[B]":
                return RoseTree(
                    f(a.value), [cls.fmap(f, child) for child in a.children]
                )

            def __repr__(self) -> str:
                return f"Node: {self.value}, Children: {self.children}"
        ```

        - The function is applied **recursively** to each node's value.
        - The tree structure **remains unchanged**.
        - Only the values inside the tree are modified.

        > Try using `RoseTree` in the cell below.
        """
    )
    return


@app.cell(hide_code=True)
def _(A, B, Callable, Functor, Generic, dataclass, mo):
    @dataclass
    class RoseTree(Functor, Generic[A]):
        """
        ### Doc: RoseTree

        A Functor implementation of `RoseTree`, allowing transformation of values while preserving the tree structure.

        **Attributes**

        - `value (A)`: The value stored in the node.
        - `children (list[RoseTree[A]])`: A list of child nodes forming the tree structure.

        **Methods:**

        - `fmap(f: Callable[[A], B], a: "RoseTree[A]") -> "RoseTree[B]"`

            Applies a function to each value in the tree, producing a new `RoseTree[b]` with transformed values.

        **Implementation logic:**

          - The function `f` is applied to the root node's `value`.
          - Each child in `children` recursively calls `fmap`, ensuring all values in the tree are mapped.
          - The overall tree structure remains unchanged.
        """

        value: A
        children: list["RoseTree[A]"]

        @classmethod
        def fmap(cls, f: Callable[[A], B], a: "RoseTree[A]") -> "RoseTree[B]":
            return RoseTree(
                f(a.value), [cls.fmap(f, child) for child in a.children]
            )

        def __repr__(self) -> str:
            return f"Node: {self.value}, Children: {self.children}"


    mo.md(RoseTree.__doc__)
    return (RoseTree,)


@app.cell
def _(RoseTree, pp):
    rosetree = RoseTree(1, [RoseTree(2, []), RoseTree(3, [RoseTree(4, [])])])

    pp(rosetree)
    pp(RoseTree.fmap(lambda x: [x], rosetree))
    pp(RoseTree.fmap(lambda x: RoseTree(x, []), rosetree))
    return (rosetree,)


@app.cell(hide_code=True)
def _(mo):
    mo.md(
        """
        ## Generic Functions that can be Used with Any Functor

        One of the powerful features of functors is that we can write **generic functions** that can work with any functor.

        Remember that in Haskell, the type of `fmap` can be written as:

        ```haskell
        fmap :: Functor f => (a -> b) -> (f a -> f b)
        ```

        Translating to Python, we get:

        ```python
        def fmap(func: Callable[[A], B]) -> Callable[[Functor[A]], Functor[B]]
        ```

        This means that `fmap`:

        - Takes an **ordinary function** `Callable[[A], B]` as input.
        - Outputs a function that:
            - Takes a **functor** of type `Functor[A]` as input.
            - Outputs a **functor** of type `Functor[B]`.

        We can implement a similar idea in Python:

        ```python
        fmap = lambda f, functor: functor.__class__.fmap(f, functor)
        inc = lambda functor: fmap(lambda x: x + 1, functor)
        ```

        - **`fmap`**: Lifts an ordinary function (`f`) to the functor world, allowing the function to operate on the wrapped value inside the functor.
        - **`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.

        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.

        ### Applying the `inc` Function to Various Functors

        You can now apply `inc` to any functor like `Wrapper`, `List`, or `RoseTree`:

        ```python
        # Applying `inc` to a Wrapper
        wrapper = Wrapper(5)
        inc(wrapper)  # Wrapper(value=6)

        # Applying `inc` to a List
        list_wrapper = List([1, 2, 3])
        inc(list_wrapper)  # List(value=[2, 3, 4])

        # Applying `inc` to a RoseTree
        tree = RoseTree(1, [RoseTree(2, []), RoseTree(3, [])])
        inc(tree)  # RoseTree(value=2, children=[RoseTree(value=3, children=[]), RoseTree(value=4, children=[])])
        ```

        > Try using `fmap` in the cell below.
        """
    )
    return


@app.cell
def _(flist, pp, rosetree, wrapper):
    fmap = lambda f, functor: functor.__class__.fmap(f, functor)
    inc = lambda functor: fmap(lambda x: x + 1, functor)

    pp(inc(wrapper))
    pp(inc(flist))
    pp(inc(rosetree))
    return fmap, inc


@app.cell(hide_code=True)
def _(mo):
    mo.md(
        """
        ## Functor laws

        In addition to providing a function `fmap` of the specified type, functors are also required to satisfy two equational laws:

        ```haskell
        fmap id = id                    -- fmap preserves identity
        fmap (g . h) = fmap g . fmap h  -- fmap distributes over composition
        ```

        1. `fmap` should preserve the **identity function**, in the sense that applying `fmap` to this function returns the same function as the result.
        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`.

        /// admonition | 
        - 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.
        ///

        ### Functor Law Verification

        We can define `id` and `compose` in `Python` as below:

        ```python
        id = lambda x: x
        compose = lambda f, g: lambda x: f(g(x))
        ```

        We can add a helper function `check_functor_law` to verify that an instance satisfies the functor laws.

        ```Python
        check_functor_law = lambda functor: repr(fmap(id, functor)) == repr(functor)
        ```

        We can verify the functor we've defined.
        """
    )
    return


@app.cell
def _():
    id = lambda x: x
    compose = lambda f, g: lambda x: f(g(x))
    return compose, id


@app.cell
def _(fmap, id):
    check_functor_law = lambda functor: repr(fmap(id, functor)) == repr(functor)
    return (check_functor_law,)


@app.cell
def _(check_functor_law, flist, pp, rosetree, wrapper):
    for functor in (wrapper, flist, rosetree):
        pp(check_functor_law(functor))
    return (functor,)


@app.cell(hide_code=True)
def _(mo):
    mo.md(
        """
        And here is an `EvilFunctor`. We can verify it's not a valid `Functor`.

        ```python
        @dataclass
        class EvilFunctor(Functor, Generic[A]):
            value: list[A]

            @classmethod
            def fmap(cls, f: Callable[[A], B], a: "EvilFunctor[A]") -> "EvilFunctor[B]":
                return (
                    cls([a.value[0]] * 2 + list(map(f, a.value[1:])))
                    if a.value
                    else []
                )
        ```
        """
    )
    return


@app.cell
def _(A, B, Callable, Functor, Generic, check_functor_law, dataclass, pp):
    @dataclass
    class EvilFunctor(Functor, Generic[A]):
        value: list[A]

        @classmethod
        def fmap(
            cls, f: Callable[[A], B], a: "EvilFunctor[A]"
        ) -> "EvilFunctor[B]":
            return (
                cls([a.value[0]] * 2 + [f(x) for x in a.value[1:]])
                if a.value
                else []
            )


    pp(check_functor_law(EvilFunctor([1, 2, 3, 4])))
    return (EvilFunctor,)


@app.cell(hide_code=True)
def _(mo):
    mo.md(
        """
        ## Final definition of Functor

        We can now draft the final definition of `Functor` with some utility functions.

        ```Python
            @classmethod
            @abstractmethod
            def fmap(cls, f: Callable[[A], B], a: "Functor[A]") -> "Functor[B]":
                return NotImplementedError

            @classmethod
            def const_fmap(cls, a: "Functor[A]", b: B) -> "Functor[B]":
                return cls.fmap(lambda _: b, a)

            @classmethod
            def void(cls, a: "Functor[A]") -> "Functor[None]":
                return cls.const_fmap(a, None)
        ```
        """
    )
    return


@app.cell(hide_code=True)
def _(A, ABC, B, Callable, Generic, abstractmethod, dataclass, mo):
    @dataclass
    class Functor(ABC, Generic[A]):
        """
        ### Doc: Functor

        A generic interface for types that support mapping over their values.

        **Methods:**

        - `fmap(f: Callable[[A], B], a: Functor[A]) -> Functor[B]`
          Abstract method to apply a function to all values inside a functor.

        - `const_fmap(a: "Functor[A]", b: B) -> Functor[B]`
          Replaces all values inside a functor with a constant `b`, preserving the original structure.

        - `void(a: "Functor[A]") -> Functor[None]`
          Equivalent to `const_fmap(a, None)`, transforming all values in a functor into `None`.
        """

        @classmethod
        @abstractmethod
        def fmap(cls, f: Callable[[A], B], a: "Functor[A]") -> "Functor[B]":
            return NotImplementedError

        @classmethod
        def const_fmap(cls, a: "Functor[A]", b: B) -> "Functor[B]":
            return cls.fmap(lambda _: b, a)

        @classmethod
        def void(cls, a: "Functor[A]") -> "Functor[None]":
            return cls.const_fmap(a, None)


    mo.md(Functor.__doc__)
    return (Functor,)


@app.cell(hide_code=True)
def _(mo):
    mo.md("""> Try with utility functions in the cell below""")
    return


@app.cell
def _(List, RoseTree, flist, pp, rosetree):
    pp(RoseTree.const_fmap(rosetree, "Ξ»"))
    pp(RoseTree.void(rosetree))
    pp(List.const_fmap(flist, "Ξ»"))
    pp(List.void(flist))
    return


@app.cell(hide_code=True)
def _(mo):
    mo.md(
        """
        ## Functors for Non-Iterable Types

        In the previous examples, we implemented functors for **iterables**, like `List` and `RoseTree`, which are inherently **iterable types**. This is a natural fit for functors, as iterables can be mapped over.

        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.

        ### The Maybe Functor

        One example is the **`Maybe`** type from Haskell, which is used to represent computations that can either result in a value or no value (`Nothing`). 

        We can define the `Maybe` functor as below:

        ```python
        @dataclass
        class Maybe(Functor, Generic[A]):
            value: None | A

            @classmethod
            def fmap(cls, f: Callable[[A], B], a: "Maybe[A]") -> "Maybe[B]":
                return (
                    cls(None) if a.value is None else cls(f(a.value))
                )

            def __repr__(self):
                return "Nothing" if self.value is None else repr(self.value)
        ```
        """
    )
    return


@app.cell
def _(A, B, Callable, Functor, Generic, dataclass):
    @dataclass
    class Maybe(Functor, Generic[A]):
        value: None | A

        @classmethod
        def fmap(cls, f: Callable[[A], B], a: "Maybe[A]") -> "Maybe[B]":
            return cls(None) if a.value is None else cls(f(a.value))

        def __repr__(self):
            return "Nothing" if self.value is None else repr(self.value)
    return (Maybe,)


@app.cell(hide_code=True)
def _(mo):
    mo.md(
        """
        **`Maybe`** is a functor that can either hold a value or be `Nothing` (equivalent to `None` in Python). The `fmap` method applies a function to the value inside the functor, if it exists. If the value is `None` (representing `Nothing`), `fmap` simply returns `None`.

        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.

        > Try using `Maybe` in the cell below.
        """
    )
    return


@app.cell
def _(Maybe, pp):
    mint = Maybe(1)
    mnone = Maybe(None)

    pp(Maybe.fmap(lambda x: x + 1, mint))
    pp(Maybe.fmap(lambda x: x + 1, mnone))
    return mint, mnone


@app.cell(hide_code=True)
def _(mo):
    mo.md(
        """
        ## Limitations of Functor

        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:

        ```haskell
        fmap0 :: a -> f a

        fmap1 :: (a -> b) -> f a -> f b

        fmap2 :: (a -> b -> c) -> f a -> f b -> f c

        fmap3 :: (a -> b -> c -> d) -> f a -> f b -> f c -> f d
        ```

        And we have to declare a special version of the functor class for each case.

        We will learn how to resolve this problem in the next notebook on `Applicatives`.
        """
    )
    return


@app.cell(hide_code=True)
def _(mo):
    mo.md(
        """
        # Introduction to Categories

        A [category](https://en.wikibooks.org/wiki/Haskell/Category_theory#Introduction_to_categories) is, in essence, a simple collection. It has three components: 

        - A collection of **objects**.
        - 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$.
        - 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$.

        ## Category laws

        There are three laws that categories need to follow. 

        1. The composition of morphisms needs to be **associative**. Symbolically, $f ∘ (g ∘ h) = (f ∘ g) ∘ h$

            - Morphisms are applied right to left, so with $f ∘ g$ first $g$ is applied, then $f$. 

        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$. 

        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$

        /// attention | The definition of a category does not define: 

        - what `∘` is,
        - what `id` is, or
        - what `f`, `g`, and `h` might be. 

        Instead, category theory leaves it up to us to discover what they might be.
        ///
        """
    )
    return


@app.cell(hide_code=True)
def _(mo):
    mo.md(
        """
        ## The Python category

        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.

        Remember that we defined the `id` and `compose` function above as:

        ```Python
        def id(x: Generic[A]) -> Generic[A]:
            return x

        def compose(f: Callable[[B], C], g: Callable[[A], B]) -> Callable[[A], C]:
            return lambda x: f(g(x))  
        ```

        We can check second law easily. 

        For the first law, we have:

        ```python
        # compose(f, g) = lambda x: f(g(x))
        f ∘ (g ∘ h) 
        = compose(f, compose(g, h)) 
        = lambda x: f(compose(g, h)(x))
        = lambda x: f(lambda y: g(h(y))(x))
        = lambda x: f(g(h(x)))

        (f ∘ g) ∘ h 
        = compose(compose(f, g), h)
        = lambda x: compose(f, g)(h(x))
        = lambda x: lambda y: f(g(y))(h(x))
        = lambda x: f(g(h(x)))
        ```

        For the third law, we have: 

        ```python
        g ∘ id_A 
        = compose(g: Callable[[a], b], id: Callable[[a], a]) -> Callable[[a], b]
        = lambda x: g(id(x))
        = lambda x: g(x) # id(x) = x
        = g
        ```
        the similar proof can be applied to $id_B ∘ g =g$.

        Thus `Py` is a valid category.
        """
    )
    return


@app.cell(hide_code=True)
def _(mo):
    mo.md(
        """
        # Functors, again

        A functor is essentially a transformation between categories, so given categories $C$ and $D$, a functor $F : C β†’ D$:

        - Maps any object $A$ in $C$ to $F ( A )$, in $D$.
        - Maps morphisms $f : A β†’ B$ in $C$ to $F ( f ) : F ( A ) β†’ F ( B )$ in $D$.

        /// admonition | 

        Endofunctors are functors from a category to itself.

        ///
        """
    )
    return


@app.cell(hide_code=True)
def _(mo):
    mo.md(
        """
        ## Functors on the category of Python

        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. 

        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 `Callable[[RoseTree[T]], RoseTree[U]]` for types `T`, `U`.

        Recall the definition of `Functor`:

        ```Python
        @dataclass
        class Functor(ABC, Generic[A])
        ```

        And RoseTree: 

        ```Python
        @dataclass
        class RoseTree(Functor, Generic[A])
        ```

        **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 `Callable[[A], B]` to a function `Callable[[RoseTree[A]], RoseTree[B]]`.

        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. 

        To sum up:

        - We work in the category **Py** and its subcategories.  
        - **Objects** are types (e.g., `int`, `str`, `list`).  
        - **Morphisms** are functions (`Callable[[A], B]`).  
        - **Things that take a type and return another type** are type constructors (`RoseTree[T]`).  
        - **Things that take a function and return another function** are higher-order functions (`Callable[[Callable[[A], B]], Callable[[C], D]]`).  
        - **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.
        """
    )
    return


@app.cell(hide_code=True)
def _(mo):
    mo.md(
        """
        ## Functor laws, again

        Once again there are a few axioms that functors have to obey. 

        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)}}$
        2. Functors must distribute over morphism composition, i.e. ${\displaystyle F(f\circ g)=F(f)\circ F(g)}$
        """
    )
    return


@app.cell(hide_code=True)
def _(mo):
    mo.md(
        """
        Remember that we defined the `fmap`, `id` and `compose` as 
        ```python
        fmap = lambda f, functor: functor.__class__.fmap(f, functor)  
        id = lambda x: x
        compose = lambda f, g: lambda x: f(g(x))
        ```

        Let's prove that `fmap` is a functor.

        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. `List`, `RoseTree`, `Maybe` and more):

        **Notice that** in this case, we can actually view `fmap` as:
        ```python
        fmap = lambda f, functor: functor.fmap(f, functor)  
        ```

        We define `WrapperCategory` as:

        ```python
        @dataclass
        class WrapperCategory:
            @staticmethod
            def id(wrapper: Wrapper[A]) -> Wrapper[A]:
                return Wrapper(wrapper.value)

            @staticmethod
            def compose(
                f: Callable[[Wrapper[B]], Wrapper[C]],
                g: Callable[[Wrapper[A]], Wrapper[B]],
                wrapper: Wrapper[A]
            ) -> Callable[[Wrapper[A]], Wrapper[C]]:
                return f(g(Wrapper(wrapper.value)))
        ```

        And `Wrapper` is:

        ```Python
        @dataclass
        class Wrapper(Functor, Generic[A]):
            value: A

            @classmethod
            def fmap(cls, f: Callable[[A], B], a: "Wrapper[A]") -> "Wrapper[B]":
                return Wrapper(f(a.value))
        ```
        """
    )
    return


@app.cell(hide_code=True)
def _(mo):
    mo.md(
        """
        We can prove that:

        ```python
        fmap(id, wrapper)
        = Wrapper.fmap(id, wrapper)
        = Wrapper(id(wrapper.value))
        = Wrapper(wrapper.value)
        = WrapperCategory.id(wrapper)
        ```
        and:
        ```python
        fmap(compose(f, g), wrapper)
        = Wrapper.fmap(compose(f, g), wrapper)
        = Wrapper(compose(f, g)(wrapper.value))
        = Wrapper(f(g(wrapper.value)))

        WrapperCategory.compose(fmap(f, wrapper), fmap(g, wrapper), wrapper)
        = fmap(f, wrapper)(fmap(g, wrapper)(wrapper))
        = fmap(f, wrapper)(Wrapper.fmap(g, wrapper))
        = fmap(f, wrapper)(Wrapper(g(wrapper.value)))
        = Wrapper.fmap(f, Wrapper(g(wrapper.value)))
        = Wrapper(f(Wrapper(g(wrapper.value)).value))
        = Wrapper(f(g(wrapper.value)))  # Wrapper(g(wrapper.value)).value = g(wrapper.value)
        ```

        So our `Wrapper` is a valid `Functor`.

        > Try validating functor laws for `Wrapper` below.
        """
    )
    return


@app.cell
def _(A, B, C, Callable, Wrapper, dataclass):
    @dataclass
    class WrapperCategory:
        @staticmethod
        def id(wrapper: Wrapper[A]) -> Wrapper[A]:
            return Wrapper(wrapper.value)

        @staticmethod
        def compose(
            f: Callable[[Wrapper[B]], Wrapper[C]],
            g: Callable[[Wrapper[A]], Wrapper[B]],
            wrapper: Wrapper[A],
        ) -> Callable[[Wrapper[A]], Wrapper[C]]:
            return f(g(Wrapper(wrapper.value)))
    return (WrapperCategory,)


@app.cell
def _(WrapperCategory, fmap, id, pp, wrapper):
    pp(fmap(id, wrapper) == WrapperCategory.id(wrapper))
    return


@app.cell(hide_code=True)
def _(mo):
    mo.md(
        """
        ## Length as a Functor

        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.

        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**.

        ### Category of List Concatenation

        First, let’s define the category of list concatenation:

        ```python
        @dataclass
        class ListConcatenation(Generic[A]):
            value: list[A]

            @staticmethod
            def id() -> "ListConcatenation[A]":
                return ListConcatenation([])

            @staticmethod
            def compose(
                this: "ListConcatenation[A]", other: "ListConcatenation[A]"
            ) -> "ListConcatenation[a]":
                return ListConcatenation(this.value + other.value)
        ```
        """
    )
    return


@app.cell
def _(A, Generic, dataclass):
    @dataclass
    class ListConcatenation(Generic[A]):
        value: list[A]

        @staticmethod
        def id() -> "ListConcatenation[A]":
            return ListConcatenation([])

        @staticmethod
        def compose(
            this: "ListConcatenation[A]", other: "ListConcatenation[A]"
        ) -> "ListConcatenation[a]":
            return ListConcatenation(this.value + other.value)
    return (ListConcatenation,)


@app.cell(hide_code=True)
def _(mo):
    mo.md(
        """
        - **Identity**: The identity element is an empty list (`ListConcatenation([])`).
        - **Composition**: The composition of two lists is their concatenation (`this.value + other.value`).
        """
    )
    return


@app.cell(hide_code=True)
def _(mo):
    mo.md(
        """
        ### Category of Integer Addition

        Now, let's define the category of integer addition:

        ```python
        @dataclass
        class IntAddition:
            value: int

            @staticmethod
            def id() -> "IntAddition":
                return IntAddition(0)

            @staticmethod
            def compose(this: "IntAddition", other: "IntAddition") -> "IntAddition":
                return IntAddition(this.value + other.value)
        ```
        """
    )
    return


@app.cell
def _(dataclass):
    @dataclass
    class IntAddition:
        value: int

        @staticmethod
        def id() -> "IntAddition":
            return IntAddition(0)

        @staticmethod
        def compose(this: "IntAddition", other: "IntAddition") -> "IntAddition":
            return IntAddition(this.value + other.value)
    return (IntAddition,)


@app.cell(hide_code=True)
def _(mo):
    mo.md(
        """
        - **Identity**: The identity element is `IntAddition(0)` (the additive identity).
        - **Composition**: The composition of two integers is their sum (`this.value + other.value`).
        """
    )
    return


@app.cell(hide_code=True)
def _(mo):
    mo.md(
        """
        ### Defining the Length Functor

        We now define the `length` function as a functor, mapping from the category of list concatenation to the category of integer addition:

        ```python
        length = lambda l: IntAddition(len(l.value))
        ```
        """
    )
    return


@app.cell(hide_code=True)
def _(IntAddition):
    length = lambda l: IntAddition(len(l.value))
    return (length,)


@app.cell(hide_code=True)
def _(mo):
    mo.md("""This function takes an instance of `ListConcatenation`, computes its length, and returns an `IntAddition` instance with the computed length.""")
    return


@app.cell(hide_code=True)
def _(mo):
    mo.md(
        """
        ### Verifying Functor Laws

        Now, let’s verify that `length` satisfies the two functor laws.

        #### 1. **Identity Law**:
        The identity law states that applying the functor to the identity element of one category should give the identity element of the other category.

        ```python
        > length(ListConcatenation.id()) == IntAddition.id()
        True
        ```
        """
    )
    return


@app.cell(hide_code=True)
def _(mo):
    mo.md("""This ensures that the length of an empty list (identity in the `ListConcatenation` category) is `0` (identity in the `IntAddition` category).""")
    return


@app.cell(hide_code=True)
def _(mo):
    mo.md(
        """
        #### 2. **Composition Law**:
        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.

        ```python
        > lista = ListConcatenation([1, 2])
        > listb = ListConcatenation([3, 4])
        > length(ListConcatenation.compose(lista, listb)) == IntAddition.compose(
        >     length(lista), length(listb)
        > )
        True
        ```
        """
    )
    return


@app.cell(hide_code=True)
def _(mo):
    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.""")
    return


@app.cell
def _(IntAddition, ListConcatenation, length, pp):
    pp(length(ListConcatenation.id()) == IntAddition.id())
    lista = ListConcatenation([1, 2])
    listb = ListConcatenation([3, 4])
    pp(
        length(ListConcatenation.compose(lista, listb))
        == IntAddition.compose(length(lista), length(listb))
    )
    return lista, listb


@app.cell(hide_code=True)
def _(mo):
    mo.md(
        """
        # Further reading

        - [The Trivial Monad](http://blog.sigfpe.com/2007/04/trivial-monad.html)
        - [Haskellwiki. Category Theory](https://en.wikibooks.org/wiki/Haskell/Category_theory)
        - [Haskellforall. The Category Design Pattern](https://www.haskellforall.com/2012/08/the-category-design-pattern.html)
        - [Haskellforall. The Functor Design Pattern](https://www.haskellforall.com/2012/09/the-functor-design-pattern.html)

            /// attention | ATTENTION 
            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. 
            ///

        - [Haskellwiki. Functor](https://wiki.haskell.org/index.php?title=Functor)
        - [Haskellwiki. Typeclassopedia#Functor](https://wiki.haskell.org/index.php?title=Typeclassopedia#Functor)
        - [Haskellwiki. Typeclassopedia#Category](https://wiki.haskell.org/index.php?title=Typeclassopedia#Category)
        """
    )
    return


@app.cell(hide_code=True)
def _():
    import marimo as mo
    return (mo,)


@app.cell(hide_code=True)
def _():
    from abc import abstractmethod, ABC
    return ABC, abstractmethod


@app.cell(hide_code=True)
def _():
    from dataclasses import dataclass
    from typing import Callable, Generic, TypeVar
    from pprint import pp
    return Callable, Generic, TypeVar, dataclass, pp


@app.cell(hide_code=True)
def _(TypeVar):
    A = TypeVar("A")
    B = TypeVar("B")
    C = TypeVar("C")
    return A, B, C


if __name__ == "__main__":
    app.run()