File size: 44,103 Bytes
e9e13d8
 
 
 
 
 
 
 
 
3c962e6
e9e13d8
 
48feff6
e9e13d8
3c962e6
e9e13d8
 
 
 
 
 
 
 
 
 
 
 
 
3c962e6
e9e13d8
 
3c962e6
 
e9e13d8
 
 
 
3c962e6
215d7d0
e9e13d8
 
 
 
 
 
 
3c962e6
e9e13d8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3c962e6
e9e13d8
 
48feff6
e9e13d8
e485eac
3c962e6
e485eac
 
e9e13d8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3c962e6
e9e13d8
 
 
 
 
 
e485eac
e9e13d8
 
 
 
 
 
 
 
 
 
 
3c962e6
e9e13d8
 
e485eac
e9e13d8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3c962e6
e9e13d8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3c962e6
e9e13d8
 
e485eac
 
 
e9e13d8
 
 
 
 
 
 
 
3c962e6
e9e13d8
 
 
 
 
 
 
 
 
 
 
 
3c962e6
e9e13d8
 
 
 
 
 
3c962e6
e9e13d8
 
 
 
 
 
 
 
 
 
 
662415d
e9e13d8
 
 
 
 
 
 
 
 
3c962e6
e9e13d8
 
 
 
3c962e6
e9e13d8
 
 
 
e485eac
e9e13d8
 
 
 
 
 
 
 
3c962e6
e9e13d8
 
3c962e6
e9e13d8
3c962e6
e9e13d8
 
 
 
 
e485eac
e9e13d8
48feff6
e9e13d8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3c962e6
e9e13d8
 
 
 
3c962e6
e9e13d8
 
 
 
 
 
 
 
 
3c962e6
e9e13d8
 
3c962e6
e9e13d8
 
 
 
 
 
 
 
662415d
e9e13d8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3c962e6
e9e13d8
 
 
 
3c962e6
e9e13d8
 
 
 
 
 
 
3c962e6
e9e13d8
 
 
 
3c962e6
e9e13d8
 
3c962e6
e9e13d8
 
 
 
 
 
 
 
 
e485eac
e9e13d8
 
48feff6
e9e13d8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e485eac
e9e13d8
e485eac
e9e13d8
 
 
e485eac
e9e13d8
 
 
 
3c962e6
e9e13d8
 
 
 
3c962e6
e9e13d8
 
 
 
 
 
 
 
3c962e6
e9e13d8
 
 
 
 
 
 
e485eac
3c962e6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e485eac
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3c962e6
e485eac
 
 
 
3c962e6
e485eac
 
 
 
 
 
 
 
 
 
3c962e6
e485eac
 
 
 
3c962e6
e485eac
 
 
 
3c962e6
e485eac
 
 
e9e13d8
3c962e6
e9e13d8
 
 
 
e485eac
 
 
 
 
 
 
 
 
e9e13d8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e485eac
e9e13d8
3c962e6
e9e13d8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3c962e6
e9e13d8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3c962e6
e9e13d8
 
 
 
e485eac
48feff6
 
 
e9e13d8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3c962e6
 
e9e13d8
 
 
 
e485eac
 
3c962e6
e9e13d8
 
 
 
 
3c962e6
e9e13d8
 
c3b8d53
e9e13d8
 
 
 
 
 
 
3c962e6
e9e13d8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3c962e6
 
e9e13d8
 
 
 
 
 
 
3c962e6
 
e9e13d8
 
 
 
 
 
 
 
 
 
 
e485eac
e9e13d8
 
 
 
 
 
 
 
e485eac
 
 
 
 
 
 
 
 
3c962e6
e485eac
 
 
e9e13d8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3c962e6
e9e13d8
3c962e6
 
e9e13d8
 
 
3c962e6
e9e13d8
3c962e6
 
e9e13d8
 
 
3c962e6
e9e13d8
3c962e6
 
e9e13d8
 
 
 
 
 
 
 
3c962e6
e9e13d8
3c962e6
 
e9e13d8
 
 
 
 
3c962e6
e9e13d8
 
48feff6
e9e13d8
e485eac
e9e13d8
ccf4a01
e9e13d8
 
 
 
 
3c962e6
e9e13d8
 
 
 
 
 
 
 
3c962e6
e9e13d8
 
 
 
 
 
e485eac
e9e13d8
48feff6
e9e13d8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e485eac
 
e9e13d8
 
 
 
3c962e6
e9e13d8
 
 
 
 
 
3c962e6
 
 
e9e13d8
 
 
 
3c962e6
e485eac
e9e13d8
 
 
 
3c962e6
e9e13d8
 
 
 
3c962e6
e9e13d8
 
 
 
48feff6
e9e13d8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3c962e6
e9e13d8
 
3c962e6
e9e13d8
 
 
 
48feff6
e9e13d8
 
 
 
 
3c962e6
e9e13d8
 
3c962e6
e9e13d8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3c962e6
e9e13d8
 
 
 
 
 
 
 
 
 
 
 
 
 
3c962e6
e9e13d8
 
48feff6
e9e13d8
 
 
 
 
e485eac
e9e13d8
 
 
 
e485eac
e9e13d8
 
 
 
 
 
3c962e6
e9e13d8
 
 
 
662415d
e9e13d8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3c962e6
e485eac
e9e13d8
 
 
 
 
 
 
 
 
 
e485eac
3c962e6
e485eac
 
 
 
3c962e6
e485eac
 
 
e9e13d8
 
 
 
 
 
 
3c962e6
 
e9e13d8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3c962e6
 
e9e13d8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3c962e6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e9e13d8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
# /// script
# requires-python = ">=3.12"
# dependencies = [
#     "marimo",
# ]
# ///

import marimo

__generated_with = "0.12.9"
app = marimo.App(app_title="Applicative programming with effects")


@app.cell(hide_code=True)
def _(mo) -> None:
    mo.md(
        r"""
        # Applicative programming with effects

        `Applicative Functor` encapsulates certain sorts of *effectful* computations in a functionally pure way, and encourages an *applicative* programming style.

        Applicative is a functor with application, providing operations to

        + embed pure expressions (`pure`), and
        + sequence computations and combine their results (`apply`).

        In this notebook, you will learn:

        1. How to view `Applicative` as multi-functor intuitively.
        2. How to use `lift` to simplify chaining application.
        3. How to bring *effects* to the functional pure world.
        4. How to view `Applicative` as a lax monoidal functor.
        5. How to use `Alternative` to amalgamate multiple computations into a single computation.

        /// details | Notebook metadata
            type: info

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

        ///
        """
    )


@app.cell(hide_code=True)
def _(mo) -> None:
    mo.md(
        r"""
        # The intuition: [Multifunctor](https://arxiv.org/pdf/2401.14286)

        ## Limitations of functor

        Recall that 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.
        """
    )


@app.cell(hide_code=True)
def _(mo) -> None:
    mo.md(
        r"""
        ## Defining Multifunctor

        /// admonition
        we use prefix `f` rather than `ap` to indicate *Applicative Functor*
        ///

        As a result, we may want to define a single `Multifunctor` such that:

        1. Lift a regular n-argument function into the context of functors

            ```python
            # lift a regular 3-argument function `g`
            g: Callable[[A, B, C], D]
            # into the context of functors
            fg: Callable[[Functor[A], Functor[B], Functor[C]], Functor[D]]
            ```

        3. Apply it to n functor-wrapped values

            ```python
            # fa: Functor[A], fb: Functor[B], fc: Functor[C]
            fg(fa, fb, fc)
            ```

        5. Get a single functor-wrapped result

            ```python
            fd: Functor[D]
            ```

        We will define a function `lift` such that

        ```python
        fd = lift(g, fa, fb, fc)
        ```
        """
    )


@app.cell(hide_code=True)
def _(mo) -> None:
    mo.md(
        r"""
        ## Pure, apply and lift

        Traditionally, applicative functors are presented through two core operations:

        1. `pure`: embeds an object (value or function) into the applicative functor

            ```python
            # a -> F a
            pure: Callable[[A], Applicative[A]]
            # for example, if `a` is
            a: A
            # then we can have `fa` as
            fa: Applicative[A] = pure(a)
            # or if we have a regular function `g`
            g: Callable[[A], B]
            # then we can have `fg` as
            fg: Applicative[Callable[[A], B]] = pure(g)
            ```

        2. `apply`: applies a function inside an applicative functor to a value inside an applicative functor

            ```python
            # F (a -> b) -> F a -> F b
            apply: Callable[[Applicative[Callable[[A], B]], Applicative[A]], Applicative[B]]
            # and we can have
            fd = apply(apply(apply(fg, fa), fb), fc)
            ```


        As a result,

        ```python
        lift(g, fa, fb, fc) = apply(apply(apply(pure(g), fa), fb), fc)
        ```
        """
    )


@app.cell(hide_code=True)
def _(mo) -> None:
    mo.md(
        r"""
        /// admonition | How to use *Applicative* in the manner of *Multifunctor*

        1. Define `pure` and `apply` for an `Applicative` subclass

            - We can define them much easier compared with `lift`.

        2. Use the `lift` method

            - We can use it much more convenient compared with the combination of `pure` and `apply`.


        ///

        /// attention | You can suppress the chaining application of `apply` and `pure` as:

        ```python
        apply(pure(g), fa) -> lift(g, fa)
        apply(apply(pure(g), fa), fb) -> lift(g, fa, fb)
        apply(apply(apply(pure(g), fa), fb), fc) -> lift(g, fa, fb, fc)
        ```

        ///
        """
    )


@app.cell(hide_code=True)
def _(mo) -> None:
    mo.md(
        r"""
        ## Abstracting applicatives

        We can now provide an initial abstraction definition of applicatives:

        ```python
        @dataclass
        class Applicative[A](Functor, ABC):
            @classmethod
            @abstractmethod
            def pure(cls, a: A) -> "Applicative[A]":
                raise NotImplementedError("Subclasses must implement pure")

            @classmethod
            @abstractmethod
            def apply(
                cls, fg: "Applicative[Callable[[A], B]]", fa: "Applicative[A]"
            ) -> "Applicative[B]":
                raise NotImplementedError("Subclasses must implement apply")

            @classmethod
            def lift(cls, f: Callable, *args: "Applicative") -> "Applicative":
                curr = cls.pure(f)
                if not args:
                    return curr
                for arg in args:
                    curr = cls.apply(curr, arg)
                return curr
        ```

        /// attention | minimal implementation requirement

        - `pure`
        - `apply`
        ///
        """
    )


@app.cell(hide_code=True)
def _(mo) -> None:
    mo.md(r"""# Instances, laws and utility functions""")


@app.cell(hide_code=True)
def _(mo) -> None:
    mo.md(
        r"""
        ## Applicative instances

        When we are actually implementing an *Applicative* instance, we can keep in mind that `pure` and `apply` fundamentally:

        - embed an object (value or function) to the computational context
        - apply a function inside the computation context to a value inside the computational context
        """
    )


@app.cell(hide_code=True)
def _(mo) -> None:
    mo.md(
        r"""
        ### The Wrapper Applicative

        - `pure` should simply *wrap* an object, in the sense that:

            ```haskell
            Wrapper.pure(1) => Wrapper(value=1)
            ```

        - `apply` should apply a *wrapped* function to a *wrapped* value

        The implementation is:
        """
    )


@app.cell
def _(Applicative, dataclass):
    @dataclass
    class Wrapper[A](Applicative):
        value: A

        @classmethod
        def pure(cls, a: A) -> "Wrapper[A]":
            return cls(a)

        @classmethod
        def apply(
            cls, fg: "Wrapper[Callable[[A], B]]", fa: "Wrapper[A]"
        ) -> "Wrapper[B]":
            return cls(fg.value(fa.value))
    return (Wrapper,)


@app.cell(hide_code=True)
def _(mo) -> None:
    mo.md(r"""> try with Wrapper below""")


@app.cell
def _(Wrapper) -> None:
    Wrapper.lift(
        lambda a: lambda b: lambda c: a + b * c,
        Wrapper(1),
        Wrapper(2),
        Wrapper(3),
    )


@app.cell(hide_code=True)
def _(mo) -> None:
    mo.md(
        r"""
        ### The List Applicative

        - `pure` should wrap the object in a list, in the sense that:

            ```haskell
            List.pure(1) => List(value=[1])
            ```

        - `apply` should apply a list of functions to a list of values
            - you can think of this as cartesian product, concatenating the result of applying every function to every value

        The implementation is:
        """
    )


@app.cell
def _(Applicative, dataclass, product):
    @dataclass
    class List[A](Applicative):
        value: list[A]

        @classmethod
        def pure(cls, a: A) -> "List[A]":
            return cls([a])

        @classmethod
        def apply(cls, fg: "List[Callable[[A], B]]", fa: "List[A]") -> "List[B]":
            return cls([g(a) for g, a in product(fg.value, fa.value)])
    return (List,)


@app.cell(hide_code=True)
def _(mo) -> None:
    mo.md(r"""> try with List below""")


@app.cell
def _(List) -> None:
    List.apply(
        List([lambda a: a + 1, lambda a: a * 2]),
        List([1, 2]),
    )


@app.cell
def _(List) -> None:
    List.lift(lambda a: lambda b: a + b, List([1, 2]), List([3, 4, 5]))


@app.cell(hide_code=True)
def _(mo) -> None:
    mo.md(
        r"""
        ### The Maybe Applicative

        - `pure` should wrap the object in a Maybe, in the sense that:

            ```haskell
            Maybe.pure(1)    => "Just 1"
            Maybe.pure(None) => "Nothing"
            ```

        - `apply` should apply a function maybe exist to a value maybe exist
            - if the function is `None` or the value is `None`, simply returns `None`
            - else apply the function to the value and wrap the result in `Just`

        The implementation is:
        """
    )


@app.cell
def _(Applicative, dataclass):
    @dataclass
    class Maybe[A](Applicative):
        value: None | A

        @classmethod
        def pure(cls, a: A) -> "Maybe[A]":
            return cls(a)

        @classmethod
        def apply(
            cls, fg: "Maybe[Callable[[A], B]]", fa: "Maybe[A]"
        ) -> "Maybe[B]":
            if fg.value is None or fa.value is None:
                return cls(None)

            return cls(fg.value(fa.value))

        def __repr__(self):
            return "Nothing" if self.value is None else f"Just({self.value!r})"
    return (Maybe,)


@app.cell(hide_code=True)
def _(mo) -> None:
    mo.md(r"""> try with Maybe below""")


@app.cell
def _(Maybe) -> None:
    Maybe.lift(
        lambda a: lambda b: a + b,
        Maybe(1),
        Maybe(2),
    )


@app.cell
def _(Maybe) -> None:
    Maybe.lift(
        lambda a: lambda b: None,
        Maybe(1),
        Maybe(2),
    )


@app.cell(hide_code=True)
def _(mo) -> None:
    mo.md(
        r"""
        ### The Either Applicative

        - `pure` should wrap the object in `Right`, in the sense that:

            ```haskell
            Either.pure(1) => Right(1)
            ```

        - `apply` should apply a function that is either on Left or Right to a value that is either on Left or Right
            - if the function is `Left`, simply returns the `Left` of the function
            - else `fmap` the `Right` of the function to the value

        The implementation is:
        """
    )


@app.cell
def _(Applicative, B, Callable, Union, dataclass):
    @dataclass
    class Either[A](Applicative):
        left: A = None
        right: A = None

        def __post_init__(self):
            if (self.left is not None and self.right is not None) or (
                self.left is None and self.right is None
            ):
                msg = "Provide either the value of the left or the value of the right."
                raise TypeError(
                    msg
                )

        @classmethod
        def pure(cls, a: A) -> "Either[A]":
            return cls(right=a)

        @classmethod
        def apply(
            cls, fg: "Either[Callable[[A], B]]", fa: "Either[A]"
        ) -> "Either[B]":
            if fg.left is not None:
                return cls(left=fg.left)
            return cls.fmap(fg.right, fa)

        @classmethod
        def fmap(
            cls, g: Callable[[A], B], fa: "Either[A]"
        ) -> Union["Either[A]", "Either[B]"]:
            if fa.left is not None:
                return cls(left=fa.left)
            return cls(right=g(fa.right))

        def __repr__(self):
            if self.left is not None:
                return f"Left({self.left!r})"
            return f"Right({self.right!r})"
    return (Either,)


@app.cell(hide_code=True)
def _(mo) -> None:
    mo.md(r"""> try with `Either` below""")


@app.cell
def _(Either) -> None:
    Either.apply(Either(left=TypeError("Parse Error")), Either(right=2))


@app.cell
def _(Either) -> None:
    Either.apply(
        Either(right=lambda x: x + 1), Either(left=TypeError("Parse Error"))
    )


@app.cell
def _(Either) -> None:
    Either.apply(Either(right=lambda x: x + 1), Either(right=1))


@app.cell(hide_code=True)
def _(mo) -> None:
    mo.md(
        r"""
        ## Collect the list of response with sequenceL

        One often wants to execute a list of commands and collect the list of their response, and we can define a function `sequenceL` for this

        /// admonition
        In a further notebook about `Traversable`, we will have a more generic `sequence` that execute a **sequence** of commands and collect the **sequence** of their response, which is not limited to `list`.
        ///

        ```python
        @classmethod
        def sequenceL(cls, fas: list["Applicative[A]"]) -> "Applicative[list[A]]":
            if not fas:
                return cls.pure([])

            return cls.apply(
                cls.fmap(lambda v: lambda vs: [v] + vs, fas[0]),
                cls.sequenceL(fas[1:]),
            )
        ```

        Let's try `sequenceL` with the instances.
        """
    )


@app.cell
def _(Wrapper) -> None:
    Wrapper.sequenceL([Wrapper(1), Wrapper(2), Wrapper(3)])


@app.cell(hide_code=True)
def _(mo) -> None:
    mo.md(
        r"""
        /// attention
        For the `Maybe` Applicative, the presence of any `Nothing` causes the entire computation to return Nothing.
        ///
        """
    )


@app.cell
def _(Maybe) -> None:
    Maybe.sequenceL([Maybe(1), Maybe(2), Maybe(None), Maybe(3)])


@app.cell(hide_code=True)
def _(mo) -> None:
    mo.md(r"""The result of `sequenceL` for `List Applicative`  is the Cartesian product of the input lists, yielding all possible ordered combinations of elements from each list.""")


@app.cell
def _(List) -> None:
    List.sequenceL([List([1, 2]), List([3]), List([5, 6, 7])])


@app.cell(hide_code=True)
def _(mo) -> None:
    mo.md(
        r"""
        ## Applicative laws

        /// admonition | id and compose

        Remember that

        - `id = lambda x: x`
        - `compose = lambda f: lambda g: lambda x: f(g(x))`

        ///

        Traditionally, there are four laws that `Applicative` instances should satisfy. In some sense, they are all concerned with making sure that `pure` deserves its name:

        - The identity law:
          ```python
          # fa: Applicative[A]
          apply(pure(id), fa) = fa
          ```
        - Homomorphism:
          ```python
          # a: A
          # g: Callable[[A], B]
          apply(pure(g), pure(a)) = pure(g(a))
          ```
          Intuitively, applying a non-effectful function to a non-effectful argument in an effectful context is the same as just applying the function to the argument and then injecting the result into the context with pure.
        - Interchange:
          ```python
          # a: A
          # fg: Applicative[Callable[[A], B]]
          apply(fg, pure(a)) = apply(pure(lambda g: g(a)), fg)
          ```
          Intuitively, this says that when evaluating the application of an effectful function to a pure argument, the order in which we evaluate the function and its argument doesn't matter.
        - Composition:
          ```python
          # fg: Applicative[Callable[[B], C]]
          # fh: Applicative[Callable[[A], B]]
          # fa: Applicative[A]
          apply(fg, apply(fh, fa)) = lift(compose, fg, fh, fa)
          ```
          This one is the trickiest law to gain intuition for. In some sense it is expressing a sort of associativity property of `apply`.

        We can add 4 helper functions to `Applicative` to check whether an instance respects the laws or not:

        ```python
        @dataclass
        class Applicative[A](Functor, ABC):

            @classmethod
            def check_identity(cls, fa: "Applicative[A]"):
                if cls.lift(id, fa) != fa:
                    raise ValueError("Instance violates identity law")
                return True

            @classmethod
            def check_homomorphism(cls, a: A, f: Callable[[A], B]):
                if cls.lift(f, cls.pure(a)) != cls.pure(f(a)):
                    raise ValueError("Instance violates homomorphism law")
                return True

            @classmethod
            def check_interchange(cls, a: A, fg: "Applicative[Callable[[A], B]]"):
                if cls.apply(fg, cls.pure(a)) != cls.lift(lambda g: g(a), fg):
                    raise ValueError("Instance violates interchange law")
                return True

            @classmethod
            def check_composition(
                cls,
                fg: "Applicative[Callable[[B], C]]",
                fh: "Applicative[Callable[[A], B]]",
                fa: "Applicative[A]",
            ):
                if cls.apply(fg, cls.apply(fh, fa)) != cls.lift(compose, fg, fh, fa):
                    raise ValueError("Instance violates composition law")
                return True
        ```

        > Try to validate applicative laws below
        """
    )


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


@app.cell
def _(List, Wrapper) -> None:
    print("Checking Wrapper")
    print(Wrapper.check_identity(Wrapper.pure(1)))
    print(Wrapper.check_homomorphism(1, lambda x: x + 1))
    print(Wrapper.check_interchange(1, Wrapper.pure(lambda x: x + 1)))
    print(
        Wrapper.check_composition(
            Wrapper.pure(lambda x: x * 2),
            Wrapper.pure(lambda x: x + 0.1),
            Wrapper.pure(1),
        )
    )

    print("\nChecking List")
    print(List.check_identity(List.pure(1)))
    print(List.check_homomorphism(1, lambda x: x + 1))
    print(List.check_interchange(1, List.pure(lambda x: x + 1)))
    print(
        List.check_composition(
            List.pure(lambda x: x * 2), List.pure(lambda x: x + 0.1), List.pure(1)
        )
    )


@app.cell(hide_code=True)
def _(mo) -> None:
    mo.md(
        r"""
        ## Utility functions

        /// attention | using `fmap`
        `fmap` is defined automatically using `pure` and `apply`, so you can use `fmap` with any `Applicative`
        ///

        ```python
        @dataclass
        class Applicative[A](Functor, ABC):
            @classmethod
            def skip(
                cls, fa: "Applicative[A]", fb: "Applicative[B]"
            ) -> "Applicative[B]":
                '''
                Sequences the effects of two Applicative computations,
                but discards the result of the first.
                '''
                return cls.apply(cls.const(fa, id), fb)

            @classmethod
            def keep(
                cls, fa: "Applicative[A]", fb: "Applicative[B]"
            ) -> "Applicative[B]":
                '''
                Sequences the effects of two Applicative computations,
                but discard the result of the second.
                '''
                return cls.lift(const, fa, fb)

            @classmethod
            def revapp(
                cls, fa: "Applicative[A]", fg: "Applicative[Callable[[A], [B]]]"
            ) -> "Applicative[B]":
                '''
                The first computation produces values which are provided
                as input to the function(s) produced by the second computation.
                '''
                return cls.lift(lambda a: lambda f: f(a), fa, fg)
        ```

        - `skip` sequences the effects of two Applicative computations, but **discards the result of the first**. For example, if `m1` and `m2` are instances of type `Maybe[Int]`, then `Maybe.skip(m1, m2)` is `Nothing` whenever either `m1` or `m2` is `Nothing`; but if not, it will have the same value as `m2`.
        - Likewise, `keep` sequences the effects of two computations, but **keeps only the result of the first**.
        - `revapp` is similar to `apply`, but where the first computation produces value(s) which are provided as input to the function(s) produced by the second computation.
        """
    )


@app.cell(hide_code=True)
def _(mo) -> None:
    mo.md(
        r"""
        /// admonition | Exercise
        Try to use utility functions with different instances
        ///
        """
    )


@app.cell(hide_code=True)
def _(mo) -> None:
    mo.md(
        r"""
        # Formal implementation of Applicative

        Now, we can give the formal implementation of `Applicative`
        """
    )


@app.cell
def _(
    ABC,
    B,
    Callable,
    Functor,
    abstractmethod,
    compose,
    const,
    dataclass,
    id,
):
    @dataclass
    class Applicative[A](Functor, ABC):
        @classmethod
        @abstractmethod
        def pure(cls, a: A) -> "Applicative[A]":
            """Lift a value into the Structure."""
            msg = "Subclasses must implement pure"
            raise NotImplementedError(msg)

        @classmethod
        @abstractmethod
        def apply(
            cls, fg: "Applicative[Callable[[A], B]]", fa: "Applicative[A]"
        ) -> "Applicative[B]":
            """Sequential application."""
            msg = "Subclasses must implement apply"
            raise NotImplementedError(msg)

        @classmethod
        def lift(cls, f: Callable, *args: "Applicative") -> "Applicative":
            """Lift a function of arbitrary arity to work with values in applicative context."""
            curr = cls.pure(f)

            if not args:
                return curr

            for arg in args:
                curr = cls.apply(curr, arg)

            return curr

        @classmethod
        def fmap(
            cls, f: Callable[[A], B], fa: "Applicative[A]"
        ) -> "Applicative[B]":
            return cls.lift(f, fa)

        @classmethod
        def sequenceL(cls, fas: list["Applicative[A]"]) -> "Applicative[list[A]]":
            """
            Execute a list of commands and collect the list of their response.
            """
            if not fas:
                return cls.pure([])

            return cls.apply(
                cls.fmap(lambda v: lambda vs: [v, *vs], fas[0]),
                cls.sequenceL(fas[1:]),
            )

        @classmethod
        def skip(
            cls, fa: "Applicative[A]", fb: "Applicative[B]"
        ) -> "Applicative[B]":
            """
            Sequences the effects of two Applicative computations,
            but discards the result of the first.
            """
            return cls.apply(cls.const(fa, id), fb)

        @classmethod
        def keep(
            cls, fa: "Applicative[A]", fb: "Applicative[B]"
        ) -> "Applicative[B]":
            """
            Sequences the effects of two Applicative computations,
            but discard the result of the second.
            """
            return cls.lift(const, fa, fb)

        @classmethod
        def revapp(
            cls, fa: "Applicative[A]", fg: "Applicative[Callable[[A], [B]]]"
        ) -> "Applicative[B]":
            """
            The first computation produces values which are provided
            as input to the function(s) produced by the second computation.
            """
            return cls.lift(lambda a: lambda f: f(a), fa, fg)

        @classmethod
        def check_identity(cls, fa: "Applicative[A]") -> bool:
            if cls.lift(id, fa) != fa:
                msg = "Instance violates identity law"
                raise ValueError(msg)
            return True

        @classmethod
        def check_homomorphism(cls, a: A, f: Callable[[A], B]) -> bool:
            if cls.lift(f, cls.pure(a)) != cls.pure(f(a)):
                msg = "Instance violates homomorphism law"
                raise ValueError(msg)
            return True

        @classmethod
        def check_interchange(cls, a: A, fg: "Applicative[Callable[[A], B]]") -> bool:
            if cls.apply(fg, cls.pure(a)) != cls.lift(lambda g: g(a), fg):
                msg = "Instance violates interchange law"
                raise ValueError(msg)
            return True

        @classmethod
        def check_composition(
            cls,
            fg: "Applicative[Callable[[B], C]]",
            fh: "Applicative[Callable[[A], B]]",
            fa: "Applicative[A]",
        ) -> bool:
            if cls.apply(fg, cls.apply(fh, fa)) != cls.lift(compose, fg, fh, fa):
                msg = "Instance violates composition law"
                raise ValueError(msg)
            return True
    return (Applicative,)


@app.cell(hide_code=True)
def _(mo) -> None:
    mo.md(
        r"""
        # Effectful programming

        Our original motivation for applicatives was the desire to generalise the idea of mapping to functions with multiple arguments. This is a valid interpretation of the concept of applicatives, but from the three instances we have seen it becomes clear that there is also another, more abstract view.

         The arguments are no longer just plain values but may also have effects, such as the possibility of failure, having many ways to succeed, or performing input/output actions. In this manner, applicative functors can also be viewed as abstracting the idea of **applying pure functions to effectful arguments**, with the precise form of effects that are permitted depending on the nature of the underlying functor.
        """
    )


@app.cell(hide_code=True)
def _(mo) -> None:
    mo.md(
        r"""
        ## The IO Applicative

        We will try to define an `IO` applicative here.

        As before, we first abstract how `pure` and `apply` should function.

        - `pure` should wrap the object in an IO action, and make the object *callable* if it's not because we want to perform the action later:

            ```haskell
            IO.pure(1) => IO(effect=lambda: 1)
            IO.pure(f) => IO(effect=f)
            ```

        - `apply` should perform an action that produces a value, then apply the function with the value

        The implementation is:
        """
    )


@app.cell
def _(Applicative, Callable, dataclass):
    @dataclass
    class IO(Applicative):
        effect: Callable

        def __call__(self):
            return self.effect()

        @classmethod
        def pure(cls, a):
            return cls(a) if isinstance(a, Callable) else IO(lambda: a)

        @classmethod
        def apply(cls, fg, fa):
            return cls.pure(fg.effect(fa.effect()))
    return (IO,)


@app.cell(hide_code=True)
def _(mo) -> None:
    mo.md(r"""For example, a function that reads a given number of lines from the keyboard can be defined in applicative style as follows:""")


@app.cell
def _(IO):
    def get_chars(n: int = 3):
        return IO.sequenceL([
            IO.pure(input(f"input the {i}th str")) for i in range(1, n + 1)
        ])
    return (get_chars,)


@app.cell
def _() -> None:
    # get_chars()()
    return


@app.cell(hide_code=True)
def _(mo) -> None:
    mo.md(r"""# From the perspective of category theory""")


@app.cell(hide_code=True)
def _(mo) -> None:
    mo.md(
        r"""
        ## Lax Monoidal Functor

        An alternative, equivalent formulation of `Applicative` is given by
        """
    )


@app.cell
def _(ABC, Functor, abstractmethod, dataclass):
    @dataclass
    class Monoidal[A](Functor, ABC):
        @classmethod
        @abstractmethod
        def unit(cls) -> "Monoidal[Tuple[()]]":
            pass

        @classmethod
        @abstractmethod
        def tensor(
            cls, this: "Monoidal[A]", other: "Monoidal[B]"
        ) -> "Monoidal[Tuple[A, B]]":
            pass
    return (Monoidal,)


@app.cell(hide_code=True)
def _(mo) -> None:
    mo.md(
        r"""
        Intuitively, this states that a *monoidal functor* is one which has some sort of "default shape" and which supports some sort of "combining" operation.

        - `unit` provides the identity element
        - `tensor` combines two contexts into a product context

        More technically, the idea is that `monoidal functor` preserves the "monoidal structure" given by the pairing constructor `(,)` and unit type `()`.
        """
    )


@app.cell(hide_code=True)
def _(mo) -> None:
    mo.md(
        r"""
        Furthermore, to deserve the name "monoidal", instances of Monoidal ought to satisfy the following laws, which seem much more straightforward than the traditional Applicative laws:

        - Left identity

            `tensor(unit, v) β‰… v`

        - Right identity

            `tensor(u, unit) β‰… u`

        - Associativity

            `tensor(u, tensor(v, w)) β‰… tensor(tensor(u, v), w)`
        """
    )


@app.cell(hide_code=True)
def _(mo) -> None:
    mo.md(
        r"""
        /// admonition | β‰… indicates isomorphism

        `β‰…` refers to *isomorphism* rather than equality.

        In particular we consider `(x, ()) β‰… x β‰… ((), x)` and `((x, y), z) β‰… (x, (y, z))`

        ///
        """
    )


@app.cell(hide_code=True)
def _(mo) -> None:
    mo.md(
        r"""
        ## Mutual definability of Monoidal and Applicative

        We can implement `pure` and `apply` in terms of `unit` and `tensor`, and vice versa.

        ```python
        pure(a) = fmap((lambda _: a), unit)
        apply(fg, fa) = fmap((lambda pair: pair[0](pair[1])), tensor(fg, fa))
        ```

        ```python
        unit() = pure(())
        tensor(fa, fb) = lift(lambda fa: lambda fb: (fa, fb), fa, fb)
        ```
        """
    )


@app.cell(hide_code=True)
def _(mo) -> None:
    mo.md(
        r"""
        ## Instance: ListMonoidal

        - `unit` should simply return a empty tuple wrapper in a list

            ```haskell
            ListMonoidal.unit() => [()]
            ```

        - `tensor` should return the *cartesian product* of the items of 2 ListMonoidal instances

        The implementation is:
        """
    )


@app.cell
def _(B, Callable, Monoidal, dataclass, product):
    @dataclass
    class ListMonoidal[A](Monoidal):
        items: list[A]

        @classmethod
        def unit(cls) -> "ListMonoidal[Tuple[()]]":
            return cls([()])

        @classmethod
        def tensor(
            cls, this: "ListMonoidal[A]", other: "ListMonoidal[B]"
        ) -> "ListMonoidal[Tuple[A, B]]":
            return cls(list(product(this.items, other.items)))

        @classmethod
        def fmap(
            cls, f: Callable[[A], B], ma: "ListMonoidal[A]"
        ) -> "ListMonoidal[B]":
            return cls([f(a) for a in ma.items])
    return (ListMonoidal,)


@app.cell(hide_code=True)
def _(mo) -> None:
    mo.md(r"""> try with `ListMonoidal` below""")


@app.cell
def _(ListMonoidal):
    xs = ListMonoidal([1, 2])
    ys = ListMonoidal(["a", "b"])
    ListMonoidal.tensor(xs, ys)
    return xs, ys


@app.cell(hide_code=True)
def _(mo) -> None:
    mo.md(r"""and we can prove that `tensor(fa, fb) = lift(lambda fa: lambda fb: (fa, fb), fa, fb)`:""")


@app.cell
def _(List, xs, ys) -> None:
    List.lift(lambda fa: lambda fb: (fa, fb), List(xs.items), List(ys.items))


@app.cell(hide_code=True)
def _(ABC, B, Callable, abstractmethod, dataclass):
    @dataclass
    class Functor[A](ABC):
        @classmethod
        @abstractmethod
        def fmap(cls, f: Callable[[A], B], a: "Functor[A]") -> "Functor[B]":
            msg = "Subclasses must implement fmap"
            raise NotImplementedError(msg)

        @classmethod
        def const(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 (Functor,)


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


@app.cell(hide_code=True)
def _():
    from abc import ABC, abstractmethod
    from collections.abc import Callable
    from dataclasses import dataclass
    from typing import TypeVar, Union
    return ABC, Callable, TypeVar, Union, abstractmethod, dataclass


@app.cell(hide_code=True)
def _():
    from itertools import product
    return (product,)


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


@app.cell(hide_code=True)
def _(mo) -> None:
    mo.md(
        r"""
        # From Applicative to Alternative

        ## Abstracting Alternative

        In our studies so far, we saw that both `Maybe` and `List` can represent computations with a varying number of results.

        We use `Maybe` to indicate a computation can fail somehow and `List` for computations that can have many possible results. In both of these cases, one useful operation is amalgamating all possible results from multiple computations into a single computation.

        `Alternative` formalizes computations that support:

        - **Failure** (empty result)
        - **Choice** (combination of results)
        - **Repetition** (multiple results)

        It extends `Applicative` with monoidal structure, where:

        ```python
        @dataclass
        class Alternative[A](Applicative, ABC):
            @classmethod
            @abstractmethod
            def empty(cls) -> "Alternative[A]":
                '''Identity element for alternative computations'''

            @classmethod
            @abstractmethod
            def alt(
                cls, fa: "Alternative[A]", fb: "Alternative[A]"
            ) -> "Alternative[A]":
                '''Binary operation combining computations'''
        ```

        - `empty` is the identity element (e.g., `Maybe(None)`, `List([])`)
        - `alt` is a combination operator (e.g., `Maybe` fallback, list concatenation)

        `empty` and `alt` should satisfy the following **laws**:

        ```python
        # Left identity
        alt(empty, fa) == fa
        # Right identity
        alt(fa, empty) == fa
        # Associativity
        alt(fa, alt(fb, fc)) == alt(alt(fa, fb), fc)
        ```

        /// admonition
        Actually, `Alternative` is a *monoid* on `Applicative Functors`. We will talk about *monoid* and review these laws in the next notebook about `Monads`.
        ///

        /// attention | minimal implementation requirement
        - `empty`
        - `alt`
        ///
        """
    )


@app.cell(hide_code=True)
def _(mo) -> None:
    mo.md(
        r"""
        ## Instances of Alternative

        ### The Maybe Alternative

        - `empty`: the identity element of `Maybe` is `Maybe(None)`
        - `alt`: return the first element if it's not `None`, else return the second element
        """
    )


@app.cell
def _(Alternative, Maybe, dataclass):
    @dataclass
    class AltMaybe[A](Maybe, Alternative):
        @classmethod
        def empty(cls) -> "AltMaybe[A]":
            return cls(None)

        @classmethod
        def alt(cls, fa: "AltMaybe[A]", fb: "AltMaybe[A]") -> "AltMaybe[A]":
            if fa.value is not None:
                return cls(fa.value)
            return cls(fb.value)

        def __repr__(self):
            return "Nothing" if self.value is None else f"Just({self.value!r})"
    return (AltMaybe,)


@app.cell
def _(AltMaybe) -> None:
    print(AltMaybe.empty())
    print(AltMaybe.alt(AltMaybe(None), AltMaybe(1)))
    print(AltMaybe.alt(AltMaybe(None), AltMaybe(None)))
    print(AltMaybe.alt(AltMaybe(1), AltMaybe(None)))
    print(AltMaybe.alt(AltMaybe(1), AltMaybe(2)))


@app.cell
def _(AltMaybe) -> None:
    print(AltMaybe.check_left_identity(AltMaybe(1)))
    print(AltMaybe.check_right_identity(AltMaybe(1)))
    print(AltMaybe.check_associativity(AltMaybe(1), AltMaybe(2), AltMaybe(None)))


@app.cell(hide_code=True)
def _(mo) -> None:
    mo.md(
        r"""
        ### The List Alternative

        - `empty`: the identity element of `List` is `List([])`
        - `alt`: return the concatenation of 2 input lists
        """
    )


@app.cell
def _(Alternative, List, dataclass):
    @dataclass
    class AltList[A](List, Alternative):
        @classmethod
        def empty(cls) -> "AltList[A]":
            return cls([])

        @classmethod
        def alt(cls, fa: "AltList[A]", fb: "AltList[A]") -> "AltList[A]":
            return cls(fa.value + fb.value)
    return (AltList,)


@app.cell
def _(AltList) -> None:
    print(AltList.empty())
    print(AltList.alt(AltList([1, 2, 3]), AltList([4, 5])))


@app.cell
def _(AltList) -> None:
    AltList([1])


@app.cell
def _(AltList) -> None:
    AltList([1])


@app.cell
def _(AltList) -> None:
    print(AltList.check_left_identity(AltList([1, 2, 3])))
    print(AltList.check_right_identity(AltList([1, 2, 3])))
    print(
        AltList.check_associativity(
            AltList([1, 2]), AltList([3, 4, 5]), AltList([6])
        )
    )


@app.cell(hide_code=True)
def _(mo) -> None:
    mo.md(
        r"""
        ## some and many


        /// admonition | This section mainly refers to

        - https://stackoverflow.com/questions/7671009/some-and-many-functions-from-the-alternative-type-class/7681283#7681283

        ///

        First let's have a look at the implementation of `some` and `many`:

        ```python
        @classmethod
        def some(cls, fa: "Alternative[A]") -> "Alternative[list[A]]":
            # Short-circuit if input is empty
            if fa == cls.empty():
                return cls.empty()

            return cls.apply(
                cls.fmap(lambda a: lambda b: [a] + b, fa), cls.many(fa)
            )

        @classmethod
        def many(cls, fa: "Alternative[A]") -> "Alternative[list[A]]":
            # Directly return empty list if input is empty
            if fa == cls.empty():
                return cls.pure([])

            return cls.alt(cls.some(fa), cls.pure([]))
        ```

        So `some f` runs `f` once, then *many* times, and conses the results. `many f` runs f *some* times, or *alternatively* just returns the empty list.

        The idea is that they both run `f` as often as possible until it **fails**, collecting the results in a list. The difference is that `some f` immediately fails if `f` fails, while `many f` will still succeed and *return* the empty list in such a case. But what all this exactly means depends on how `alt` is defined.

        Let's see what it does for the instances `AltMaybe` and `AltList`.
        """
    )


@app.cell(hide_code=True)
def _(mo) -> None:
    mo.md(r"""For `AltMaybe`. `None` means failure, so some `None` fails as well and evaluates to `None` while many `None` succeeds and evaluates to `Just []`. Both `some (Just ())` and `many (Just ())` never return, because `Just ()` never fails.""")


@app.cell
def _(AltMaybe) -> None:
    print(AltMaybe.some(AltMaybe.empty()))
    print(AltMaybe.many(AltMaybe.empty()))


@app.cell(hide_code=True)
def _(mo) -> None:
    mo.md(r"""For `AltList`, `[]` means failure, so `some []` evaluates to `[]` (no answers) while `many []` evaluates to `[[]]` (there's one answer and it is the empty list). Again `some [()]` and `many [()]` don't return.""")


@app.cell
def _(AltList) -> None:
    print(AltList.some(AltList.empty()))
    print(AltList.many(AltList.empty()))


@app.cell(hide_code=True)
def _(mo) -> None:
    mo.md(r"""## Formal implementation of Alternative""")


@app.cell
def _(ABC, Applicative, abstractmethod, dataclass):
    @dataclass
    class Alternative[A](Applicative, ABC):
        """A monoid on applicative functors."""

        @classmethod
        @abstractmethod
        def empty(cls) -> "Alternative[A]":
            msg = "Subclasses must implement empty"
            raise NotImplementedError(msg)

        @classmethod
        @abstractmethod
        def alt(
            cls, fa: "Alternative[A]", fb: "Alternative[A]"
        ) -> "Alternative[A]":
            msg = "Subclasses must implement alt"
            raise NotImplementedError(msg)

        @classmethod
        def some(cls, fa: "Alternative[A]") -> "Alternative[list[A]]":
            # Short-circuit if input is empty
            if fa == cls.empty():
                return cls.empty()

            return cls.apply(
                cls.fmap(lambda a: lambda b: [a, *b], fa), cls.many(fa)
            )

        @classmethod
        def many(cls, fa: "Alternative[A]") -> "Alternative[list[A]]":
            # Directly return empty list if input is empty
            if fa == cls.empty():
                return cls.pure([])

            return cls.alt(cls.some(fa), cls.pure([]))

        @classmethod
        def check_left_identity(cls, fa: "Alternative[A]") -> bool:
            return cls.alt(cls.empty(), fa) == fa

        @classmethod
        def check_right_identity(cls, fa: "Alternative[A]") -> bool:
            return cls.alt(fa, cls.empty()) == fa

        @classmethod
        def check_associativity(
            cls, fa: "Alternative[A]", fb: "Alternative[A]", fc: "Alternative[A]"
        ) -> bool:
            return cls.alt(fa, cls.alt(fb, fc)) == cls.alt(cls.alt(fa, fb), fc)
    return (Alternative,)


@app.cell(hide_code=True)
def _(mo) -> None:
    mo.md(
        r"""
        /// admonition

        We will explore more about `Alternative` in a future notebooks about [Monadic Parsing](https://www.cambridge.org/core/journals/journal-of-functional-programming/article/monadic-parsing-in-haskell/E557DFCCE00E0D4B6ED02F3FB0466093)

        ///
        """
    )


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

        Notice that these reading sources are optional and non-trivial

        - [Applicaive Programming with Effects](https://www.staff.city.ac.uk/~ross/papers/Applicative.html)
        - [Equivalence of Applicative Functors and
        Multifunctors](https://arxiv.org/pdf/2401.14286)
        - [Applicative functor](https://wiki.haskell.org/index.php?title=Applicative_functor)
        - [Control.Applicative](https://hackage.haskell.org/package/base-4.21.0.0/docs/Control-Applicative.html#t:Applicative)
        - [Typeclassopedia#Applicative](https://wiki.haskell.org/index.php?title=Typeclassopedia#Applicative)
        - [Notions of computation as monoids](https://www.cambridge.org/core/journals/journal-of-functional-programming/article/notions-of-computation-as-monoids/70019FC0F2384270E9F41B9719042528)
        - [Free Applicative Functors](https://arxiv.org/abs/1403.0749)
        - [The basics of applicative functors, put to practical work](http://www.serpentine.com/blog/2008/02/06/the-basics-of-applicative-functors-put-to-practical-work/)
        - [Abstracting with Applicatives](http://comonad.com/reader/2012/abstracting-with-applicatives/)
        - [Static analysis with Applicatives](https://gergo.erdi.hu/blog/2012-12-01-static_analysis_with_applicatives/)
        - [Explaining Applicative functor in categorical terms - monoidal functors](https://cstheory.stackexchange.com/questions/12412/explaining-applicative-functor-in-categorical-terms-monoidal-functors)
        - [Applicative, A Strong Lax Monoidal Functor](https://beuke.org/applicative/)
        - [Applicative Functors](https://bartoszmilewski.com/2017/02/06/applicative-functors/)
        """
    )


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