Spaces:
Running
Running
File size: 41,814 Bytes
463e388 7139673 463e388 bfe46e3 8b10f04 6399834 87e47b3 6399834 8b10f04 6b8214a 8b10f04 6b8214a 8b10f04 6b8214a 8b10f04 6b8214a 8b10f04 6b8214a 8b10f04 6b8214a 8b10f04 6b8214a 8b10f04 6b8214a 8b10f04 6399834 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 3c4c5bc 8b10f04 d417768 8b10f04 6b8214a 7139673 d417768 6b8214a 8b10f04 6b8214a 8b10f04 6b8214a 8b10f04 6b8214a 8b10f04 6b8214a c6fe084 7139673 8b10f04 7139673 d417768 8b10f04 d417768 3c4c5bc 7139673 3c4c5bc 7139673 8b10f04 7139673 8b10f04 d417768 7139673 8b10f04 6b8214a 8b10f04 3c4c5bc 7139673 d417768 8b10f04 6b8214a 8b10f04 6b8214a 3c4c5bc 6b8214a 8b10f04 6b8214a 8b10f04 d417768 6b8214a d417768 8b10f04 6b8214a 8b10f04 6b8214a 3c4c5bc 8b10f04 d417768 6b8214a 8b10f04 c6fe084 7139673 8b10f04 7139673 d417768 8b10f04 d417768 3c4c5bc 7139673 8b10f04 7139673 d417768 7139673 c6fe084 8b10f04 6b8214a 8b10f04 d417768 8b10f04 6b8214a 3c4c5bc 6b8214a 8b10f04 6b8214a 8b10f04 6b8214a 3c4c5bc 6b8214a 8b10f04 6b8214a 8b10f04 6b8214a 3c4c5bc 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 7139673 d417768 6b8214a 3c4c5bc 6b8214a 8b10f04 6b8214a 8b10f04 6b8214a 3c4c5bc 8e62b80 8b10f04 3c4c5bc 8b10f04 3c4c5bc 8b10f04 3c4c5bc bfe46e3 8e62b80 3c4c5bc 8b10f04 3c4c5bc 8b10f04 3c4c5bc 8b10f04 3c4c5bc 7139673 8b10f04 3c4c5bc 8b10f04 3c4c5bc 8e62b80 8b10f04 8e62b80 3c4c5bc 8e62b80 6399834 6b8214a 8b10f04 8e62b80 8b10f04 3c4c5bc 8b10f04 8e62b80 8b10f04 3c4c5bc 8b10f04 3c4c5bc d417768 3c4c5bc 8b10f04 3c4c5bc 8b10f04 8e62b80 8b10f04 3c4c5bc 8b10f04 3c4c5bc 8b10f04 d417768 3c4c5bc 8b10f04 3c4c5bc 8b10f04 d417768 8b10f04 d417768 c6fe084 d417768 c6fe084 8b10f04 6b8214a 8b10f04 6b8214a 8b10f04 6b8214a 8b10f04 6b8214a 8b10f04 6b8214a 8b10f04 6b8214a 3c4c5bc 6b8214a 8b10f04 6b8214a 8b10f04 d417768 6b8214a d417768 8b10f04 3c4c5bc 8b10f04 3c4c5bc 8b10f04 3c4c5bc 8b10f04 3c4c5bc 6b8214a 8b10f04 3c4c5bc 8b10f04 6b8214a 8b10f04 6b8214a 8b10f04 6b8214a 8b10f04 6b8214a 8b10f04 6b8214a 3c4c5bc 6b8214a 3c4c5bc 8b10f04 3c4c5bc 8e62b80 8b10f04 3c4c5bc 6b8214a 8b10f04 3c4c5bc 8b10f04 3c4c5bc d417768 3c4c5bc d417768 8b10f04 6b8214a 3c4c5bc 8b10f04 c6fe084 3c4c5bc 8b10f04 7139673 d417768 8b10f04 d417768 3c4c5bc d417768 8b10f04 3c4c5bc 7139673 8b10f04 3c4c5bc 8b10f04 3c4c5bc d417768 3c4c5bc 8b10f04 3c4c5bc 6b8214a 3c4c5bc 8b10f04 8e62b80 8b10f04 8e62b80 8b10f04 3c4c5bc 8b10f04 d417768 3c4c5bc d417768 3c4c5bc d417768 8b10f04 6b8214a 3c4c5bc c6fe084 8b10f04 c6fe084 3c4c5bc 8b10f04 3c4c5bc d417768 3c4c5bc 6399834 8b10f04 3c4c5bc 463e388 3c4c5bc 8e62b80 3c4c5bc 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 7139673 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 3c4c5bc 8b10f04 6b8214a 8b10f04 6b8214a 7139673 6b8214a 8b10f04 6b8214a 8b10f04 6b8214a 7139673 6b8214a 8b10f04 d417768 8b10f04 6b8214a 8b10f04 6b8214a 8b10f04 6b8214a 8b10f04 6b8214a 8b10f04 6b8214a 6399834 6b8214a 8b10f04 6b8214a 3c4c5bc 6b8214a 3c4c5bc 6b8214a 3c4c5bc 6b8214a 3c4c5bc 6b8214a d417768 6b8214a d417768 6b8214a d417768 6b8214a 7139673 d417768 6b8214a d417768 3c4c5bc 6b8214a d417768 6b8214a d417768 6b8214a d417768 6b8214a d417768 6b8214a 8b10f04 d417768 8b10f04 d417768 8b10f04 d417768 8b10f04 d417768 3c4c5bc 8b10f04 6b8214a 8b10f04 3c4c5bc 8b10f04 6b8214a 8b10f04 6b8214a 8b10f04 6b8214a c6fe084 8b10f04 c6fe084 7139673 8b10f04 7139673 d417768 8b10f04 d417768 bfe46e3 8b10f04 d417768 bfe46e3 8b10f04 c6fe084 6b8214a c6fe084 8b10f04 c6fe084 6b8214a 8b10f04 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 3c4c5bc d417768 3c4c5bc 6b8214a 8b10f04 3c4c5bc 8b10f04 6b8214a c6fe084 8b10f04 6b8214a 3c4c5bc 8b10f04 3c4c5bc d417768 8b10f04 463e388 c6fe084 d417768 3c4c5bc 6399834 8b10f04 6b8214a 8b10f04 6b8214a 3c4c5bc 8b10f04 6b8214a 8b10f04 3c4c5bc 6b8214a 8b10f04 463e388 8b10f04 c6fe084 8b10f04 6b8214a 8e62b80 d417768 8e62b80 463e388 6b8214a 463e388 d417768 6399834 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 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 |
# /// script
# requires-python = ">=3.13"
# dependencies = [
# "marimo",
# ]
# ///
import marimo
__generated_with = "0.12.8"
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.5 | last modified: 2025-04-11 | 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 TypeVar
A = TypeVar("A")
B = TypeVar("B")
@dataclass
class Wrapper[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:
"""
)
return
@app.cell
def _(B, Callable, Functor, dataclass):
@dataclass
class Wrapper[A](Functor):
value: A
@classmethod
def fmap(cls, g: Callable[[A], B], fa: "Wrapper[A]") -> "Wrapper[B]":
return Wrapper(g(fa.value))
return (Wrapper,)
@app.cell(hide_code=True)
def _(mo):
mo.md(
r"""
/// attention
To distinguish between regular types and functors, we use the prefix `f` to indicate `Functor`.
For instance,
- `a: A` is a regular variable of type `A`
- `g: Callable[[A], B]` is a regular function from type `A` to `B`
- `fa: Functor[A]` is a *Functor* wrapping a value of type `A`
- `fg: Functor[Callable[[A], B]]` is a *Functor* wrapping a function from type `A` to `B`
and we will avoid using `f` to represent a function
///
> Try with Wrapper below
"""
)
return
@app.cell
def _(Wrapper, pp):
wrapper = Wrapper(1)
pp(Wrapper.fmap(lambda x: x + 1, wrapper))
pp(Wrapper.fmap(lambda x: [x], wrapper))
return (wrapper,)
@app.cell(hide_code=True)
def _(mo):
mo.md(
"""
We can analyze the type signature of `fmap` for `Wrapper`:
* `g` is of type `Callable[[A], B]`
* `fa` 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(g: Callable[[A], B], fa: 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 Functor
We can define a `List` class to represent a wrapped list that supports `fmap`:
"""
)
return
@app.cell
def _(B, Callable, Functor, dataclass):
@dataclass
class List[A](Functor):
value: list[A]
@classmethod
def fmap(cls, g: Callable[[A], B], fa: "List[A]") -> "List[B]":
return List([g(x) for x in fa.value])
return (List,)
@app.cell(hide_code=True)
def _(mo):
mo.md(r"""> Try with List below""")
return
@app.cell
def _(List, pp):
flist = List([1, 2, 3, 4])
pp(List.fmap(lambda x: x + 1, flist))
pp(List.fmap(lambda x: [x], flist))
return (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(g: Callable[[A], B], fa: List[A]) -> List[B]
```
Similarly, for `Wrapper`:
```python
fmap(g: Callable[[A], B], fa: Wrapper[A]) -> Wrapper[B]
```
Both follow the same pattern, which we can generalize as:
```python
fmap(g: Callable[[A], B], fa: 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
@dataclass
class Functor[A](ABC):
@classmethod
@abstractmethod
def fmap(g: Callable[[A], B], fa: "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.
"""
)
return
@app.cell(hide_code=True)
def _(mo):
mo.md(
r"""
# More Functor instances (optional)
In this section, we will explore more *Functor* instances to help you build up a better comprehension.
The main reference is [Data.Functor](https://hackage.haskell.org/package/base-4.21.0.0/docs/Data-Functor.html)
"""
)
return
@app.cell(hide_code=True)
def _(mo):
mo.md(
r"""
## The [Maybe](https://hackage.haskell.org/package/base-4.21.0.0/docs/Data-Maybe.html#t:Maybe) Functor
**`Maybe`** is a functor that can either hold a value (`Just(value)`) or be `Nothing` (equivalent to `None` in Python).
- It the value exists, `fmap` applies the function to this value inside the functor.
- If the value is `None`, `fmap` simply returns `None`.
/// admonition
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.
///
We can implement the `Maybe` functor as:
"""
)
return
@app.cell
def _(B, Callable, Functor, dataclass):
@dataclass
class Maybe[A](Functor):
value: None | A
@classmethod
def fmap(cls, g: Callable[[A], B], fa: "Maybe[A]") -> "Maybe[B]":
return cls(None) if fa.value is None else cls(g(fa.value))
def __repr__(self):
return "Nothing" if self.value is None else f"Just({self.value!r})"
return (Maybe,)
@app.cell
def _(Maybe, pp):
pp(Maybe.fmap(lambda x: x + 1, Maybe(1)))
pp(Maybe.fmap(lambda x: x + 1, Maybe(None)))
return
@app.cell(hide_code=True)
def _(mo):
mo.md(
r"""
## The [Either](https://hackage.haskell.org/package/base-4.21.0.0/docs/Data-Either.html#t:Either) Functor
The `Either` type represents values with two possibilities: a value of type `Either a b` is either `Left a` or `Right b`.
The `Either` type is sometimes used to represent a value which is **either correct or an error**; by convention, the `left` attribute is used to hold an error value and the `right` attribute is used to hold a correct value.
`fmap` for `Either` will ignore Left values, but will apply the supplied function to values contained in the Right.
The implementation is:
"""
)
return
@app.cell
def _(B, Callable, Functor, Union, dataclass):
@dataclass
class Either[A](Functor):
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
):
raise TypeError(
"Provide either the value of the left or the value of the right."
)
@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
def _(Either):
print(Either.fmap(lambda x: x + 1, Either(left=TypeError("Parse Error"))))
print(Either.fmap(lambda x: x + 1, Either(right=1)))
return
@app.cell(hide_code=True)
def _(mo):
mo.md(
"""
## The [RoseTree](https://en.wikipedia.org/wiki/Rose_tree) Functor
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
The implementation is:
"""
)
return
@app.cell
def _(B, Callable, Functor, dataclass):
@dataclass
class RoseTree[A](Functor):
value: A # The value stored in the node.
children: list[
"RoseTree[A]"
] # A list of child nodes forming the tree structure.
@classmethod
def fmap(cls, g: Callable[[A], B], fa: "RoseTree[A]") -> "RoseTree[B]":
"""
Applies a function to each value in the tree, producing a new `RoseTree[b]` with transformed values.
1. `g` is applied to the root node's `value`.
2. Each child in `children` recursively calls `fmap`.
"""
return RoseTree(
g(fa.value), [cls.fmap(g, child) for child in fa.children]
)
def __repr__(self) -> str:
return f"Node: {self.value}, Children: {self.children}"
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(g: 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]`.
Inspired by this, we can implement an `inc` function which takes a functor, applies the function `lambda x: x + 1` to every value inside it, and returns a new functor with the updated values.
"""
)
return
@app.cell
def _():
inc = lambda functor: functor.fmap(lambda x: x + 1, functor)
return (inc,)
@app.cell
def _(flist, inc, pp, rosetree, wrapper):
pp(inc(wrapper))
pp(inc(flist))
pp(inc(rosetree))
return
@app.cell(hide_code=True)
def _(mo):
mo.md(
r"""
/// admonition | exercise
Implement other generic functions and apply them to different *Functor* instances.
///
"""
)
return
@app.cell(hide_code=True)
def _(mo):
mo.md(r"""# Functor laws and utility functions""")
return
@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.md) as well.
///
"""
)
return
@app.cell(hide_code=True)
def _(mo):
mo.md(
r"""
### Functor laws verification
We can define `id` and `compose` in `Python` as:
"""
)
return
@app.cell
def _():
id = lambda x: x
compose = lambda f, g: lambda x: f(g(x))
return compose, id
@app.cell(hide_code=True)
def _(mo):
mo.md(r"""We can add a helper function `check_functor_law` to verify that an instance satisfies the functor laws:""")
return
@app.cell
def _(id):
check_functor_law = lambda functor: repr(functor.fmap(id, functor)) == repr(
functor
)
return (check_functor_law,)
@app.cell(hide_code=True)
def _(mo):
mo.md(r"""We can verify the functor we've defined:""")
return
@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`.""")
return
@app.cell
def _(B, Callable, Functor, dataclass):
@dataclass
class EvilFunctor[A](Functor):
value: list[A]
@classmethod
def fmap(
cls, g: Callable[[A], B], fa: "EvilFunctor[A]"
) -> "EvilFunctor[B]":
return (
cls([fa.value[0]] * 2 + [g(x) for x in fa.value[1:]])
if fa.value
else []
)
return (EvilFunctor,)
@app.cell
def _(EvilFunctor, check_functor_law, pp):
pp(check_functor_law(EvilFunctor([1, 2, 3, 4])))
return
@app.cell
def _(mo):
mo.md(
r"""
## Utility functions
```python
@classmethod
def const(cls, fa: "Functor[A]", b: B) -> "Functor[B]":
return cls.fmap(lambda _: b, fa)
@classmethod
def void(cls, fa: "Functor[A]") -> "Functor[None]":
return cls.const(fa, None)
@classmethod
def unzip(
cls, fab: "Functor[tuple[A, B]]"
) -> tuple["Functor[A]", "Functor[B]"]:
return cls.fmap(lambda p: p[0], fab), cls.fmap(lambda p: p[1], fab)
```
- `const` replaces all values inside a functor with a constant `b`
- `void` is equivalent to `const(fa, None)`, transforming all values in a functor into `None`
- `unzip` is a generalization of the regular *unzip* on a list of pairs
"""
)
return
@app.cell
def _(List, Maybe):
print(Maybe.const(Maybe(0), 1))
print(Maybe.const(Maybe(None), 1))
print(List.const(List([1, 2, 3, 4]), 1))
return
@app.cell
def _(List, Maybe):
print(Maybe.void(Maybe(1)))
print(List.void(List([1, 2, 3])))
return
@app.cell
def _(List, Maybe):
print(Maybe.unzip(Maybe(("Hello", "World"))))
print(List.unzip(List([("I", "love"), ("really", "Ξ»")])))
return
@app.cell(hide_code=True)
def _(mo):
mo.md(
r"""
/// admonition
You can always override these utility functions with a more efficient implementation for specific instances.
///
"""
)
return
@app.cell
def _(List, RoseTree, flist, pp, rosetree):
pp(RoseTree.const(rosetree, "Ξ»"))
pp(RoseTree.void(rosetree))
pp(List.const(flist, "Ξ»"))
pp(List.void(flist))
return
@app.cell(hide_code=True)
def _(mo):
mo.md("""# Formal implementation of Functor""")
return
@app.cell
def _(ABC, B, Callable, abstractmethod, dataclass):
@dataclass
class Functor[A](ABC):
@classmethod
@abstractmethod
def fmap(cls, g: Callable[[A], B], fa: "Functor[A]") -> "Functor[B]":
raise NotImplementedError("Subclasses must implement fmap")
@classmethod
def const(cls, fa: "Functor[A]", b: B) -> "Functor[B]":
return cls.fmap(lambda _: b, fa)
@classmethod
def void(cls, fa: "Functor[A]") -> "Functor[None]":
return cls.const(fa, None)
@classmethod
def unzip(
cls, fab: "Functor[tuple[A, B]]"
) -> tuple["Functor[A]", "Functor[B]"]:
return cls.fmap(lambda p: p[0], fab), cls.fmap(lambda p: p[1], fab)
return (Functor,)
@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: A) -> 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[A](ABC)
```
And RoseTree:
```Python
@dataclass
class RoseTree[A](Functor)
```
**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 )$.:
$$F({id} _{A})={id} _{F(A)}$$
3. Functors must distribute over morphism composition.
$$F(f\circ g)=F(f)\circ F(g)$$
"""
)
return
@app.cell(hide_code=True)
def _(mo):
mo.md(
"""
Remember that we defined the `id` and `compose` as
```python
id = lambda x: x
compose = lambda f, g: lambda x: f(g(x))
```
We can define `fmap` as:
```python
fmap = lambda g, functor: functor.fmap(g, functor)
```
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):
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[A](Functor):
value: A
@classmethod
def fmap(cls, g: Callable[[A], B], fa: "Wrapper[A]") -> "Wrapper[B]":
return Wrapper(g(fa.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, id, pp, wrapper):
pp(wrapper.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:
"""
)
return
@app.cell
def _(A, dataclass):
@dataclass
class ListConcatenation[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:
"""
)
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.
**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.
"""
)
return
@app.cell
def _(IntAddition, ListConcatenation, length, pp):
pp(length(ListConcatenation.id()) == IntAddition.id())
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(
"""
**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.
"""
)
return
@app.cell
def _(IntAddition, ListConcatenation, length, pp):
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("""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(hide_code=True)
def _(mo):
mo.md(
r"""
# Bifunctor
A `Bifunctor` is a type constructor that takes two type arguments and **is a functor in both arguments.**
For example, think about `Either`'s usual `Functor` instance. It only allows you to fmap over the second type parameter: `right` values get mapped, `left` values stay as they are.
However, its `Bifunctor` instance allows you to map both halves of the sum.
There are three core methods for `Bifunctor`:
- `bimap` allows mapping over both type arguments at once.
- `first` and `second` are also provided for mapping over only one type argument at a time.
The abstraction of `Bifunctor` is:
"""
)
return
@app.cell
def _(ABC, B, Callable, D, dataclass, f, id):
@dataclass
class Bifunctor[A, C](ABC):
@classmethod
def bimap(
cls, g: Callable[[A], B], h: Callable[[C], D], fa: "Bifunctor[A, C]"
) -> "Bifunctor[B, D]":
return cls.first(f, cls.second(g, fa))
@classmethod
def first(
cls, g: Callable[[A], B], fa: "Bifunctor[A, C]"
) -> "Bifunctor[B, C]":
return cls.bimap(g, id, fa)
@classmethod
def second(
cls, g: Callable[[B], C], fa: "Bifunctor[A, B]"
) -> "Bifunctor[A, C]":
return cls.bimap(id, g, fa)
return (Bifunctor,)
@app.cell(hide_code=True)
def _(mo):
mo.md(
r"""
/// admonition | minimal implementation requirement
- `bimap` or both `first` and `second`
///
"""
)
return
@app.cell(hide_code=True)
def _(mo):
mo.md(r"""## Instances of Bifunctor""")
return
@app.cell(hide_code=True)
def _(mo):
mo.md(
r"""
### The Either Bifunctor
For the `Either Bifunctor`, we allow it to map a function over the `left` value as well.
Notice that, the `Either Bifunctor` still only contains the `left` value or the `right` value.
"""
)
return
@app.cell
def _(B, Bifunctor, Callable, D, dataclass):
@dataclass
class BiEither[A, C](Bifunctor):
left: A = None
right: C = 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
):
raise TypeError(
"Provide either the value of the left or the value of the right."
)
@classmethod
def bimap(
cls, g: Callable[[A], B], h: Callable[[C], D], fa: "BiEither[A, C]"
) -> "BiEither[B, D]":
if fa.left is not None:
return cls(left=g(fa.left))
return cls(right=h(fa.right))
def __repr__(self):
if self.left is not None:
return f"Left({self.left!r})"
return f"Right({self.right!r})"
return (BiEither,)
@app.cell
def _(BiEither):
print(BiEither.bimap(lambda x: x + 1, lambda x: x * 2, BiEither(left=1)))
print(BiEither.bimap(lambda x: x + 1, lambda x: x * 2, BiEither(right=2)))
print(BiEither.first(lambda x: x + 1, BiEither(left=1)))
print(BiEither.first(lambda x: x + 1, BiEither(right=2)))
print(BiEither.second(lambda x: x + 1, BiEither(left=1)))
print(BiEither.second(lambda x: x + 1, BiEither(right=2)))
return
@app.cell(hide_code=True)
def _(mo):
mo.md(
r"""
### The 2d Tuple Bifunctor
For 2d tuples, we simply expect `bimap` to map 2 functions to the 2 elements in the tuple respectively.
"""
)
return
@app.cell
def _(B, Bifunctor, Callable, D, dataclass):
@dataclass
class BiTuple[A, C](Bifunctor):
value: tuple[A, C]
@classmethod
def bimap(
cls, g: Callable[[A], B], h: Callable[[C], D], fa: "BiTuple[A, C]"
) -> "BiTuple[B, D]":
return cls((g(fa.value[0]), h(fa.value[1])))
return (BiTuple,)
@app.cell
def _(BiTuple):
print(BiTuple.bimap(lambda x: x + 1, lambda x: x * 2, BiTuple((1, 2))))
print(BiTuple.first(lambda x: x + 1, BiTuple((1, 2))))
print(BiTuple.second(lambda x: x + 1, BiTuple((1, 2))))
return
@app.cell(hide_code=True)
def _(mo):
mo.md(
r"""
## Bifunctor laws
The only law we need to follow is
```python
bimap(id, id, fa) == id(fa)
```
and then other laws are followed automatically.
"""
)
return
@app.cell
def _(BiEither, BiTuple, id):
print(BiEither.bimap(id, id, BiEither(left=1)) == id(BiEither(left=1)))
print(BiEither.bimap(id, id, BiEither(right=1)) == id(BiEither(right=1)))
print(BiTuple.bimap(id, id, BiTuple((1, 2))) == id(BiTuple((1, 2))))
return
@app.cell(hide_code=True)
def _(mo):
mo.md(
"""
# Further reading
- [The Trivial Monad](http://blog.sigfpe.com/2007/04/trivial-monad.html)
- [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)
- [Haskellwiki: Category Theory](https://en.wikibooks.org/wiki/Haskell/Category_theory)
"""
)
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, TypeVar, Union
from pprint import pp
return Callable, TypeVar, Union, dataclass, pp
@app.cell(hide_code=True)
def _(TypeVar):
A = TypeVar("A")
B = TypeVar("B")
C = TypeVar("C")
D = TypeVar("D")
return A, B, C, D
if __name__ == "__main__":
app.run()
|