├── .gitattributes
├── .github
└── FUNDING.yml
├── .gitignore
├── .ocamlformat
├── LICENSE
├── README.org
├── chapter1
├── chapter1.md
├── dune
└── dune.inc
├── chapter10
├── README.md
├── dune
├── dune.inc
└── prelude.ml
├── chapter11
├── README.md
├── dune
├── dune.inc
└── prelude.ml
├── chapter12
├── README.md
├── dune
├── dune.inc
└── prelude.ml
├── chapter13
├── README.md
├── dune
├── dune.inc
└── prelude.ml
├── chapter14
├── README.md
├── dune
├── dune.inc
└── prelude.ml
├── chapter15
├── README.md
├── dune
├── dune.inc
└── prelude.ml
├── chapter16
├── README.md
├── dune
├── dune.inc
└── prelude.ml
├── chapter17
└── README.md
├── chapter18
├── README.md
├── dune
├── dune.inc
└── prelude.ml
├── chapter19
├── README.md
├── dune
├── dune.inc
└── prelude.ml
├── chapter2
├── README.md
├── dune
├── dune.inc
└── prelude.ml
├── chapter20
├── README.md
├── dune
├── dune.inc
└── prelude.ml
├── chapter21
├── README.md
├── dune
├── dune.inc
└── prelude.ml
├── chapter22
├── README.md
├── dune
├── dune.inc
└── prelude.ml
├── chapter23
├── README.md
├── dune
├── dune.inc
└── prelude.ml
├── chapter24
├── README.md
├── dune
├── dune.inc
└── prelude.ml
├── chapter25
├── README.md
├── dune
├── dune.inc
└── prelude.ml
├── chapter26
├── README.md
├── dune
├── dune.inc
└── prelude.ml
├── chapter27
├── README.md
├── dune
├── dune.inc
└── prelude.ml
├── chapter3
├── README.md
├── dune
├── dune.inc
└── prelude.ml
├── chapter30
├── README.md
├── dune
├── dune.inc
└── prelude.ml
├── chapter4
├── README.md
├── dune
├── dune.inc
└── prelude.ml
├── chapter5
├── README.md
├── dune
├── dune.inc
└── prelude.ml
├── chapter6
├── README.md
├── dune
├── dune.inc
└── prelude.ml
├── chapter7
├── README.md
├── dune
├── dune.inc
└── prelude.ml
├── chapter8
├── README.md
├── dune
├── dune.inc
└── prelude.ml
├── chapter9
├── README.md
├── dune
├── dune.inc
└── prelude.ml
├── dune
├── dune-project
├── ocaml-ctfp.install
├── ocaml-ctfp.opam
└── playground
├── .merlin
├── dune
├── dune-project
├── playground.md
└── playground.md.out.expected
/.gitattributes:
--------------------------------------------------------------------------------
1 | *.md linguist-language=OCaml
2 |
--------------------------------------------------------------------------------
/.github/FUNDING.yml:
--------------------------------------------------------------------------------
1 | # These are supported funding model platforms
2 |
3 | github: [ArulselvanMadhavan]
4 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | _opam/**
2 | **/_build/**
3 | **/.merlin
--------------------------------------------------------------------------------
/.ocamlformat:
--------------------------------------------------------------------------------
1 | profile=janestreet
2 | margin=70
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | GNU GENERAL PUBLIC LICENSE
2 | Version 3, 29 June 2007
3 |
4 | Copyright (C) 2007 Free Software Foundation, Inc.
5 | Everyone is permitted to copy and distribute verbatim copies
6 | of this license document, but changing it is not allowed.
7 |
8 | Preamble
9 |
10 | The GNU General Public License is a free, copyleft license for
11 | software and other kinds of works.
12 |
13 | The licenses for most software and other practical works are designed
14 | to take away your freedom to share and change the works. By contrast,
15 | the GNU General Public License is intended to guarantee your freedom to
16 | share and change all versions of a program--to make sure it remains free
17 | software for all its users. We, the Free Software Foundation, use the
18 | GNU General Public License for most of our software; it applies also to
19 | any other work released this way by its authors. You can apply it to
20 | your programs, too.
21 |
22 | When we speak of free software, we are referring to freedom, not
23 | price. Our General Public Licenses are designed to make sure that you
24 | have the freedom to distribute copies of free software (and charge for
25 | them if you wish), that you receive source code or can get it if you
26 | want it, that you can change the software or use pieces of it in new
27 | free programs, and that you know you can do these things.
28 |
29 | To protect your rights, we need to prevent others from denying you
30 | these rights or asking you to surrender the rights. Therefore, you have
31 | certain responsibilities if you distribute copies of the software, or if
32 | you modify it: responsibilities to respect the freedom of others.
33 |
34 | For example, if you distribute copies of such a program, whether
35 | gratis or for a fee, you must pass on to the recipients the same
36 | freedoms that you received. You must make sure that they, too, receive
37 | or can get the source code. And you must show them these terms so they
38 | know their rights.
39 |
40 | Developers that use the GNU GPL protect your rights with two steps:
41 | (1) assert copyright on the software, and (2) offer you this License
42 | giving you legal permission to copy, distribute and/or modify it.
43 |
44 | For the developers' and authors' protection, the GPL clearly explains
45 | that there is no warranty for this free software. For both users' and
46 | authors' sake, the GPL requires that modified versions be marked as
47 | changed, so that their problems will not be attributed erroneously to
48 | authors of previous versions.
49 |
50 | Some devices are designed to deny users access to install or run
51 | modified versions of the software inside them, although the manufacturer
52 | can do so. This is fundamentally incompatible with the aim of
53 | protecting users' freedom to change the software. The systematic
54 | pattern of such abuse occurs in the area of products for individuals to
55 | use, which is precisely where it is most unacceptable. Therefore, we
56 | have designed this version of the GPL to prohibit the practice for those
57 | products. If such problems arise substantially in other domains, we
58 | stand ready to extend this provision to those domains in future versions
59 | of the GPL, as needed to protect the freedom of users.
60 |
61 | Finally, every program is threatened constantly by software patents.
62 | States should not allow patents to restrict development and use of
63 | software on general-purpose computers, but in those that do, we wish to
64 | avoid the special danger that patents applied to a free program could
65 | make it effectively proprietary. To prevent this, the GPL assures that
66 | patents cannot be used to render the program non-free.
67 |
68 | The precise terms and conditions for copying, distribution and
69 | modification follow.
70 |
71 | TERMS AND CONDITIONS
72 |
73 | 0. Definitions.
74 |
75 | "This License" refers to version 3 of the GNU General Public License.
76 |
77 | "Copyright" also means copyright-like laws that apply to other kinds of
78 | works, such as semiconductor masks.
79 |
80 | "The Program" refers to any copyrightable work licensed under this
81 | License. Each licensee is addressed as "you". "Licensees" and
82 | "recipients" may be individuals or organizations.
83 |
84 | To "modify" a work means to copy from or adapt all or part of the work
85 | in a fashion requiring copyright permission, other than the making of an
86 | exact copy. The resulting work is called a "modified version" of the
87 | earlier work or a work "based on" the earlier work.
88 |
89 | A "covered work" means either the unmodified Program or a work based
90 | on the Program.
91 |
92 | To "propagate" a work means to do anything with it that, without
93 | permission, would make you directly or secondarily liable for
94 | infringement under applicable copyright law, except executing it on a
95 | computer or modifying a private copy. Propagation includes copying,
96 | distribution (with or without modification), making available to the
97 | public, and in some countries other activities as well.
98 |
99 | To "convey" a work means any kind of propagation that enables other
100 | parties to make or receive copies. Mere interaction with a user through
101 | a computer network, with no transfer of a copy, is not conveying.
102 |
103 | An interactive user interface displays "Appropriate Legal Notices"
104 | to the extent that it includes a convenient and prominently visible
105 | feature that (1) displays an appropriate copyright notice, and (2)
106 | tells the user that there is no warranty for the work (except to the
107 | extent that warranties are provided), that licensees may convey the
108 | work under this License, and how to view a copy of this License. If
109 | the interface presents a list of user commands or options, such as a
110 | menu, a prominent item in the list meets this criterion.
111 |
112 | 1. Source Code.
113 |
114 | The "source code" for a work means the preferred form of the work
115 | for making modifications to it. "Object code" means any non-source
116 | form of a work.
117 |
118 | A "Standard Interface" means an interface that either is an official
119 | standard defined by a recognized standards body, or, in the case of
120 | interfaces specified for a particular programming language, one that
121 | is widely used among developers working in that language.
122 |
123 | The "System Libraries" of an executable work include anything, other
124 | than the work as a whole, that (a) is included in the normal form of
125 | packaging a Major Component, but which is not part of that Major
126 | Component, and (b) serves only to enable use of the work with that
127 | Major Component, or to implement a Standard Interface for which an
128 | implementation is available to the public in source code form. A
129 | "Major Component", in this context, means a major essential component
130 | (kernel, window system, and so on) of the specific operating system
131 | (if any) on which the executable work runs, or a compiler used to
132 | produce the work, or an object code interpreter used to run it.
133 |
134 | The "Corresponding Source" for a work in object code form means all
135 | the source code needed to generate, install, and (for an executable
136 | work) run the object code and to modify the work, including scripts to
137 | control those activities. However, it does not include the work's
138 | System Libraries, or general-purpose tools or generally available free
139 | programs which are used unmodified in performing those activities but
140 | which are not part of the work. For example, Corresponding Source
141 | includes interface definition files associated with source files for
142 | the work, and the source code for shared libraries and dynamically
143 | linked subprograms that the work is specifically designed to require,
144 | such as by intimate data communication or control flow between those
145 | subprograms and other parts of the work.
146 |
147 | The Corresponding Source need not include anything that users
148 | can regenerate automatically from other parts of the Corresponding
149 | Source.
150 |
151 | The Corresponding Source for a work in source code form is that
152 | same work.
153 |
154 | 2. Basic Permissions.
155 |
156 | All rights granted under this License are granted for the term of
157 | copyright on the Program, and are irrevocable provided the stated
158 | conditions are met. This License explicitly affirms your unlimited
159 | permission to run the unmodified Program. The output from running a
160 | covered work is covered by this License only if the output, given its
161 | content, constitutes a covered work. This License acknowledges your
162 | rights of fair use or other equivalent, as provided by copyright law.
163 |
164 | You may make, run and propagate covered works that you do not
165 | convey, without conditions so long as your license otherwise remains
166 | in force. You may convey covered works to others for the sole purpose
167 | of having them make modifications exclusively for you, or provide you
168 | with facilities for running those works, provided that you comply with
169 | the terms of this License in conveying all material for which you do
170 | not control copyright. Those thus making or running the covered works
171 | for you must do so exclusively on your behalf, under your direction
172 | and control, on terms that prohibit them from making any copies of
173 | your copyrighted material outside their relationship with you.
174 |
175 | Conveying under any other circumstances is permitted solely under
176 | the conditions stated below. Sublicensing is not allowed; section 10
177 | makes it unnecessary.
178 |
179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
180 |
181 | No covered work shall be deemed part of an effective technological
182 | measure under any applicable law fulfilling obligations under article
183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or
184 | similar laws prohibiting or restricting circumvention of such
185 | measures.
186 |
187 | When you convey a covered work, you waive any legal power to forbid
188 | circumvention of technological measures to the extent such circumvention
189 | is effected by exercising rights under this License with respect to
190 | the covered work, and you disclaim any intention to limit operation or
191 | modification of the work as a means of enforcing, against the work's
192 | users, your or third parties' legal rights to forbid circumvention of
193 | technological measures.
194 |
195 | 4. Conveying Verbatim Copies.
196 |
197 | You may convey verbatim copies of the Program's source code as you
198 | receive it, in any medium, provided that you conspicuously and
199 | appropriately publish on each copy an appropriate copyright notice;
200 | keep intact all notices stating that this License and any
201 | non-permissive terms added in accord with section 7 apply to the code;
202 | keep intact all notices of the absence of any warranty; and give all
203 | recipients a copy of this License along with the Program.
204 |
205 | You may charge any price or no price for each copy that you convey,
206 | and you may offer support or warranty protection for a fee.
207 |
208 | 5. Conveying Modified Source Versions.
209 |
210 | You may convey a work based on the Program, or the modifications to
211 | produce it from the Program, in the form of source code under the
212 | terms of section 4, provided that you also meet all of these conditions:
213 |
214 | a) The work must carry prominent notices stating that you modified
215 | it, and giving a relevant date.
216 |
217 | b) The work must carry prominent notices stating that it is
218 | released under this License and any conditions added under section
219 | 7. This requirement modifies the requirement in section 4 to
220 | "keep intact all notices".
221 |
222 | c) You must license the entire work, as a whole, under this
223 | License to anyone who comes into possession of a copy. This
224 | License will therefore apply, along with any applicable section 7
225 | additional terms, to the whole of the work, and all its parts,
226 | regardless of how they are packaged. This License gives no
227 | permission to license the work in any other way, but it does not
228 | invalidate such permission if you have separately received it.
229 |
230 | d) If the work has interactive user interfaces, each must display
231 | Appropriate Legal Notices; however, if the Program has interactive
232 | interfaces that do not display Appropriate Legal Notices, your
233 | work need not make them do so.
234 |
235 | A compilation of a covered work with other separate and independent
236 | works, which are not by their nature extensions of the covered work,
237 | and which are not combined with it such as to form a larger program,
238 | in or on a volume of a storage or distribution medium, is called an
239 | "aggregate" if the compilation and its resulting copyright are not
240 | used to limit the access or legal rights of the compilation's users
241 | beyond what the individual works permit. Inclusion of a covered work
242 | in an aggregate does not cause this License to apply to the other
243 | parts of the aggregate.
244 |
245 | 6. Conveying Non-Source Forms.
246 |
247 | You may convey a covered work in object code form under the terms
248 | of sections 4 and 5, provided that you also convey the
249 | machine-readable Corresponding Source under the terms of this License,
250 | in one of these ways:
251 |
252 | a) Convey the object code in, or embodied in, a physical product
253 | (including a physical distribution medium), accompanied by the
254 | Corresponding Source fixed on a durable physical medium
255 | customarily used for software interchange.
256 |
257 | b) Convey the object code in, or embodied in, a physical product
258 | (including a physical distribution medium), accompanied by a
259 | written offer, valid for at least three years and valid for as
260 | long as you offer spare parts or customer support for that product
261 | model, to give anyone who possesses the object code either (1) a
262 | copy of the Corresponding Source for all the software in the
263 | product that is covered by this License, on a durable physical
264 | medium customarily used for software interchange, for a price no
265 | more than your reasonable cost of physically performing this
266 | conveying of source, or (2) access to copy the
267 | Corresponding Source from a network server at no charge.
268 |
269 | c) Convey individual copies of the object code with a copy of the
270 | written offer to provide the Corresponding Source. This
271 | alternative is allowed only occasionally and noncommercially, and
272 | only if you received the object code with such an offer, in accord
273 | with subsection 6b.
274 |
275 | d) Convey the object code by offering access from a designated
276 | place (gratis or for a charge), and offer equivalent access to the
277 | Corresponding Source in the same way through the same place at no
278 | further charge. You need not require recipients to copy the
279 | Corresponding Source along with the object code. If the place to
280 | copy the object code is a network server, the Corresponding Source
281 | may be on a different server (operated by you or a third party)
282 | that supports equivalent copying facilities, provided you maintain
283 | clear directions next to the object code saying where to find the
284 | Corresponding Source. Regardless of what server hosts the
285 | Corresponding Source, you remain obligated to ensure that it is
286 | available for as long as needed to satisfy these requirements.
287 |
288 | e) Convey the object code using peer-to-peer transmission, provided
289 | you inform other peers where the object code and Corresponding
290 | Source of the work are being offered to the general public at no
291 | charge under subsection 6d.
292 |
293 | A separable portion of the object code, whose source code is excluded
294 | from the Corresponding Source as a System Library, need not be
295 | included in conveying the object code work.
296 |
297 | A "User Product" is either (1) a "consumer product", which means any
298 | tangible personal property which is normally used for personal, family,
299 | or household purposes, or (2) anything designed or sold for incorporation
300 | into a dwelling. In determining whether a product is a consumer product,
301 | doubtful cases shall be resolved in favor of coverage. For a particular
302 | product received by a particular user, "normally used" refers to a
303 | typical or common use of that class of product, regardless of the status
304 | of the particular user or of the way in which the particular user
305 | actually uses, or expects or is expected to use, the product. A product
306 | is a consumer product regardless of whether the product has substantial
307 | commercial, industrial or non-consumer uses, unless such uses represent
308 | the only significant mode of use of the product.
309 |
310 | "Installation Information" for a User Product means any methods,
311 | procedures, authorization keys, or other information required to install
312 | and execute modified versions of a covered work in that User Product from
313 | a modified version of its Corresponding Source. The information must
314 | suffice to ensure that the continued functioning of the modified object
315 | code is in no case prevented or interfered with solely because
316 | modification has been made.
317 |
318 | If you convey an object code work under this section in, or with, or
319 | specifically for use in, a User Product, and the conveying occurs as
320 | part of a transaction in which the right of possession and use of the
321 | User Product is transferred to the recipient in perpetuity or for a
322 | fixed term (regardless of how the transaction is characterized), the
323 | Corresponding Source conveyed under this section must be accompanied
324 | by the Installation Information. But this requirement does not apply
325 | if neither you nor any third party retains the ability to install
326 | modified object code on the User Product (for example, the work has
327 | been installed in ROM).
328 |
329 | The requirement to provide Installation Information does not include a
330 | requirement to continue to provide support service, warranty, or updates
331 | for a work that has been modified or installed by the recipient, or for
332 | the User Product in which it has been modified or installed. Access to a
333 | network may be denied when the modification itself materially and
334 | adversely affects the operation of the network or violates the rules and
335 | protocols for communication across the network.
336 |
337 | Corresponding Source conveyed, and Installation Information provided,
338 | in accord with this section must be in a format that is publicly
339 | documented (and with an implementation available to the public in
340 | source code form), and must require no special password or key for
341 | unpacking, reading or copying.
342 |
343 | 7. Additional Terms.
344 |
345 | "Additional permissions" are terms that supplement the terms of this
346 | License by making exceptions from one or more of its conditions.
347 | Additional permissions that are applicable to the entire Program shall
348 | be treated as though they were included in this License, to the extent
349 | that they are valid under applicable law. If additional permissions
350 | apply only to part of the Program, that part may be used separately
351 | under those permissions, but the entire Program remains governed by
352 | this License without regard to the additional permissions.
353 |
354 | When you convey a copy of a covered work, you may at your option
355 | remove any additional permissions from that copy, or from any part of
356 | it. (Additional permissions may be written to require their own
357 | removal in certain cases when you modify the work.) You may place
358 | additional permissions on material, added by you to a covered work,
359 | for which you have or can give appropriate copyright permission.
360 |
361 | Notwithstanding any other provision of this License, for material you
362 | add to a covered work, you may (if authorized by the copyright holders of
363 | that material) supplement the terms of this License with terms:
364 |
365 | a) Disclaiming warranty or limiting liability differently from the
366 | terms of sections 15 and 16 of this License; or
367 |
368 | b) Requiring preservation of specified reasonable legal notices or
369 | author attributions in that material or in the Appropriate Legal
370 | Notices displayed by works containing it; or
371 |
372 | c) Prohibiting misrepresentation of the origin of that material, or
373 | requiring that modified versions of such material be marked in
374 | reasonable ways as different from the original version; or
375 |
376 | d) Limiting the use for publicity purposes of names of licensors or
377 | authors of the material; or
378 |
379 | e) Declining to grant rights under trademark law for use of some
380 | trade names, trademarks, or service marks; or
381 |
382 | f) Requiring indemnification of licensors and authors of that
383 | material by anyone who conveys the material (or modified versions of
384 | it) with contractual assumptions of liability to the recipient, for
385 | any liability that these contractual assumptions directly impose on
386 | those licensors and authors.
387 |
388 | All other non-permissive additional terms are considered "further
389 | restrictions" within the meaning of section 10. If the Program as you
390 | received it, or any part of it, contains a notice stating that it is
391 | governed by this License along with a term that is a further
392 | restriction, you may remove that term. If a license document contains
393 | a further restriction but permits relicensing or conveying under this
394 | License, you may add to a covered work material governed by the terms
395 | of that license document, provided that the further restriction does
396 | not survive such relicensing or conveying.
397 |
398 | If you add terms to a covered work in accord with this section, you
399 | must place, in the relevant source files, a statement of the
400 | additional terms that apply to those files, or a notice indicating
401 | where to find the applicable terms.
402 |
403 | Additional terms, permissive or non-permissive, may be stated in the
404 | form of a separately written license, or stated as exceptions;
405 | the above requirements apply either way.
406 |
407 | 8. Termination.
408 |
409 | You may not propagate or modify a covered work except as expressly
410 | provided under this License. Any attempt otherwise to propagate or
411 | modify it is void, and will automatically terminate your rights under
412 | this License (including any patent licenses granted under the third
413 | paragraph of section 11).
414 |
415 | However, if you cease all violation of this License, then your
416 | license from a particular copyright holder is reinstated (a)
417 | provisionally, unless and until the copyright holder explicitly and
418 | finally terminates your license, and (b) permanently, if the copyright
419 | holder fails to notify you of the violation by some reasonable means
420 | prior to 60 days after the cessation.
421 |
422 | Moreover, your license from a particular copyright holder is
423 | reinstated permanently if the copyright holder notifies you of the
424 | violation by some reasonable means, this is the first time you have
425 | received notice of violation of this License (for any work) from that
426 | copyright holder, and you cure the violation prior to 30 days after
427 | your receipt of the notice.
428 |
429 | Termination of your rights under this section does not terminate the
430 | licenses of parties who have received copies or rights from you under
431 | this License. If your rights have been terminated and not permanently
432 | reinstated, you do not qualify to receive new licenses for the same
433 | material under section 10.
434 |
435 | 9. Acceptance Not Required for Having Copies.
436 |
437 | You are not required to accept this License in order to receive or
438 | run a copy of the Program. Ancillary propagation of a covered work
439 | occurring solely as a consequence of using peer-to-peer transmission
440 | to receive a copy likewise does not require acceptance. However,
441 | nothing other than this License grants you permission to propagate or
442 | modify any covered work. These actions infringe copyright if you do
443 | not accept this License. Therefore, by modifying or propagating a
444 | covered work, you indicate your acceptance of this License to do so.
445 |
446 | 10. Automatic Licensing of Downstream Recipients.
447 |
448 | Each time you convey a covered work, the recipient automatically
449 | receives a license from the original licensors, to run, modify and
450 | propagate that work, subject to this License. You are not responsible
451 | for enforcing compliance by third parties with this License.
452 |
453 | An "entity transaction" is a transaction transferring control of an
454 | organization, or substantially all assets of one, or subdividing an
455 | organization, or merging organizations. If propagation of a covered
456 | work results from an entity transaction, each party to that
457 | transaction who receives a copy of the work also receives whatever
458 | licenses to the work the party's predecessor in interest had or could
459 | give under the previous paragraph, plus a right to possession of the
460 | Corresponding Source of the work from the predecessor in interest, if
461 | the predecessor has it or can get it with reasonable efforts.
462 |
463 | You may not impose any further restrictions on the exercise of the
464 | rights granted or affirmed under this License. For example, you may
465 | not impose a license fee, royalty, or other charge for exercise of
466 | rights granted under this License, and you may not initiate litigation
467 | (including a cross-claim or counterclaim in a lawsuit) alleging that
468 | any patent claim is infringed by making, using, selling, offering for
469 | sale, or importing the Program or any portion of it.
470 |
471 | 11. Patents.
472 |
473 | A "contributor" is a copyright holder who authorizes use under this
474 | License of the Program or a work on which the Program is based. The
475 | work thus licensed is called the contributor's "contributor version".
476 |
477 | A contributor's "essential patent claims" are all patent claims
478 | owned or controlled by the contributor, whether already acquired or
479 | hereafter acquired, that would be infringed by some manner, permitted
480 | by this License, of making, using, or selling its contributor version,
481 | but do not include claims that would be infringed only as a
482 | consequence of further modification of the contributor version. For
483 | purposes of this definition, "control" includes the right to grant
484 | patent sublicenses in a manner consistent with the requirements of
485 | this License.
486 |
487 | Each contributor grants you a non-exclusive, worldwide, royalty-free
488 | patent license under the contributor's essential patent claims, to
489 | make, use, sell, offer for sale, import and otherwise run, modify and
490 | propagate the contents of its contributor version.
491 |
492 | In the following three paragraphs, a "patent license" is any express
493 | agreement or commitment, however denominated, not to enforce a patent
494 | (such as an express permission to practice a patent or covenant not to
495 | sue for patent infringement). To "grant" such a patent license to a
496 | party means to make such an agreement or commitment not to enforce a
497 | patent against the party.
498 |
499 | If you convey a covered work, knowingly relying on a patent license,
500 | and the Corresponding Source of the work is not available for anyone
501 | to copy, free of charge and under the terms of this License, through a
502 | publicly available network server or other readily accessible means,
503 | then you must either (1) cause the Corresponding Source to be so
504 | available, or (2) arrange to deprive yourself of the benefit of the
505 | patent license for this particular work, or (3) arrange, in a manner
506 | consistent with the requirements of this License, to extend the patent
507 | license to downstream recipients. "Knowingly relying" means you have
508 | actual knowledge that, but for the patent license, your conveying the
509 | covered work in a country, or your recipient's use of the covered work
510 | in a country, would infringe one or more identifiable patents in that
511 | country that you have reason to believe are valid.
512 |
513 | If, pursuant to or in connection with a single transaction or
514 | arrangement, you convey, or propagate by procuring conveyance of, a
515 | covered work, and grant a patent license to some of the parties
516 | receiving the covered work authorizing them to use, propagate, modify
517 | or convey a specific copy of the covered work, then the patent license
518 | you grant is automatically extended to all recipients of the covered
519 | work and works based on it.
520 |
521 | A patent license is "discriminatory" if it does not include within
522 | the scope of its coverage, prohibits the exercise of, or is
523 | conditioned on the non-exercise of one or more of the rights that are
524 | specifically granted under this License. You may not convey a covered
525 | work if you are a party to an arrangement with a third party that is
526 | in the business of distributing software, under which you make payment
527 | to the third party based on the extent of your activity of conveying
528 | the work, and under which the third party grants, to any of the
529 | parties who would receive the covered work from you, a discriminatory
530 | patent license (a) in connection with copies of the covered work
531 | conveyed by you (or copies made from those copies), or (b) primarily
532 | for and in connection with specific products or compilations that
533 | contain the covered work, unless you entered into that arrangement,
534 | or that patent license was granted, prior to 28 March 2007.
535 |
536 | Nothing in this License shall be construed as excluding or limiting
537 | any implied license or other defenses to infringement that may
538 | otherwise be available to you under applicable patent law.
539 |
540 | 12. No Surrender of Others' Freedom.
541 |
542 | If conditions are imposed on you (whether by court order, agreement or
543 | otherwise) that contradict the conditions of this License, they do not
544 | excuse you from the conditions of this License. If you cannot convey a
545 | covered work so as to satisfy simultaneously your obligations under this
546 | License and any other pertinent obligations, then as a consequence you may
547 | not convey it at all. For example, if you agree to terms that obligate you
548 | to collect a royalty for further conveying from those to whom you convey
549 | the Program, the only way you could satisfy both those terms and this
550 | License would be to refrain entirely from conveying the Program.
551 |
552 | 13. Use with the GNU Affero General Public License.
553 |
554 | Notwithstanding any other provision of this License, you have
555 | permission to link or combine any covered work with a work licensed
556 | under version 3 of the GNU Affero General Public License into a single
557 | combined work, and to convey the resulting work. The terms of this
558 | License will continue to apply to the part which is the covered work,
559 | but the special requirements of the GNU Affero General Public License,
560 | section 13, concerning interaction through a network will apply to the
561 | combination as such.
562 |
563 | 14. Revised Versions of this License.
564 |
565 | The Free Software Foundation may publish revised and/or new versions of
566 | the GNU General Public License from time to time. Such new versions will
567 | be similar in spirit to the present version, but may differ in detail to
568 | address new problems or concerns.
569 |
570 | Each version is given a distinguishing version number. If the
571 | Program specifies that a certain numbered version of the GNU General
572 | Public License "or any later version" applies to it, you have the
573 | option of following the terms and conditions either of that numbered
574 | version or of any later version published by the Free Software
575 | Foundation. If the Program does not specify a version number of the
576 | GNU General Public License, you may choose any version ever published
577 | by the Free Software Foundation.
578 |
579 | If the Program specifies that a proxy can decide which future
580 | versions of the GNU General Public License can be used, that proxy's
581 | public statement of acceptance of a version permanently authorizes you
582 | to choose that version for the Program.
583 |
584 | Later license versions may give you additional or different
585 | permissions. However, no additional obligations are imposed on any
586 | author or copyright holder as a result of your choosing to follow a
587 | later version.
588 |
589 | 15. Disclaimer of Warranty.
590 |
591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
599 |
600 | 16. Limitation of Liability.
601 |
602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
610 | SUCH DAMAGES.
611 |
612 | 17. Interpretation of Sections 15 and 16.
613 |
614 | If the disclaimer of warranty and limitation of liability provided
615 | above cannot be given local legal effect according to their terms,
616 | reviewing courts shall apply local law that most closely approximates
617 | an absolute waiver of all civil liability in connection with the
618 | Program, unless a warranty or assumption of liability accompanies a
619 | copy of the Program in return for a fee.
620 |
621 | END OF TERMS AND CONDITIONS
622 |
623 | How to Apply These Terms to Your New Programs
624 |
625 | If you develop a new program, and you want it to be of the greatest
626 | possible use to the public, the best way to achieve this is to make it
627 | free software which everyone can redistribute and change under these terms.
628 |
629 | To do so, attach the following notices to the program. It is safest
630 | to attach them to the start of each source file to most effectively
631 | state the exclusion of warranty; and each file should have at least
632 | the "copyright" line and a pointer to where the full notice is found.
633 |
634 |
635 | Copyright (C)
636 |
637 | This program is free software: you can redistribute it and/or modify
638 | it under the terms of the GNU General Public License as published by
639 | the Free Software Foundation, either version 3 of the License, or
640 | (at your option) any later version.
641 |
642 | This program is distributed in the hope that it will be useful,
643 | but WITHOUT ANY WARRANTY; without even the implied warranty of
644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
645 | GNU General Public License for more details.
646 |
647 | You should have received a copy of the GNU General Public License
648 | along with this program. If not, see .
649 |
650 | Also add information on how to contact you by electronic and paper mail.
651 |
652 | If the program does terminal interaction, make it output a short
653 | notice like this when it starts in an interactive mode:
654 |
655 | Copyright (C)
656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
657 | This is free software, and you are welcome to redistribute it
658 | under certain conditions; type `show c' for details.
659 |
660 | The hypothetical commands `show w' and `show c' should show the appropriate
661 | parts of the General Public License. Of course, your program's commands
662 | might be different; for a GUI interface, you would use an "about box".
663 |
664 | You should also get your employer (if you work as a programmer) or school,
665 | if any, to sign a "copyright disclaimer" for the program, if necessary.
666 | For more information on this, and how to apply and follow the GNU GPL, see
667 | .
668 |
669 | The GNU General Public License does not permit incorporating your program
670 | into proprietary programs. If your program is a subroutine library, you
671 | may consider it more useful to permit linking proprietary applications with
672 | the library. If this is what you want to do, use the GNU Lesser General
673 | Public License instead of this License. But first, please read
674 | .
675 |
--------------------------------------------------------------------------------
/README.org:
--------------------------------------------------------------------------------
1 | * OCaml version of Category Theory For Programmers
2 |
3 | ** How do I get the book?
4 | - Currently, the book can be download by cloning this fork -
5 | https://github.com/ArulselvanMadhavan/milewski-ctfp-pdf and
6 | running
7 | #+BEGIN_SRC bash
8 | cd milewski-ctfp-pdf
9 | git checkout ocaml
10 | cd src
11 | make ocaml
12 | #+END_SRC
13 |
14 | ** Acknowledgements
15 | - Thanks to Marcello Seri @mseri for doing the code review. If @mseri
16 | hadn't offered to do the code review, this project would not have started
17 | - Thanks to @XVilka for promoting this effort in reddit, ocaml
18 | forums and offering helpful links
19 | - All the kind people in OCaml discord who hang out in the
20 | #beginners channel answering questions
21 |
22 | ** Helpful Resources
23 | - Resources I found useful as I started translating the book in OCaml:
24 | 1) https://github.com/freebroccolo/ocaml-cats
25 | 2) https://github.com/ocamllabs/higher
26 |
27 |
--------------------------------------------------------------------------------
/chapter1/chapter1.md:
--------------------------------------------------------------------------------
1 | # Chapter 1 - The essence of composition
2 | ### Utilities (Feel free to skip. Used to compile code below)
3 | ```ocaml
4 | # let (>>) : 'a 'b 'c. ('b -> 'c) -> ('a -> 'b) -> 'a -> 'c =
5 | fun g f x -> g (f x)
6 | val ( >> ) : ('b -> 'c) -> ('a -> 'b) -> 'a -> 'c =
7 | # let f : string -> int = String.length
8 | val f : string -> int =
9 | ```
10 | ### Code snippets
11 | * A generic function from type a to type b.
12 | ```ocaml
13 | module type Polymorphic_Function_F = sig
14 | type a
15 | type b
16 | val f : a -> b
17 | end
18 | ```
19 | * Another polymorphic function from type b to type c.
20 | ```ocaml
21 | module type Polymorphic_Function_G = sig
22 | type b
23 | type c
24 | val g : b -> c
25 | end
26 | ```
27 | * Compose Function definition is not part of the standard library. We can define a custom /compose/ function.
28 | ```ocaml
29 | module Compose_Example = functor(F: Polymorphic_Function_F)(G: Polymorphic_Function_G with type b = F.b) -> struct
30 | (** OCaml doesn't have a compose operator. So, creating one. **)
31 | let (>>) g f x = g (f x)
32 | let compose : 'a -> 'c = G.g >> F.f
33 | end
34 | ```
35 | * Compose Three functions
36 | ```OCaml
37 | module Compose_Three_GF = functor(F:Polymorphic_Function_F)(G:Polymorphic_Function_G with type b = F.b)(H:Polymorphic_Function_H with type c = G.c) -> struct
38 | let compose : 'a -> 'd = H.h >> (G.g >> F.f)
39 | end
40 |
41 | module Compose_Three_HG = functor(F:Polymorphic_Function_F)(G:Polymorphic_Function_G with type b = F.b)(H:Polymorphic_Function_H with type c = G.c) -> struct
42 | let compose : 'a -> 'd = (H.h >> G.g) >> F.f
43 | end
44 |
45 | Compose_Three_GF.compose = Compose_Three_HG.compose
46 | ```
47 | * Identity Function
48 | ```ocaml
49 | # let id x = x
50 | val id : 'a -> 'a =
51 | ```
52 | * Compose and Identity
53 | ```OCaml
54 | f >> id
55 | id >> f
56 | ```
57 |
--------------------------------------------------------------------------------
/chapter1/dune:
--------------------------------------------------------------------------------
1 | (rule
2 | (with-stdout-to dune.gen
3 | (run ocaml-mdx rule --direction=to-ml chapter1.md)))
4 |
5 | (alias
6 | (name runtest)
7 | (deps chapter1.md)
8 | (action (diff dune.inc dune.gen)))
9 |
10 | (include dune.inc)
--------------------------------------------------------------------------------
/chapter1/dune.inc:
--------------------------------------------------------------------------------
1 | (alias
2 | (name runtest)
3 | (deps (:x chapter1.md))
4 | (action (progn
5 | (run ocaml-mdx test --direction=to-ml %{x})
6 | (diff? %{x} %{x}.corrected)
7 | )))
8 |
--------------------------------------------------------------------------------
/chapter10/README.md:
--------------------------------------------------------------------------------
1 | # Natural Transformations
2 | ### Utilities used by the code below
3 | ```ocaml
4 | type ('a, 'b) const = Const of 'a
5 | module type Functor = sig
6 | type 'a t
7 | val fmap : ('a -> 'b) -> 'a t -> 'b t
8 | end
9 | let compose f g x = f (g x)
10 | module type Contravariant = sig
11 | type 'a t
12 | val contramap : ('b -> 'a) -> 'a t -> 'b t
13 | end
14 | ```
15 | - Functor is a mapping between categories that preserve their structure.
16 | - Embeds source category in target category by using the source as the blueprint.
17 | - Functor
18 | - may collapse the whole source category into one object in the target category.
19 | - map every object to a different object
20 | - map every morphism to different morphism
21 | - Natural transformation help us compare these realizations.
22 | - Mappings of functors.
23 | - Natural isomorphism is defined as a natural transformation whose components are all isomorphisms.
24 | ### Polymorphic Functions
25 | - Endofunctors - Type constructors that map types to types. Source and target category are the same.
26 | ```OCaml
27 | val alpha : 'a . 'a f -> 'a g
28 | ```
29 | - Without universal quantification.
30 | ```OCaml
31 | val alpha : 'a f -> 'a g
32 | ```
33 | - Polymorphic functions like this automatically satisfy the naturality condition.
34 | ```OCaml
35 | val alpha : 'a f -> 'a g
36 | ```
37 | - Free theorems are the naturality conditions, in the case of natural transformations expressed using parametric polymorphism.
38 | ```ocaml
39 | # let safe_head = function
40 | | [] -> None
41 | | x :: xs -> Some x
42 | val safe_head : 'a list -> 'a option =
43 | ```
44 | - Verifying the Naturality condition(Pseudo OCaml, since function equality cannot be expressed)
45 | ```OCaml
46 | compose (fmap f) safe_head = compose safe_head (fmap f)
47 | ```
48 | - Cases to handle
49 | ```OCaml
50 | (* Starting with empty list *)
51 | let fmap f (safe_head []) = fmap f None = None
52 | ```
53 | ```OCaml
54 | let safe_head (fmap f []) = safe_head [] = None
55 | ```
56 | - Non empty list
57 | ```OCaml
58 | let fmap f (safe_head (x :: xs)) = fmap f (Some x)= Some (f x)
59 | ```
60 | ```OCaml
61 | let safe_head (fmap f (x :: xs)) = safe_head (f x :: f xs) = Some (f x)
62 | ```
63 | - Implemenation of fmap for lists
64 | ```ocaml
65 | # let rec fmap f = function
66 | | [] -> []
67 | | (x :: xs) -> f x :: fmap f xs
68 | val fmap : ('a -> 'b) -> 'a list -> 'b list =
69 | ```
70 | - Implementation of fmap for option type
71 | ```ocaml
72 | # let rec fmap f = function
73 | | None -> None
74 | | Some x -> Some (f x)
75 | val fmap : ('a -> 'b) -> 'a option -> 'b option =
76 | ```
77 | - Natural transformation to or from the *Const* functor looks just like a function that's polymorphic in either the return type or argument type.
78 | ```ocaml
79 | (** OCaml requires mutually recursive functions to be defined together *)
80 | let rec length : 'a list -> (int, 'a) const = function
81 | | [] -> Const 0
82 | | (_ :: xs) -> Const (1 + un_const (length xs))
83 | and un_const : 'c 'a. ('c, 'a) const -> 'c = function | Const c -> c
84 | ```
85 | - unconst defined separately
86 | ```ocaml
87 | let un_const : 'c 'a. ('c, 'a) const -> 'c = function | Const c -> c
88 | ```
89 | - In practice, length is defined as
90 | ```OCaml
91 | val length : 'a list -> int
92 | ```
93 | - Parametrically polymorphic function from `Const` functor
94 | ```ocaml
95 | # let scam : 'a. ('int, 'a) const -> 'a option = function
96 | | Const a -> None
97 | val scam : ('int, 'a) const -> 'a option =
98 | ```
99 | - Reader type
100 | ```ocaml
101 | type ('e, 'a) reader = Reader of ('e -> 'a)
102 | ```
103 | - Functor instance for Reader type
104 | ```ocaml
105 | module Reader_Functor(T : sig type e end) : Functor = struct
106 | type 'a t = (T.e, 'a) reader
107 | let fmap : 'a 'b. ('a -> 'b) -> 'a t -> 'b t = fun f -> function
108 | | Reader r -> Reader (compose f r)
109 | end
110 | ```
111 | - Natural Transformation from Reader () a -> Maybe a
112 | ```OCaml
113 | val alpha : (unit, 'a) reader -> 'a option
114 | ```
115 | - dumb version
116 | ```ocaml
117 | # let dumb : 'a. (unit, 'a) reader -> 'a option = function
118 | | Reader _ -> None
119 | val dumb : (unit, 'a) reader -> 'a option =
120 | ```
121 | - obvious implementation
122 | ```ocaml
123 | # let obvious : 'a. (unit, 'a) reader -> 'a option = function
124 | | Reader f -> Some (f ())
125 | val obvious : (unit, 'a) reader -> 'a option =
126 | ```
127 | ### Beyond Naturality
128 | - Parametrically polymorphic function between two functors is always a natural transformation.
129 | - Function types are covariant in their return type.
130 | - Function types are contravariant in their argument type.
131 | - Contravariant example
132 | ```ocaml
133 | type ('r, 'a) op = Op of ('a -> 'r)
134 | ```
135 | - Contravariant instance
136 | ```ocaml
137 | module Op_Contravariant(T : sig type r end): Contravariant = struct
138 | type 'a t = (T.r, 'a) op
139 | let contramap : ('b -> 'a) -> 'a t -> 'b t = fun f -> function
140 | | Op g -> Op (compose g f)
141 | end
142 | ```
143 | - predToStr
144 | ```ocaml
145 | # let pred_to_str = function
146 | | Op f -> Op (fun x -> if f x then "T" else "F")
147 | val pred_to_str : (bool, 'a) op -> (string, 'a) op =
148 | ```
149 | - Contravariant functors satisfy the opposite naturality condition.
150 | ```OCaml
151 | compose (contramap f) pred_to_str = compose pred_to_str (contramap f)
152 | ```
153 | - Op Bool contramap signature
154 | ```ocaml
155 | module Op_Bool = Op_Contravariant(struct type r = bool end)
156 | let op_bool_contramap : ('b -> 'a) -> 'a Op_Bool.t -> 'b Op_Bool.t = Op_Bool.contramap
157 | ```
158 | - Type constructors that are neither covariant or contravariant.
159 | ```OCaml
160 | 'a -> 'a
161 | ```
162 | ```OCaml
163 | ('a -> 'a) -> 'a f
164 | ```
165 | - Dinatural transformation is a generalization of the natural transformations.
166 | ### Functor Category
167 | - There is one category of functors for each pair of categories, C and D.
168 | - Objects in this category are functors from C to D.
169 | - Morphisms = Natural transformations between C and D.
170 | - Composition of natural transformations is associative.
171 | - Functor category between C and D is Fun(C, D) or |C, D| or D^C
172 | ### Revisiting abstractions
173 | - Category
174 | - objects and morphisms
175 | - Cat - Higher order category that contains other categories as objects.
176 | - Morphisms in Cat are functors.
177 | - Hom-Set in Cat is a set of functors. Cat(C,D) - Set of functors between C and D categories.
178 | - Functor Category |C,D| is *also* a set of functors between C and D.
179 | - Functor Category is also a category. So it must be part of Cat.
180 | - Cat is a full blown Cartesian Closed Category in which there is an exponential object D^C for any pair of categories. This exponential object is a category - Functor Category Fun(C, D)
181 | ### 2-Categories
182 | - Cat - Higher order category with categories as objects and functors as morphisms.
183 | - Hom-Set in Cat is a set of functors.
184 | - Set of functors form a category.
185 | - Functors are morphisms in Cat. Natural transformations are morphisms between morphisms.
186 | - 2-category contains
187 | - objects - Categories
188 | - 1 morphisms - Functors between categories
189 | - 2 morphisms between morphisms - Natural transformation between functors.
190 |
--------------------------------------------------------------------------------
/chapter10/dune:
--------------------------------------------------------------------------------
1 | (rule
2 | (with-stdout-to dune.gen
3 | (run ocaml-mdx rule --direction=to-ml README.md --prelude=prelude.ml)))
4 |
5 | (alias
6 | (name runtest)
7 | (deps README.md)
8 | (action (diff dune.inc dune.gen)))
9 |
10 | (include dune.inc)
--------------------------------------------------------------------------------
/chapter10/dune.inc:
--------------------------------------------------------------------------------
1 | (alias
2 | (name runtest)
3 | (deps (:x README.md)
4 | prelude.ml)
5 | (action (progn
6 | (run ocaml-mdx test --prelude=prelude.ml --direction=to-ml %{x})
7 | (diff? %{x} %{x}.corrected)
8 | )))
9 |
--------------------------------------------------------------------------------
/chapter10/prelude.ml:
--------------------------------------------------------------------------------
1 | #require "core,core.top,ppx_jane";;
2 |
3 | open Base
4 |
5 | let () = Printexc.record_backtrace false
6 |
--------------------------------------------------------------------------------
/chapter11/README.md:
--------------------------------------------------------------------------------
1 | # Declarative Programming
2 | ### Utilities (Needed for compiling the code. Skip this section)
3 | ```ocaml
4 | let compose g f x = g (f x)
5 | ```
6 | - Snippets marked as Pseudo OCaml are not compiled by mdx
7 | ### Declarative Programming in compose
8 | - Compose (declarative)
9 | ```OCaml
10 | (* Assume g and f are already defined *)
11 | let h = compose g f
12 | ```
13 | - Compose (imperative)
14 | ```OCaml
15 | let h = fun x ->
16 | let y = f x in
17 | g y
18 | ```
19 |
--------------------------------------------------------------------------------
/chapter11/dune:
--------------------------------------------------------------------------------
1 | (rule
2 | (with-stdout-to dune.gen
3 | (run ocaml-mdx rule --direction=to-ml README.md --prelude=prelude.ml)))
4 |
5 | (alias
6 | (name runtest)
7 | (deps README.md)
8 | (action (diff dune.inc dune.gen)))
9 |
10 | (include dune.inc)
--------------------------------------------------------------------------------
/chapter11/dune.inc:
--------------------------------------------------------------------------------
1 | (alias
2 | (name runtest)
3 | (deps (:x README.md)
4 | prelude.ml)
5 | (action (progn
6 | (run ocaml-mdx test --prelude=prelude.ml --direction=to-ml %{x})
7 | (diff? %{x} %{x}.corrected)
8 | )))
9 |
--------------------------------------------------------------------------------
/chapter11/prelude.ml:
--------------------------------------------------------------------------------
1 | #require "core,core.top,ppx_jane";;
2 |
3 | open Base
4 |
5 | let () = Printexc.record_backtrace false
6 |
--------------------------------------------------------------------------------
/chapter12/README.md:
--------------------------------------------------------------------------------
1 | # Limits and Colimits
2 | ### Utilities used by the code below
3 | ```ocaml
4 | let compose f g x = f (g x)
5 | ```
6 | - In CT, everything is related to everything and can be viewed from many angles.
7 | ### Generalizing products
8 | - 2 category
9 | - contains two objects.
10 | - No morphisms between them.
11 | - Only identity morphsisms.
12 | - Selecting two objects in C is the same as defining a functor(D) from 2 to C.
13 | - Selecting a candidate object c
14 | - A constant functor from 2 to C
15 | - Selection of c in C is done using the constant functor.
16 | - Natural transformation between constant functor (to c) and D
17 | - NT component - 'c' to 'a' is a morphism - p
18 | - NT component - 'c' to 'b' is a morphism - q
19 | ```OCaml
20 | let p1 = compose p m
21 | let q1 = compose q m
22 | ```
23 | - Contramap definition
24 | ```ocaml
25 | # let contramap : ('c_prime -> 'c) -> ('c -> 'limD) -> ('c_prime -> 'limD) = fun f u -> compose u f
26 | val contramap : ('c_prime -> 'c) -> ('c -> 'limD) -> 'c_prime -> 'limD =
27 |
28 | ```
29 | - Presheaves: Contravariant functor from any category C to Set
30 | - Natural Isomorphism: Natural Transformation whose every component is an isomorphism.
31 | ### Examples of limits
32 | - Example of a limit - Terminal object
33 | - Terminal object is a limit generated by an empty category.
34 | - Functor from an empty category selects no object, so a cone shrinks to just the apex.
35 | - Equalizer - A limit generated by a two-element category with two parallel morphisms going between them
36 | -
37 | ```OCaml
38 | val f : 'a -> 'b
39 | val g : 'a -> 'b
40 | ```
41 | ```OCaml
42 | val p : 'c -> 'a
43 | val q : 'c -> 'b
44 | ```
45 | ```OCaml
46 | q = compose f p
47 | q = compose g p
48 | ```
49 | ```OCaml
50 | (** Pseudo OCaml expressing function equality **)
51 | compose f p = compose g p
52 | ```
53 | - Example: a - two dimensional plane parameterized by coordinates x and y
54 | - b - real line
55 | ```ocaml
56 | let f (x, y) = 2 * y + x
57 | let g (x, y) = y - x
58 | ```
59 | -
60 | ```ocaml
61 | let p t = (t, (-2) * t)
62 | ```
63 | ```OCaml
64 | (** Pseudo OCaml expressing function equality **)
65 | compose f p' = compose g p'
66 | ```
67 | ```ocaml
68 | let p' () = (0, 0)
69 | ```
70 | ```OCaml
71 | let p' = compose p h
72 | ```
73 | ```ocaml
74 | let h () = 0
75 | ```
76 | - Pullback - Has two morphisms that we want to equate but their domains are different.
77 | ```OCaml
78 | val f : 'a -> 'b
79 | val g : 'c -> 'b
80 | ```
81 | - cospan
82 | ```OCaml
83 | val p : 'd -> 'a
84 | val q : 'd -> 'c
85 | val r : 'd -> 'b
86 | ```
87 | - Commutativity conditions
88 | ```OCaml
89 | compose g q = compose f p
90 | ```
91 | ```ocaml
92 | let f x = 1.23
93 | ```
94 | ### Colimits
95 | - Dual of limits
96 | - Co-cone - Invert the direction of all arrows in a cone
97 | - Universal co-cone - Co-limit
98 | - Example of a co-limit - co-product
99 | - Terminal object - limit
100 | - Initial object - co-limit
101 | - Dual of the pullback - pushout ex: 1 <- 2 -> 3
102 | ### Continuity
103 | - Continuous Functor F from C to C' preserves limits
104 | - Functors preserve almost everything.
105 | - Uniqueness condition may be the only affected property
106 | - Hom-functor C^op x C -> Set
107 | ```ocaml
108 | module type Contravariant = sig
109 | type 'a t
110 | val contramap : ('b -> 'a) -> 'a t -> 'b t
111 | end
112 | type 'a tostring = ToString of ('a -> string)
113 |
114 | module ToStringInstance : Contravariant = struct
115 | type 'a t = 'a tostring
116 | let contramap f (ToString g) = ToString (compose g f)
117 | end
118 | ```
119 | ```OCaml
120 | ('b 'c either) tostring ~ ('b -> string, 'c -> string)
121 | ```
122 | ```OCaml
123 | 'r -> ('a, 'b) ~ ('r -> 'a, 'r -> 'b)
124 | ```
125 |
126 |
--------------------------------------------------------------------------------
/chapter12/dune:
--------------------------------------------------------------------------------
1 | (rule
2 | (with-stdout-to dune.gen
3 | (run ocaml-mdx rule --direction=to-ml README.md --prelude=prelude.ml)))
4 |
5 | (alias
6 | (name runtest)
7 | (deps README.md)
8 | (action (diff dune.inc dune.gen)))
9 |
10 | (include dune.inc)
--------------------------------------------------------------------------------
/chapter12/dune.inc:
--------------------------------------------------------------------------------
1 | (alias
2 | (name runtest)
3 | (deps (:x README.md)
4 | prelude.ml)
5 | (action (progn
6 | (run ocaml-mdx test --prelude=prelude.ml --direction=to-ml %{x})
7 | (diff? %{x} %{x}.corrected)
8 | )))
9 |
--------------------------------------------------------------------------------
/chapter12/prelude.ml:
--------------------------------------------------------------------------------
1 | #require "core,core.top,ppx_jane";;
2 |
3 | open Base
4 |
5 | let () = Printexc.record_backtrace false
6 |
--------------------------------------------------------------------------------
/chapter13/README.md:
--------------------------------------------------------------------------------
1 | # Free Monoids
2 | ## Utilities used by the code below
3 | ```ocaml
4 | module type Functor = sig
5 | type 'a t
6 | val fmap : ('a -> 'b) -> 'a t -> 'b t
7 | end
8 | let compose f g x = f (g x)
9 | ```
10 | - Categories - strongly typed languages
11 | - Monoids - untyped languages
12 | - Monoid - Category with a single object, where all logic is encoded in rules of morphism composition.
13 | - Categorical model of monoid is fully equivalent to set theoretical definition of monoid.
14 | - Generators of the free monoid - basic set of elements needed to generate free monoid
15 | - Free construction - keep generating all possible combination of elements, and perform the minimum number of identifications - just enough to uphold the laws
16 | ### Free Monoid in OCaml
17 | ```ocaml
18 | module type Monoid = sig
19 | type m
20 | val mempty : m
21 | val mappend : m -> m -> m
22 | end
23 | ```
24 | - Monoid instance for list
25 | ```ocaml
26 | module ListMonoid(T1 : sig type a end) : (Monoid with type m = T1.a list) = struct
27 | type m = T1.a list
28 | let mempty = []
29 | let mappend xs ys = List.append xs ys
30 | end;;
31 | ```
32 | ```OCaml
33 | 2 * 3 = 6
34 | List.append [2] [3] = [2; 3]
35 | ```
36 | ### Free monoid universal construction
37 | ```OCaml
38 | let h (a * b) = h a * h b
39 | ```
40 | - Homomorphism from lists of integers to integers
41 | ```OCaml
42 | List.append [2] [3] = [2; 3]
43 | ```
44 | - becomes multiplication
45 | ```ocaml
46 | 2 * 3 = 6
47 | ```
48 | - Let p be the function that identifies the set of generators inside the X-ray image of monoid m.
49 | ```ocaml
50 | module type FreeMonoidRep = functor (F : Functor) -> sig
51 | type x
52 | type m
53 | val p : x -> m F.t
54 | end
55 | ```
56 | - Similar function on a different monoid n can be
57 | ```ocaml
58 | module type FreeMonoidRep = functor (F : Functor) -> sig
59 | type x
60 | type n
61 | val q : x -> n F.t
62 | end
63 | ```
64 | - Homomorphism between monoids
65 | ```OCaml
66 | val h : m -> n
67 | ```
68 | - Building q through p
69 | ```OCaml
70 | val q = compose uh p
71 | ```
72 |
--------------------------------------------------------------------------------
/chapter13/dune:
--------------------------------------------------------------------------------
1 | (rule
2 | (with-stdout-to dune.gen
3 | (run ocaml-mdx rule --direction=to-ml README.md --prelude=prelude.ml)))
4 |
5 | (alias
6 | (name runtest)
7 | (deps README.md)
8 | (action (diff dune.inc dune.gen)))
9 |
10 | (include dune.inc)
--------------------------------------------------------------------------------
/chapter13/dune.inc:
--------------------------------------------------------------------------------
1 | (alias
2 | (name runtest)
3 | (deps (:x README.md)
4 | prelude.ml)
5 | (action (progn
6 | (run ocaml-mdx test --prelude=prelude.ml --direction=to-ml %{x})
7 | (diff? %{x} %{x}.corrected)
8 | )))
9 |
--------------------------------------------------------------------------------
/chapter13/prelude.ml:
--------------------------------------------------------------------------------
1 | #require "core,core.top,ppx_jane";;
2 |
3 | open Base
4 |
5 | let () = Printexc.record_backtrace false
6 |
--------------------------------------------------------------------------------
/chapter14/README.md:
--------------------------------------------------------------------------------
1 | # Representable Functors
2 | ## Utilities used by the code below
3 | ```ocaml
4 | module type Functor = sig
5 | type 'a t
6 | val fmap : ('a -> 'b) -> 'a t -> 'b t
7 | end
8 |
9 | module type Contravariant = sig
10 | type 'a t
11 | val contramap : ('b -> 'a) -> 'a t -> 'b t
12 | end
13 |
14 | module type Profunctor = sig
15 | type ('a,'b) p
16 | val dimap : ('a -> 'b) -> ('c -> 'd) -> ('b, 'c) p -> ('a, 'd) p
17 | val lmap : ('a -> 'b) -> ('b, 'c) p -> ('a, 'c) p
18 | val rmap : ('b -> 'c) -> ('a, 'b) p -> ('a, 'c) p
19 | end
20 |
21 | let flip f b a = f a b
22 | let compose f g x = f (g x)
23 | ```
24 | - Set theory - assembly language of mathematics
25 | - *Set* category of all sets
26 | - morphisms between any two objects in a category form a set (hom-set)
27 | - All the information about sets can be encoded in *isormorphic* functions between them.
28 | - Interaction between programming and math goes both ways.
29 | ## Hom Functor
30 | - There's family of mappings from a category to Set
31 | - These mappings are functors.
32 | - hom-functor is reader functor
33 | ```ocaml
34 | type ('a, 'x) reader = 'a -> 'x
35 | ```
36 | - C(a,-) - CoVariant Functor instance
37 | ```ocaml
38 | module ReaderFunctor(T : sig type r end) : Functor = struct
39 | type 'a t = (T.r, 'a) reader
40 | let fmap f h = fun a -> f (h a)
41 | end
42 | ```
43 | - C(-,a) - Contravariant Functor
44 | ```ocaml
45 | type ('a, 'x) op = 'x -> 'a
46 | ```
47 | - Contravariant instance
48 | ```ocaml
49 | module OpContravariant(T : sig type r end) : Contravariant = struct
50 | type 'a t = (T.r, 'a) op
51 | let contramap f h = fun b -> h (f b)
52 | end
53 | ```
54 | - C(-, -) - If we allows both arguments to change
55 | ```ocaml
56 | module ProfunctorArrow : Profunctor = struct
57 | type ('a, 'b) p = 'a -> 'b
58 | let dimap f g p = compose g (compose p f)
59 | let lmap f p = (flip compose) f p
60 | let rmap = compose
61 | end
62 | ```
63 | - The mapping of objects from any category to hom-sets is functorial.
64 | - C^op x C -> Set
65 | ## Representable Functors
66 | - Structure preserving mapping to Set is called a *representation*.
67 | - Any functor F that is naturally isomorphic to hom-functor for some choice of a is called representable functor.
68 | - For F to be representable,
69 | - an object a in C
70 | - Nat Transformation(between functors) - alpha - C(a, -) to F
71 | - Nat Transformation - beta - F to C(a, -)
72 | - Composition of these two Nat Trans is Identity Nat Trans
73 | - alphaAtx :: C(a, x) -> Fx
74 | ```ocaml
75 | module type NT_AX_FX = sig
76 | type a
77 | type 'x t
78 | val alpha : (a -> 'x) -> 'x t
79 | end
80 | ```
81 | - Pseudo OCaml expressing function equality
82 | ```OCaml
83 | compose (F.fmap f) NT.alpha = compose NT.alpha (F.fmap f)
84 | ```
85 | - Replacing fmap with function composition (since fmap on f is a reader functor on the right hand side)
86 | ```OCaml
87 | F.fmap f (N.alpha h) = N.alpha (compose f h)
88 | ```
89 | - Other Nat Transformation that goes opposite direction
90 | ```ocaml
91 | module type NT_FX_AX = sig
92 | type a
93 | type 'x t
94 | val beta : 'x t -> (a -> 'x)
95 | end
96 | ```
97 | - alpha . beta = id = beta . alpha
98 | - Yoneda Lemma: Nat Trans from C(a, -) to any Set-valued functor always exists but it's not always invertible.
99 | - Alpha example
100 | ```ocaml
101 | module NT_Impl(F: Functor with type 'a t = 'a list) : NT_AX_FX with type a = int and type 'x t = 'x list = struct
102 | type a = int
103 | type 'x t = 'x list
104 | let alpha: 'x. (int -> 'x) -> 'x list = fun h -> F.fmap h [12]
105 | end
106 | ```
107 | - Naturality condition is equivalent to the composiability of map.
108 | ```OCaml
109 | F.fmap f (F.fmap h [12]) = F.fmap (compose f h) [12]
110 | ```
111 | - Beta with example on List and Int
112 | ```ocaml
113 | module type NT_ListX_IntX = sig
114 | type a = int
115 | type 'x t = 'x list
116 | val beta : 'x t -> (a -> 'x)
117 | end
118 | ```
119 | - Beta can't be implemented for List and Int combination. (When List is empty we can't return a value of type x)
120 | - So, List functor is not Representable.
121 | - Rep. functors are containers for memoized results of function calls
122 | - Representing type 'a' of C(a, -) is the key type to access values of a function.
123 | - *alpha* is called tabulate and *beta* is called index.
124 | - Representable functor
125 | ```ocaml
126 | module type Representable = sig
127 | type 'x t
128 | type rep (* Representing type 'a' *)
129 | val tabulate : (rep -> 'x) -> 'x t
130 | val index : 'x t -> (rep -> 'x)
131 | end
132 | ```
133 | - Stream type
134 | ```ocaml
135 | type 'a stream = | Cons of 'a * 'a stream Lazy.t
136 | ```
137 | - Representable functor Instance
138 | ```ocaml
139 | module StreamRepresentable : Representable = struct
140 | type rep = int
141 | type 'x t = 'x stream
142 | let rec tabulate f = Cons ((f 0), lazy (tabulate (compose f succ)))
143 | let rec index (Cons (b, bs)) n = if n = 0 then b else index (Lazy.force bs) (n - 1)
144 | end
145 | ```
146 | - Single memoization scheme to cover a whole family of functions with arbitrary return types.
147 | - Representability of contravariant functors
148 | - Functor that are based on product types can be represented with sum types.
149 | - Sum-type functors in general are not representable.
150 | - Representable functor gives us two different implementations of the same thing - one a function, one a data structure.
151 | - Two representations are implemented differently and have different perf characteristics.
152 | - Being able to provide different representation of the same underlying computations is very valuable, in practice.
153 |
--------------------------------------------------------------------------------
/chapter14/dune:
--------------------------------------------------------------------------------
1 | (rule
2 | (with-stdout-to dune.gen
3 | (run ocaml-mdx rule --direction=to-ml README.md --prelude=prelude.ml)))
4 |
5 | (alias
6 | (name runtest)
7 | (deps README.md)
8 | (action (diff dune.inc dune.gen)))
9 |
10 | (include dune.inc)
--------------------------------------------------------------------------------
/chapter14/dune.inc:
--------------------------------------------------------------------------------
1 | (alias
2 | (name runtest)
3 | (deps (:x README.md)
4 | prelude.ml)
5 | (action (progn
6 | (run ocaml-mdx test --prelude=prelude.ml --direction=to-ml %{x})
7 | (diff? %{x} %{x}.corrected)
8 | )))
9 |
--------------------------------------------------------------------------------
/chapter14/prelude.ml:
--------------------------------------------------------------------------------
1 | #require "core,core.top,ppx_jane";;
2 |
3 | open Base
4 |
5 | let () = Printexc.record_backtrace false
6 |
--------------------------------------------------------------------------------
/chapter15/README.md:
--------------------------------------------------------------------------------
1 | # The Yoneda Lemma
2 | ## Utilities used by code below
3 | ```ocaml
4 | module type Functor = sig
5 | type 'a t
6 | val fmap : ('a -> 'b) -> 'a t -> 'b t
7 | end
8 | ```
9 | ## Yoneda Lemma
10 | - Yoneda Lemma is a statement about categories that doesn't have a parallel in other branches of mathematics
11 | - Arbitrary category C, Functor F from C to Set
12 | - Some Set-valued functors are "representable"
13 | - YL: All set-valued functors can be obtained from hom-functors through natural transformations and it explicitly enumerates all such natural transformations.
14 | - Naturality condition can be quite restrictive
15 | - YL: NT between a hom-functor and any other functor F is completely determined by specifying the value of its single component at just one point.
16 | - Hom-functor: C(a,x) , C(a, f)
17 | - Set-valued functor F
18 | - alpha - NT between these two functors
19 | - Nat Trans |C(a,-), F| = Fa
20 | - Reader = Hom-Functor
21 | ```ocaml
22 | type ('a, 'x) reader = 'a -> 'x
23 | ```
24 | - Reader Functor Instance (Maps morphisms by precomposition
25 | ```ocaml
26 | module ReaderFunctor(T : sig type a end):Functor = struct
27 | type 'x t = (T.a, 'x) reader
28 | let fmap : ('x -> 'y) -> 'x t -> 'y t = fun f r -> fun a -> f (r a)
29 | end
30 | ```
31 | - YL: Reader functor can be naturally mapped to any other functor
32 | - A Polymorphic function `alpha`
33 | ```ocaml
34 | module type NT_AX_FX = sig
35 | type a
36 | type 'x t
37 | val alpha : (a -> 'x) -> 'x t
38 | end
39 | ```
40 | - Polymorphic function
41 | ```OCaml
42 | val alpha : (a -> 'x) -> 'x t
43 | ```
44 | - YL can produce a container of F a when given a polymorphic function `alpha`. (Pseudo OCaml)
45 | ```OCaml
46 | alpha id : 'a f
47 | ```
48 | - Converse is also true
49 | ```OCaml
50 | val fa : 'a f
51 | ```
52 | - Converse implementation (Define a polymorphic function from F a . (Pseudo OCaml)
53 | ```OCaml
54 | alpha h = F.fmap h fa
55 | ```
56 | - Advantage of having a multiple representations is that one might be easier to compose than the other or one might be efficient than the other.
57 | - CPS = YL applied to Identity Functor
58 | ### Co-Yoneda
59 | - YL on C^op
60 | - Nat|C(-, a), F) = F a
61 | ```
62 | forall: 'x . ('x -> 'a) -> 'x t = 'a f
63 | ```
64 |
--------------------------------------------------------------------------------
/chapter15/dune:
--------------------------------------------------------------------------------
1 | (rule
2 | (with-stdout-to dune.gen
3 | (run ocaml-mdx rule --direction=to-ml README.md --prelude=prelude.ml)))
4 |
5 | (alias
6 | (name runtest)
7 | (deps README.md)
8 | (action (diff dune.inc dune.gen)))
9 |
10 | (include dune.inc)
--------------------------------------------------------------------------------
/chapter15/dune.inc:
--------------------------------------------------------------------------------
1 | (alias
2 | (name runtest)
3 | (deps (:x README.md)
4 | prelude.ml)
5 | (action (progn
6 | (run ocaml-mdx test --prelude=prelude.ml --direction=to-ml %{x})
7 | (diff? %{x} %{x}.corrected)
8 | )))
9 |
--------------------------------------------------------------------------------
/chapter15/prelude.ml:
--------------------------------------------------------------------------------
1 | #require "core,core.top,ppx_jane";;
2 |
3 | open Base
4 |
5 | let () = Printexc.record_backtrace false
6 |
--------------------------------------------------------------------------------
/chapter16/README.md:
--------------------------------------------------------------------------------
1 | # Yoneda Embedding
2 | ## Utilities used by code below
3 | ```ocaml
4 | let id a = a
5 | ```
6 | - C(a, -) - covariant functor from C to Set
7 | - For every a, when we try to get a mapping from C(a, -) to Set, they end up being objects in the functor category.
8 | - [C, Set] Functor Category from C to Set
9 | - A morphism in C is C(a, b)
10 | - A morphism in [C, Set] is a natural transformation.
11 | - Mapping of morphism to Natural Transformations is interesting
12 | - a is mapped to C(a, -)
13 | - b is mapped to C(b, -)
14 | - YL: [C, Set](C(a,-), F) = Fa
15 | - [C, Set](C(a, -), C(b,-)) = C(b, a)
16 | - NT between two hom-functors we got using YL gave us a contravariant functor
17 | - Mapping from C to [C, Set] is a contravariant, fully faithful functor
18 | - Faithful functor - Injective on hom-sets - No coalescing of morphisms
19 | - Full functor - surjective on hom-sets - maps one hom-set onto the other hom-set, fully covering the latter.
20 | - Fully faithful functor is a bijection on hom-sets.
21 | ### Embedding
22 | - The contravariant functor that maps objects in C to [C, Set] defines the Yoneda Embedding
23 | - It embeds C inside [C, Set]
24 | - Co-Yoneda Embedding
25 | - Embedding of category C in the category of presheaves
26 | - [C, Set](C(-, a), C(-, b)) = C(a, b)
27 | ### Application to OCaml
28 | - Yoneda Embedding - isomorphism between natural transformations amongst reader functors and functions
29 | ```ocaml
30 | module type BtoA = sig
31 | type a
32 | type b
33 | val btoa : b -> a
34 | end
35 | (* Define the Yoneda embedding *)
36 | module Yoneda_Embedding(E: BtoA) = struct
37 | let fromY : (E.a -> 'x) -> E.b -> 'x = fun f b -> f (E.btoa b)
38 | end
39 | ```
40 | - To recover converter
41 | ```OCaml
42 | module YE = Yoneda_Embedding(BtoAImpl)
43 | YE.fromY id (* output type : BtoA.b -> BtoA.a *)
44 | ```
45 | ### Preorder example
46 | - YE to preorder category
47 | - A set with Preorder relation gives rise to a category.
48 | - hom-set in this category is either an empty set or a one-element set.
49 | ## Naturality
50 | - YL establishes the isomorphism between the set of NT and an object in Set.
51 | - Set of NT between any functors is a hom-set in the category [C, Set]
52 | - [C, Set](C(a,-), F) = Fa
53 | - Natural isomorphism is an invertible NT between two functors.
54 |
--------------------------------------------------------------------------------
/chapter16/dune:
--------------------------------------------------------------------------------
1 | (rule
2 | (with-stdout-to dune.gen
3 | (run ocaml-mdx rule --direction=to-ml README.md --prelude=prelude.ml)))
4 |
5 | (alias
6 | (name runtest)
7 | (deps README.md)
8 | (action (diff dune.inc dune.gen)))
9 |
10 | (include dune.inc)
--------------------------------------------------------------------------------
/chapter16/dune.inc:
--------------------------------------------------------------------------------
1 | (alias
2 | (name runtest)
3 | (deps (:x README.md)
4 | prelude.ml)
5 | (action (progn
6 | (run ocaml-mdx test --prelude=prelude.ml --direction=to-ml %{x})
7 | (diff? %{x} %{x}.corrected)
8 | )))
9 |
--------------------------------------------------------------------------------
/chapter16/prelude.ml:
--------------------------------------------------------------------------------
1 | #require "core,core.top,ppx_jane";;
2 |
3 | open Base
4 |
5 | let () = Printexc.record_backtrace false
6 |
--------------------------------------------------------------------------------
/chapter17/README.md:
--------------------------------------------------------------------------------
1 | # It's all about Morphisms
2 | - Review of building blocks of hom-sets
3 | - Adjunctions are defined in terms of isomorphisms of hom-sets
4 | ## Functors
5 | - mappings of morphisms
6 | - objects tell us which pairs of morphisms are composable.
7 | ## Commuting diagrams
8 | - Used for expressing properties of morphisms
9 | - Forms the basis of all universal constructions
10 | ## Natural Transformations
11 | - NT - mapping from morphisms to commuting squares
12 | - Naturality square - Two opposing sides are the mappings of a morphism f under F and G
13 | - The other sides are the components of the NT
14 | - Functor modifies the content of a container without changing its shape
15 | - NT repackages the content in a different container without touching the contents.
16 | - A limit is defined in terms of cones.
17 | - Universal cone is the NT between the contravariant hom-functor
18 | ## Natural Isomorphisms
19 | - National Isomorphims - A NT whose every component is reversible
20 | ## Hom-Sets
21 | - Fix the source and target objects, the morphisms between the two form a boring set
22 | - Difference between members of a hom-set lies in the way they compose with other morphisms
23 | - Ff =/ Fg
24 | ## Hom-set Isomorphism
25 | - Iso between hom-sets
26 | - Plain isomorphism between them is not interesting.
27 | - Meaningful iso should take into account the composition
28 | - composition involves more than one hom-set
29 | - Iso that span whole collection of hom-sets, and we need to impose some compatibility conditions that interoperate with composition
30 |
--------------------------------------------------------------------------------
/chapter18/README.md:
--------------------------------------------------------------------------------
1 | # Adjunctions
2 | ## Utilities used by code below
3 | ```ocaml
4 | module type Functor = sig
5 | type 'a t
6 | val fmap : ('a -> 'b) -> 'a t -> 'b t
7 | end
8 | module type Representable = sig
9 | type 'x t
10 | type rep (* Representing type 'a' *)
11 | val tabulate : (rep -> 'x) -> 'x t
12 | val index : 'x t -> (rep -> 'x)
13 | val fmap : ('x -> 'y) -> 'x t -> 'y t
14 | end
15 | let idty : 'a -> 'a = fun a -> a
16 | ```
17 | ## Equality vs Iso
18 | - Equality is too strong
19 | - Isomorphism - two things can be same without actually being equal as long as there is an invertible morphism
20 | ```ocaml
21 | let swap (a, b) = (b, a)
22 | ```
23 | ## Adjunction and Unit/Counit Pair
24 | - Categories being isomorphic is expressed in terms of functors between them.
25 | - Cat C and D are isomorphic,
26 | - if there exists a functor R from C to D
27 | - if there exists a functor L from D to C
28 | - Composition of two functors R compose L and L compose R.
29 | - R compose L = I_D
30 | - L compose R = I_C
31 | - Equality of functors can be expressed via natural isomorphisms.
32 | - unit :: I_D -> R compose L
33 | - counit :: L compose R -> I_C
34 | - L - Left adjoint
35 | - R - Right adjoint
36 | - Compact Notation for Adjunction: L -| R
37 | - unit lets us introduce composition R compose L in place of an Identity functor on D
38 | - counit lets us eliminate composition L compose R and replace it with an Identity functor on C.
39 | - unit in OCaml
40 | ```ocaml
41 | module type Unit_Example = sig
42 | type 'a m
43 | val return : 'a -> 'A m
44 | end
45 | ```
46 | - extract in OCaml
47 | ```ocaml
48 | module type Counit_Example = sig
49 | type 'c w
50 | val extract : 'c w -> 'c
51 | end
52 | ```
53 | - 'm' is the endofunctor corresponding to R compose L and w is the endofunctor corresponding to L compose R.
54 | - unit is a polymorphic function that creates a default box around a value of arbitrary type.
55 | - counit does the opposite.
56 | - Pair of adjoint functors define a monad and comonad
57 | - Adjunctions of Endofunctors.
58 | ```ocaml
59 | (* L is Functor F and R is Representable Functor U *)
60 | module type Adjunction = functor (F : Functor) (U : Representable) -> sig
61 | val unit : 'a -> ('a F.t) U.t
62 | val counit : ('a U.t) F.t -> 'a
63 | end
64 | ```
65 | ## Adjunctions and Hom-Sets
66 | - Adjunctions in terms of natural isomorphisms of hom-sets.
67 | - Unique morphism - mapping some set to hom-set
68 | - Factorization can be described in terms of NT
69 | - Factorization involves commuting diagrams since it defines a morphism being equal to composition of two morphisms.
70 | - Universal construction - involves factorization - morphism to commuting diagram and then to a unique morphism.
71 | - If this morphism is invertible and it can be extended to all hom-sets then we have an adjunction.
72 | - Alternative defintion:
73 | - L :: D -> C and R :: C -> D
74 | - d - source object in D; c - target object in C
75 | - Ld -> map d to C
76 | - hom-set between Ld and c = C(Ld, c)
77 | - Rc -> map c to R
78 | - hom-set between d and Rc = D(d, Rc)
79 | - L is left-adjoint to R iff there is an isomorphism of hom-sets:
80 | - C(Ld, c) is isomorphic to D(d, Rc)
81 | - Naturality means d can be varied across D and c can be varied across C.
82 | ```ocaml
83 | module type Adjunction_HomSet = functor (F : Functor)(U : Representable) -> sig
84 | val left_adjunct : ('a F.t -> 'b) -> ('a -> 'b U.t)
85 | val right_adjunct : ('a -> 'b U.t) -> ('a F.t -> 'b)
86 | end
87 | ```
88 | - Equivalence between unit/counit and left_adjunct/right_adjunct
89 | - Complete Adjunction Definition
90 | ```ocaml
91 | (* Putting it all together to show the equivalence between unit/counit and left_adjunct/right_adjunct *)
92 | module type Adjunction = functor (F : Functor)(U : Representable) -> sig
93 | val unit : 'a -> ('a F.t) U.t
94 | val counit : ('a U.t) F.t -> 'a
95 | val left_adjunct : ('a F.t -> 'b) -> ('a -> 'b U.t)
96 | val right_adjunct : ('a -> 'b U.t) -> ('a F.t -> 'b)
97 | end
98 |
99 | (* Adjunction via unit/counit *)
100 | module type Adjunction_Unit_Counit = functor(F: Functor)(U: Representable) -> sig
101 | val unit : 'a -> ('a F.t) U.t
102 | val counit : ('a U.t) F.t -> 'a
103 | end
104 | (* Adjunction via left and right adjoints *)
105 | module type Adjunction_Hom_Set = functor (F:Functor)(U:Representable) -> sig
106 | val left_adjunct : ('a F.t -> 'b) -> 'a -> 'b U.t
107 | val right_adjunct : ('a -> 'b U.t) -> 'a F.t -> 'b
108 | end
109 |
110 | (* Implementing unit/counit from left and right adjoint definitions *)
111 | module Adjunction_From_Hom_Set(A : Adjunction_Hom_Set) : Adjunction = functor(F : Functor)(U : Representable) -> struct
112 | type 't f = 't F.t
113 | type 't u = 't U.t
114 | module M = A(F)(U)
115 | include M
116 | let unit : 'a -> 'a f u = fun a -> M.left_adjunct idty a
117 | let counit : ('a u) f -> 'a = fun fua -> M.right_adjunct idty fua
118 | end
119 |
120 | (* Implementing left and right adjunct from unit/counit Definitions *)
121 | module Adjunction_From_Unit_Counit(A:Adjunction_Unit_Counit):Adjunction = functor(F:Functor)(U:Representable) -> struct
122 | type 't f = 't F.t
123 | type 't u = 't U.t
124 | module M = A(F)(U)
125 | include M
126 | let left_adjunct f = fun a -> (U.fmap f) (M.unit a)
127 | let right_adjunct f = fun fa -> M.counit (F.fmap f fa)
128 | end
129 | ```
130 | - Why is the Right adjoint a representable functor
131 | - Right category D is Set
132 | - R is representable if we can find an object rep in C such that C(rep, _) is naturally isomorphic to R
133 | - rep = L()
134 | - C(L(), c) is naturally isomorphic to Set((), Rc)
135 | - C(L(), _) is naturally isomorphic to R
136 | - So, R is representable
137 | ### Product from Adjunction
138 | - factorizer
139 | ```ocaml
140 | let factorizer p q = fun x -> (p x, q x)
141 | ```
142 | - Pseudo OCaml expressing function equality
143 | ```OCaml
144 | compose fst (factorizer p q) = p
145 | compose snd (factorizer p q) = q
146 | ```
147 | - Product category
148 | - C and D
149 | - C x D - product category - pairs of objects from C and D - pairs of morphisms from C and D
150 | - Left aadjoint functor is the diagonal functor
151 | - Right adjoint functor is the Product bifunctor
152 | ```OCaml
153 | int * bool ~ (int, bool)
154 | ```
155 | ## Exponential form Adjunction
156 | - Function object a => b
157 | - g :: z * a -> b ; h :: z -> (a => b)
158 | - Mapping between hom-sets
159 | - Two adjoint functors are endofunctors
160 | - eval function is the counit of this adjunction: (a => b) x a -> b
161 | - If a functor has an adjoint, then it is unique up to isomorphism
162 |
--------------------------------------------------------------------------------
/chapter18/dune:
--------------------------------------------------------------------------------
1 | (rule
2 | (with-stdout-to dune.gen
3 | (run ocaml-mdx rule --direction=to-ml README.md --prelude=prelude.ml)))
4 |
5 | (alias
6 | (name runtest)
7 | (deps README.md)
8 | (action (diff dune.inc dune.gen)))
9 |
10 | (include dune.inc)
--------------------------------------------------------------------------------
/chapter18/dune.inc:
--------------------------------------------------------------------------------
1 | (alias
2 | (name runtest)
3 | (deps (:x README.md)
4 | prelude.ml)
5 | (action (progn
6 | (run ocaml-mdx test --prelude=prelude.ml --direction=to-ml %{x})
7 | (diff? %{x} %{x}.corrected)
8 | )))
9 |
--------------------------------------------------------------------------------
/chapter18/prelude.ml:
--------------------------------------------------------------------------------
1 | #require "core,core.top,ppx_jane";;
2 |
3 | open Base
4 |
5 | let () = Printexc.record_backtrace false
6 |
--------------------------------------------------------------------------------
/chapter19/README.md:
--------------------------------------------------------------------------------
1 | # Free/Forgetful Adjunctions
2 | ## Utilities used by code below
3 | ## Introduction
4 | - A free functor is the left adjoint of a forgetful functor
5 | - Forgetful functor - that forgets some structure
6 | - A functor mapping from C to Set.
7 | - A set corresponding to some object in C is called underlying set.
8 | - Monoid category has objects that have underlying sets
9 | - Forgetful functor U -> maps from Mon to Set
10 | - U maps monoid homomorphisms to functions between sets.
11 | - Mon to Set
12 | - Adjunction: Mon(Fx, m) = Set(x, Um)
13 | - Fx is the maximum monoid that can be built on the basis of x.
14 | ## Monoid with list type
15 | - 'a list is a free monoid where 'a represents the set of generators
16 | - Appending is associative and unital
17 | ```ocaml
18 | (* OCaml's string type is an immutable array of bytes *)
19 | type string' = char list
20 | ```
21 | - Isomorphism with list of units
22 | ```ocaml
23 | let to_nat : unit list -> int = List.length
24 | let to_lst : int -> unit list = fun n -> List.init n ~f:(fun _ -> ())
25 | ```
26 | ## Intuitions
27 | - Functors and functions are lossy in nature.
28 | - Functors may collapse multiple objects and morphisms
29 | - Functions may collapse multiple elements of a set.
30 | - Monomorphisms - Injective(non-collapsing)
31 | - Epimorphisms - Surjective(covering the whole codomain)
32 | - Free -| Forgetful adjunction
33 | - Constrained category C is on the left
34 | - Less constrained category D is on the right
35 | - Morhphisms in C are fewer because they have to preserve additional structure.
36 | - Image of F must consist of structure-free objects, so that there is no structure to preserve by morphisms.
37 | - These objects of F are called free objects.
38 | - C(Fd, c) = D(d, Uc)
39 | - Free monoids instead of performing the operation, they accumulate the arguments that were passed to it.
40 | - Free constructions: Accumulate expression trees before evaluating them.
41 |
--------------------------------------------------------------------------------
/chapter19/dune:
--------------------------------------------------------------------------------
1 | (rule
2 | (with-stdout-to dune.gen
3 | (run ocaml-mdx rule --direction=to-ml README.md --prelude=prelude.ml)))
4 |
5 | (alias
6 | (name runtest)
7 | (deps README.md)
8 | (action (diff dune.inc dune.gen)))
9 |
10 | (include dune.inc)
--------------------------------------------------------------------------------
/chapter19/dune.inc:
--------------------------------------------------------------------------------
1 | (alias
2 | (name runtest)
3 | (deps (:x README.md)
4 | prelude.ml)
5 | (action (progn
6 | (run ocaml-mdx test --prelude=prelude.ml --direction=to-ml %{x})
7 | (diff? %{x} %{x}.corrected)
8 | )))
9 |
--------------------------------------------------------------------------------
/chapter19/prelude.ml:
--------------------------------------------------------------------------------
1 | #require "core,core.top,ppx_jane";;
2 |
3 | open Base
4 |
5 | let () = Printexc.record_backtrace false
6 |
--------------------------------------------------------------------------------
/chapter2/README.md:
--------------------------------------------------------------------------------
1 | # Types and Functions
2 | * Declare a variable and assign a type
3 | ```ocaml
4 | module type Chapter2_DeclareVariable = sig
5 | val x : int
6 | end
7 | ```
8 | * Declare a function and assign a type
9 | ```ocaml
10 | module type Chapter2_DeclareFunction = sig
11 | val f : bool -> bool
12 | end
13 | ```
14 | * OCaml doesn't have null. Throw exceptions to introduce runtime errors
15 | ```ocaml
16 | module Chapter2_Bottom : Chapter2_DeclareFunction =
17 | struct
18 | let f (b:bool):bool = failwith "Not Implemented"
19 | end
20 | ```
21 | * Bottom is also a member of bool -> bool
22 | ```ocaml
23 | module Chapter2_Bottom : Chapter2_DeclareFunction =
24 | struct
25 | let f : bool -> bool = fun _ -> failwith "Not implemented"
26 | end
27 | ```
28 | * Functions that return bottom are called /Partial/
29 | * /Hask/ can be treated as /Set/
30 | * Factorial Function in OCaml
31 | ```ocaml
32 | # let fact n =
33 | List.fold (List.range 1 n) ~init:1 ~f:( * )
34 | val fact : int -> int =
35 | ```
36 | * Absurd in OCaml
37 | ```ocaml
38 | type void
39 | let rec absurd (x:void) = absurd x
40 | ```
41 | * Function taking unit and returning any type
42 | ```ocaml
43 | # let f44 () : int = 44
44 | val f44 : unit -> int =
45 | ```
46 | * f\_int
47 | ```ocaml
48 | # let f_int (x:int) = ()
49 | val f_int : int -> unit =
50 | ```
51 | * f\_int Generic param
52 | ```ocaml
53 | # let f_int (_:int) = ()
54 | val f_int : int -> unit =
55 | ```
56 | * A generic/polymorphic unit function
57 | ```ocaml
58 | # let unit _ = ()
59 | val unit : 'a -> unit =
60 | ```
61 | * Bool as ADT
62 | ```ocaml
63 | type bool = false | true
64 | ```
65 |
--------------------------------------------------------------------------------
/chapter2/dune:
--------------------------------------------------------------------------------
1 | (rule
2 | (with-stdout-to dune.gen
3 | (run ocaml-mdx rule --direction=to-ml README.md --prelude=prelude.ml)))
4 |
5 | (alias
6 | (name runtest)
7 | (deps README.md)
8 | (action (diff dune.inc dune.gen)))
9 |
10 | (include dune.inc)
--------------------------------------------------------------------------------
/chapter2/dune.inc:
--------------------------------------------------------------------------------
1 | (alias
2 | (name runtest)
3 | (deps (:x README.md)
4 | prelude.ml)
5 | (action (progn
6 | (run ocaml-mdx test --prelude=prelude.ml --direction=to-ml %{x})
7 | (diff? %{x} %{x}.corrected)
8 | )))
9 |
--------------------------------------------------------------------------------
/chapter2/prelude.ml:
--------------------------------------------------------------------------------
1 | #require "core,core.top,ppx_jane";;
2 |
3 | open Base
4 | open Core
5 |
6 | let () = Printexc.record_backtrace false
7 |
--------------------------------------------------------------------------------
/chapter20/README.md:
--------------------------------------------------------------------------------
1 | # Monads
2 | ## Utilities used by code below
3 | ```ocaml
4 | let ( <.> ) f g x = f (g x)
5 | let flip f x y = f y x
6 | type ('w, 'a) writer = Writer of ('a * 'w)
7 | module type Functor = sig
8 | type 'a t
9 | val fmap : ('a -> 'b) -> 'a t -> 'b t
10 | end
11 | module type Monoid = sig
12 | type a
13 | val mempty : a
14 | val mappend : a -> a -> a
15 | end
16 | let up_case = fun s -> Writer(String.uppercase_ascii s, "up_case ")
17 | ```
18 | ## Introduction
19 | ```ocaml
20 | (* Depends on OCaml library Base - #require "base" *)
21 | module Vlen(F : Functor with type 'a t = 'a list) = struct
22 |
23 | let summable = (module Float:Base.Container_intf.Summable with type t = float)
24 |
25 | let vlen = Float.sqrt <.> (List.sum summable ~f:Fn.id) <.> (F.fmap (flip Float.int_pow 2))
26 | end
27 | ```
28 | ## Kleisli Category
29 | - Writer's Functor Instance
30 | ```ocaml
31 | module WriterInstance (W : sig type w end) : Functor with type 'a t = (W.w, 'a) writer = struct
32 | type 'a t = (W.w, 'a) writer
33 | let fmap f (Writer (a, w)) = Writer (f a, w)
34 | end
35 | ```
36 | - Composing embellished functions
37 | ```OCaml
38 | 'a -> ('w, 'b) writer
39 | ```
40 | - Kleisli Category K has the same objects as C but its morphisms are different.
41 | - A morphism between a and b in K is implemented as a morphism a -> m b in C
42 | - Functor m that has a composition, which is associative, and has an identity arrow for every object, is called a monad
43 | ```ocaml
44 | module type Monad =
45 | sig
46 | type 'a m
47 | val ( >=> ) : ('a -> 'b m) -> ('b -> 'c m) -> 'a -> 'c m
48 | val return : 'a -> 'a m
49 | end
50 | ```
51 | - There are other ways of defining a monad
52 | - Monad is a way of composing embellished functions
53 | - Monad Instance for Writer
54 | ```ocaml
55 | module WriterMonad(W : Monoid): Monad with type 'a m = (W.a, 'a) writer = struct
56 | type 'a m = (W.a, 'a) writer
57 |
58 | let (>=>) f g = fun a ->
59 | let Writer (b, w) = f a in
60 | let Writer (c, w') = g b in
61 | Writer (c, W.mappend w w')
62 |
63 | let return a = Writer (a, W.mempty)
64 | end
65 | ```
66 | - Tell for Writer
67 | ```ocaml
68 | let tell w = Writer ((), w)
69 | ```
70 | ## Fish Anatomy
71 | - Step 1
72 | ```OCaml
73 | let (>=>) f g = fun a -> ...
74 | ```
75 | - Step 2
76 | ```OCaml
77 | let (>=>) f g = fun a ->
78 | let mb = f a in
79 | ...
80 | ```
81 | - Step 3
82 | ```OCaml
83 | val (>>=) : 'a m -> ('a -> 'b m) -> 'b m
84 | ```
85 | - Monad using bind
86 | ```ocaml
87 | module type Monad_Bind =
88 | sig
89 | type 'a m
90 | val ( >>= ) : 'a m -> ('a -> 'b m) -> 'b m
91 | val return : 'a -> 'a m
92 | end
93 | ```
94 | - Writer using bind
95 | ```ocaml
96 | module WriterMonadBind(W : Monoid) = struct
97 | let (>>=) (Writer (a, w)) f =
98 | let Writer (b, w') = f a in
99 | Writer (b, W.mappend w w')
100 | end
101 | ```
102 | - join in ocaml
103 | ```OCaml
104 | val join : ('a m) m -> 'a m
105 | ```
106 | - Rewrite bind as
107 | ```ocaml
108 | module BindUsingFunctionAndJoin(F : Functor) = struct
109 | type 'a m = 'a F.t
110 |
111 | (** Warning: The use of a compiler directive "%identity"
112 | here is only to make the type signature of
113 | join work without providing an implementation.
114 | This is only for the sake of the example and
115 | should **never** be relied upon. **)
116 | external join : 'a m m -> 'a m = "%identity"
117 |
118 | let (>>=) ma f = join (F.fmap f ma)
119 | end
120 | ```
121 | - Third option for defining a Monad
122 | ```ocaml
123 | module type Monad_Join = functor (F : Functor) -> sig
124 | type 'a m = 'a F.t
125 | val join : 'a m m -> 'a m
126 | val return : 'a -> 'a m
127 | end
128 | ```
129 | - fmap in terms of bind and return
130 | ```ocaml
131 | module Fmap_Using_Monad(M : Monad_Bind) = struct
132 | let fmap f ma = M.(>>=) ma (fun a -> M.return (f a))
133 | end
134 | ```
135 | - join for the Writer monad
136 | ```ocaml
137 | module Writer_Join(W : Monoid) = struct
138 | let join (Writer (Writer (a, w'), w)) = Writer (a, W.mappend w w')
139 | end
140 | ```
141 | ## do Notation
142 | - Writer example
143 | ```ocaml
144 | let to_words = fun s -> Writer (String.split_on_char ' ' s, "to_words")
145 |
146 | module Writer_Process(W : Monad with type 'a m = (string, 'a) writer) =
147 | struct
148 | let process = W.(up_case >=> to_words)
149 | end
150 | ```
151 | - OCaml do Notation
152 | ```ocaml
153 | module Process_Do(W : Monad_Bind with type 'a m = (string, 'a) writer) =
154 | struct
155 |
156 | (* Needs OCaml compiler >= 4.08 *)
157 | let (let*) = W.(>>=)
158 |
159 | let process s =
160 | let* up_str = up_case s in
161 | to_words up_str
162 | end
163 | ```
164 | - Upcase
165 | ```ocaml
166 | let up_case = fun s -> Writer(String.uppercase_ascii s, "up_case ")
167 | ```
168 | - Do block is
169 | ```ocaml
170 | module Process_Bind_Without_Do(W : Monad_Bind with type 'a m = (string, 'a) writer) =
171 | struct
172 | let process s = W.(up_case s >>= (fun up_str -> to_words up_str))
173 | end
174 | ```
175 | - Up Case
176 | ```OCaml
177 | let* up_str <- up_case s
178 | ```
179 | - Using teller towords
180 | ```ocaml
181 | module Process_Tell(W : Monad_Bind with type 'a m = (string, 'a) writer) =
182 | struct
183 | (* Needs OCaml compiler >= 4.08 *)
184 | let (let*) = W.(>>=)
185 |
186 | let tell w = Writer ((), w)
187 |
188 | let process s =
189 | let* up_str = up_case s in
190 | let* _ = tell "to_words " in
191 | to_words up_str
192 | end;;
193 | ```
194 | - With bind
195 | ```ocaml
196 | module Process_Bind_Without_Do(W : Monad_Bind with type 'a m = (string, 'a) writer) =
197 | struct
198 | let tell w = Writer((), w)
199 | let process s = W.(up_case s >>= (fun up_str ->
200 | tell "to_words" >>= (fun _ ->
201 | to_words up_str)))
202 | end;;
203 | ```
204 | - Special operator (>>)
205 | ```ocaml
206 | module Monad_Ops(M : Monad_Bind) = struct
207 | let (>>) m k = M.(m >>= (fun _ -> k))
208 | end
209 | ```
210 | - Process with special ops
211 | ```ocaml
212 | module Process_Bind_Without_Do(W : Monad_Bind with type 'a m = (string, 'a) writer) =
213 | struct
214 | open Monad_Ops(W)
215 | let tell w = Writer((), w)
216 | let process s = W.(up_case s >>= (fun up_str ->
217 | tell "to_words" >>
218 | to_words up_str))
219 | end
220 | ```
221 |
--------------------------------------------------------------------------------
/chapter20/dune:
--------------------------------------------------------------------------------
1 | (rule
2 | (with-stdout-to dune.gen
3 | (run ocaml-mdx rule --direction=to-ml README.md --prelude=prelude.ml)))
4 |
5 | (alias
6 | (name runtest)
7 | (deps README.md)
8 | (action (diff dune.inc dune.gen)))
9 |
10 | (include dune.inc)
--------------------------------------------------------------------------------
/chapter20/dune.inc:
--------------------------------------------------------------------------------
1 | (alias
2 | (name runtest)
3 | (deps
4 | (:x README.md)
5 | prelude.ml)
6 | (action
7 | (progn
8 | (run ocaml-mdx test --prelude=prelude.ml --direction=to-ml %{x})
9 | (diff? %{x} %{x}.corrected))))
10 |
--------------------------------------------------------------------------------
/chapter20/prelude.ml:
--------------------------------------------------------------------------------
1 | #require "core,core.top";;
2 | #require "str";;
3 |
4 | open Base
5 |
6 | let () = Printexc.record_backtrace false
7 |
--------------------------------------------------------------------------------
/chapter21/README.md:
--------------------------------------------------------------------------------
1 | # Monads and Effects
2 | ## Utilities used by code below
3 | ```ocaml
4 | let flip f x y = f y x
5 | let compose f g x = f (g x)
6 | module type Functor = sig
7 | type 'a t
8 | val fmap : ('a -> 'b) -> 'a t -> 'b t
9 | end
10 | module type MonadJoin = sig
11 | type 'a t
12 | include Functor with type 'a t := 'a t
13 | val join : 'a t t -> 'a t
14 | val return : 'a -> 'a t
15 | end
16 | module type MonadBind =
17 | sig
18 | type 'a m
19 | val ( >>= ) : 'a m -> ('a -> 'b m) -> 'b m
20 | val return : 'a -> 'a m
21 | end
22 | module type Monoid = sig
23 | type t
24 | val mempty : t
25 | val mappend : t -> t -> t
26 | end
27 | type 'a io = IO of (unit -> 'a)
28 | let put_str s = IO (fun () -> print_string s)
29 | ```
30 | ## Introduction
31 | - Partiality - may not terminate
32 | - Nondeterminism - return many results
33 | - Side effects - access/modify state
34 | - Exceptions - Partial functions
35 | - Continuations - ability to save state of the program and then restore it
36 | - Interactive input
37 | - Interactive output
38 | ## Partiality
39 | ```ocaml
40 | module ListMonad = functor (F : Functor with type 'a t = 'a list) -> (struct
41 | include F
42 | type 'a t = 'a F.t
43 | let join = List.concat
44 | let return a = [a]
45 | end : MonadJoin)
46 | ```
47 | - Bind using join and fmap
48 | ```ocaml
49 | module ListFunctor : Functor with type 'a t = 'a list = struct
50 | type 'a t = 'a list
51 | let fmap = List.map
52 | end
53 | module L = ListMonad(ListFunctor)
54 | let ( >>= ) xs k = L.(compose join (fmap k) xs)
55 | ```
56 | - Triples in OCaml
57 | ```ocaml
58 | (* This requires the "gen" library,
59 | after having installed them, execute
60 | #require "gen";; *)
61 |
62 | module Pythagorean = struct
63 |
64 | let (let*) = flip Gen.flat_map
65 |
66 | let (let+) x f = Gen.map f x
67 |
68 | let guard b = if b then Gen.return () else Gen.empty
69 |
70 | let triples =
71 | let* z = Gen.init (fun i -> i + 1) in
72 | let* x = Gen.init ~limit:z (fun i -> i + 1) in
73 | let* y = Gen.init ~limit:z (fun i -> i + x) in
74 | let+ _ = guard (x * x + y * y = z * z) in
75 | Gen.return (x, y, z)
76 | end
77 | ```
78 | - guard for List
79 | ```ocaml
80 | let guard = function
81 | | true -> [()]
82 | | false -> []
83 | ```
84 | - Triples alternate
85 | ```ocaml
86 | (* This requires the "gen" library,
87 | after having installed them, execute
88 | #require "gen";; *)
89 |
90 | module Pythagorean = struct
91 |
92 | let (let*) = flip Gen.flat_map
93 |
94 | let (let+) x f = Gen.map f x
95 |
96 | let guard b = if b then Gen.return () else Gen.empty
97 |
98 | let triples =
99 | let* z = Gen.init (fun i -> i + 1) in
100 | let* x = Gen.init ~limit:z (fun i -> i + 1) in
101 | let* y = Gen.init ~limit:z (fun i -> i + x) in
102 | if (x * x + y * y = z * z) then
103 | Gen.return (x, y, z) else Gen.empty
104 | end
105 | ```
106 | ### Reader
107 | - Reader type
108 | ```ocaml
109 | type ('e, 'a) reader = Reader of ('e -> 'a)
110 | ```
111 | - run_reader
112 | ```ocaml
113 | let run_reader (Reader f) e = f e
114 | ```
115 | - Bind implementation for reader
116 | ```OCaml
117 | let (>>=) ra k = Reader (fun e -> ...)
118 | ```
119 | ```OCaml
120 | let (>>=) ra k = Reader (fun e ->
121 | let a = run_reader ra e in
122 | ...)
123 | ```
124 | ```OCaml
125 | let (>>=) ra k = Reader (fun e ->
126 | let a = run_reader ra e in
127 | let rb = k a in
128 | ...)
129 | ```
130 | ```ocaml
131 | let (>>=) ra k = Reader (fun e ->
132 | let a = run_reader ra e in
133 | let rb = k a in
134 | run_reader rb e)
135 | ```
136 | ```ocaml
137 | module ReaderMonad(T : sig type t end) : MonadBind = struct
138 | type 'a m = (T.t, 'a) reader
139 | let return a = Reader (fun e -> a)
140 | let (>>=) ra k = Reader (fun e -> run_reader (k (run_reader ra e)) e)
141 | end
142 | ```
143 | ### Write Only State
144 | ```ocaml
145 | type ('w, 'a) writer = Writer of ('a * 'w);;
146 | ```
147 | ```ocaml
148 | let run_writer (Writer (a, w)) = (a, w)
149 | ```
150 | - Writer Instance
151 | ```ocaml
152 | module WriterMonad(W : Monoid):MonadBind = struct
153 | type 'a m = (W.t, 'a) writer
154 |
155 | let return a = Writer (a, W.mempty)
156 |
157 | let (>>=) (Writer (a, w)) k =
158 | let (a', w') = run_writer (k a) in
159 | Writer (a', W.mappend w w')
160 | end
161 | ```
162 | ### State
163 | - Combines Reader and Writer
164 | ```ocaml
165 | type ('s, 'a) state = State of ('s -> ('a * 's))
166 | ```
167 | - runstate
168 | ```ocaml
169 | let run_state (State f) s = f s
170 | ```
171 | - bind
172 | ```ocaml
173 | let (>>=) sa k = State (fun s ->
174 | let (a, s') = run_state sa s in
175 | let sb = k a in
176 | run_state sb s')
177 | ```
178 | - Monad Instance
179 | ```ocaml
180 | module StateMonad(S : sig type t end) : MonadBind = struct
181 |
182 | type 'a m = (S.t, 'a) state
183 |
184 | let (>>=) sa k = State (fun s ->
185 | let (a, s') = run_state sa s in
186 | let sb = k a in
187 | run_state sb s')
188 |
189 | let return a = State (fun s -> (a, s))
190 | end
191 | ```
192 | ```ocaml
193 | let get = State (fun s -> (s, s))
194 | ```
195 | ```ocaml
196 | let put s' = State (fun s -> ((), s'))
197 | ```
198 | ### Exceptions
199 | - Partial functions(throws exceptions) can be converted to total functions
200 | - Ex: Maybe, Either
201 | ```ocaml
202 | module OptionMonad : MonadBind = struct
203 | type 'a m = 'a option
204 |
205 | let (>>=) = function
206 | | Some a -> fun k -> k a
207 | | None -> fun _ -> None
208 |
209 | let return a = Some a
210 | end
211 | ```
212 | ### Continuations
213 | - Continuation type
214 | ```ocaml
215 | type ('r, 'a) cont = Cont of (('a -> 'r) -> 'r);;
216 | ```
217 | - runCont
218 | ```ocaml
219 | let run_cont (Cont k) h = k h
220 | ```
221 | - bind for Cont Monad
222 | ```OCaml
223 | val (>>=) : (('a -> 'r) -> 'r) -> ('a -> (('b -> 'r) -> 'r)) -> (('b -> 'r) -> 'r)
224 | ```
225 | - Step1
226 | ```OCaml
227 | let (>>=) ka kab = Cont (fun hb -> ...)
228 | ```
229 | - Step2
230 | ```OCaml
231 | run_cont ka (fun a -> ...)
232 | ```
233 | - Step3
234 | ```OCaml
235 | run_cont ka (fun a ->
236 | let kb = kab a in
237 | run_cont kb hb)
238 | ```
239 | - Monad Instance
240 | ```ocaml
241 | module ContMonad(R:sig type t end) : MonadBind = struct
242 | type 'a m = (R.t, 'a) cont
243 |
244 | let return a = Cont (fun ha -> ha a)
245 |
246 | let (>>=) ka kab = Cont (fun hb ->
247 | run_cont ka (fun a ->
248 | run_cont (kab a) hb))
249 | end
250 | ```
251 | ### Interactive Input
252 | ```ocaml
253 | module type TerminalIO = sig
254 | (* OCaml doesn't have a built-in IO type*)
255 | type 'a io = IO of (unit -> 'a)
256 |
257 | val get_char : unit -> char io
258 | end
259 | ```
260 | - main
261 | ```OCaml
262 | val main : unit io
263 | ```
264 | - As Kleisli arrow
265 | ```OCaml
266 | val main : unit -> unit io
267 | ```
268 | - IO as a State monad with RealWorld type
269 | ```OCaml
270 | type 'a io = realworld -> ('a * realworld)
271 | ```
272 | ```OCaml
273 | type 'a io = realworld state
274 | ```
275 | ### Interactive output
276 | ```OCaml
277 | val put_str : string -> unit io
278 | ```
279 | ```OCaml
280 | val put_str : string -> unit
281 | ```
282 | - Main function of type unit io
283 | ```ocaml
284 | (* Monad implementation for type io *)
285 | module IOMonad:MonadBind with type 'a m = 'a io = struct
286 | type 'a m = 'a io
287 | let return x = IO (fun () -> x)
288 | let (>>=) m f = IO (fun () ->
289 | let (IO m') = m in
290 | let (IO m'') = f (m' ()) in
291 | m'' ()
292 | )
293 | end
294 |
295 | (* main *)
296 | module IOMain = struct
297 |
298 | let (let*) = IOMonad.(>>=)
299 |
300 | let main =
301 | let* _ = put_str "Hello" in
302 | put_str "world!"
303 | end
304 | ```
305 |
--------------------------------------------------------------------------------
/chapter21/dune:
--------------------------------------------------------------------------------
1 | (rule
2 | (with-stdout-to dune.gen
3 | (run ocaml-mdx rule --direction=to-ml README.md --prelude=prelude.ml)))
4 |
5 | (alias
6 | (name runtest)
7 | (deps README.md)
8 | (action (diff dune.inc dune.gen)))
9 |
10 | (include dune.inc)
--------------------------------------------------------------------------------
/chapter21/dune.inc:
--------------------------------------------------------------------------------
1 | (alias
2 | (name runtest)
3 | (deps
4 | (:x README.md)
5 | prelude.ml)
6 | (action
7 | (progn
8 | (run ocaml-mdx test --prelude=prelude.ml --direction=to-ml %{x})
9 | (diff? %{x} %{x}.corrected))))
10 |
--------------------------------------------------------------------------------
/chapter21/prelude.ml:
--------------------------------------------------------------------------------
1 | #require "gen";;
2 |
3 | let () = Printexc.record_backtrace false
4 |
--------------------------------------------------------------------------------
/chapter22/README.md:
--------------------------------------------------------------------------------
1 | # Monads Categorically
2 | ## Utilities used by code below
3 | ```ocaml
4 | module type Functor = sig
5 | type 'a t
6 | val fmap : ('a -> 'b) -> 'a t -> 'b t
7 | end
8 | module type Representable = sig
9 | type rep (* Representing type 'a' *)
10 | type 'a t
11 | include Functor with type 'a t := 'a t
12 | val tabulate : (rep -> 'a) -> 'a t
13 | val index : 'a t -> (rep -> 'a)
14 | end
15 | module type MonadJoin = sig
16 | type 'a t
17 | include Functor with type 'a t := 'a t
18 | val join : 'a t t -> 'a t
19 | val return : 'a -> 'a t
20 | end
21 | module type Adjunction = sig
22 | type 'a f
23 | type 'a r
24 | include Functor with type 'a t = 'a f
25 | include Representable with type 'a t = 'a r
26 | val unit : 'a -> 'a f r
27 | val counit : 'a r f -> 'a
28 | end
29 | let (<.>) f g x = f (g x)
30 | let uncurry f (a, b) = f a b
31 | ```
32 | ## Introduction
33 | - In CT, a monad is an endofunctor T equipped with a pair of natural transformations mu and eta
34 | - mu is the NT from the square functor to T
35 | - mu :: T² -> T
36 | - muₐ :: T(Tₐ) -> Tₐ
37 | - eta is the NT between Identity functor I and T
38 | - eta :: I -> T
39 | - etaₐ :: a -> Tₐ
40 | - Kleisli arrow between a and b is a morphism a -> T b
41 | - Composition of two such arrows can be implemented using mu
42 | - f :: a -> T b
43 | - g :: b -> T c
44 | - Implementing composition of f and g using mu
45 | ```ocaml
46 | module Kleisli(M : MonadJoin) = struct
47 | (* compose *)
48 | let (<.>) f g x = f (g x)
49 |
50 | let (>=>) f g = M.join <.> M.fmap g <.> f
51 | end
52 | ```
53 | - In components
54 | ```ocaml
55 | module Kleisli(M : MonadJoin) = struct
56 |
57 | let (>=>) f g a = M.join (M.fmap g (f a))
58 | end
59 | ```
60 | - To make Kleisli arrows form a category, we want their composition to be associative and eta at a, to be the identity kleisli arrow at a
61 | - In terms of monoid laws
62 | - mu is multiplication
63 | - eta is unit
64 | - Monoidal categories
65 | ```ocaml
66 | module type Monoid = sig
67 | type m
68 | val mappend : m -> m -> m
69 | val mempty : m
70 | end
71 | ```
72 | - definition of mappend
73 | ```OCaml
74 | val mappend : m -> (m -> m)
75 | ```
76 | - Alternate definition of mappend
77 | ```OCaml
78 | val mu : (m, m) -> m
79 | ```
80 | - Alt definition of mempty
81 | ```OCaml
82 | val eta : unit -> m
83 | ```
84 | - Associativity in monoids
85 | ```OCaml
86 | mu (x, mu(y, z)) = mu (mu (x, y), z)
87 | ```
88 | - Towards point-free
89 | - LHS
90 | ```OCaml
91 | (compose mu (bimap id mu))(x, (y, z))
92 | ```
93 | - RHS
94 | ```OCaml
95 | (compose mu (bimap mu id))((x, y), z)
96 | ```
97 | - We want to be able to express function equality in point-free notation like this, but it isn't possible just yet
98 | ```OCaml
99 | compose mu (bimap id mu) = compose mu (bimap mu id)
100 | ```
101 | - Associator - establish Isomorphism between two pairs
102 | ```ocaml
103 | let alpha ((x, y), z) = (x, (y, z))
104 | ```
105 | - With the help of the associator, we can write this point-free
106 | ```OCaml
107 | compose mu (compose (bimap id mu) alpha) = compose mu (bimap mu id)
108 | ```
109 | - Moving unit laws to point-free notation. This is the unit law without point-free
110 | ```OCaml
111 | mu (eta (), x) = x
112 | mu (x, eta ()) = x
113 | ```
114 | - Using bimap
115 | ```OCaml
116 | (compose mu (bimap eta id))((), x) = lambda((), x)
117 | (compose mu (bimap id eta))(x, ()) = rho(x, ())
118 | ```
119 | - lambda - left unitor and rho - right unitor
120 | ```ocaml
121 | let lambda ((), x) = x
122 | ```
123 | ```ocaml
124 | let rho (x, ()) = x
125 | ```
126 | - Point free versions
127 | ```OCaml
128 | mu . bimap id eta = rho
129 | mu . bimap eta id = lambda
130 | ```
131 | - Associativity and unit laws for cartesian product are only valid upto isomorphism.
132 | - A monoidal category is a category C equipped with a bifunctor called the tensor product `tensor :: C x C -> C` and a distinct object i called the unit object together with three natural isomorphisms - associator, left and right unitors
133 | alpha_{abc} :: (a `tensor` b) `tensor` c -> a `tensor` (b `tensor` c)
134 | lambdaₐ :: i `tensor` a -> a
135 | rhoₐ :: a `tensor` i -> a
136 | ### Monoid in a Monoidal Category
137 | - Define monoid in monoidal category
138 | - object m
139 | - Use tensor product to form higher powers of m
140 | - To form a monoid:
141 | - U :: m `tensor` m
142 | - N :: i -> m
143 | - tensor product has to be a bifunctor
144 | ### Monads as Monoids
145 | - Monads are just monoids in the category of endofunctors
146 | ### Monads from Adjunctions
147 | - Adjunction is a pair of functors going back and forth between C and D
148 | - Endofunctors : compose R L and compose L R
149 | - L z = z x s
150 | - R b = s => b
151 | ```ocaml
152 | type ('s, 'a) state = State of ('s -> 'a * 's)
153 | ```
154 | ```ocaml
155 | type ('s, 'a) prod = Prod of 'a * 's
156 | ```
157 | ```ocaml
158 | type ('s, 'a) reader = Reader of ('s -> 'a)
159 | ```
160 | ```ocaml
161 | module AdjunctionState(S:sig type s end)(F:Functor with type 'a t = (S.s, 'a) prod)(R:Representable with type 'a t = (S.s, 'a) reader):Adjunction = struct
162 | type 'a f = (S.s, 'a) prod
163 | type 'a r = (S.s, 'a) reader
164 | include F
165 | include R
166 | let unit a = Reader (fun s -> Prod (a, s))
167 | let counit (Prod (Reader f, s)) = f s
168 | end
169 | ```
170 | - Composition of reader after product is the state functor
171 | ```ocaml
172 | type ('s, 'a) state = State of ('s -> 'a * 's)
173 | ```
174 | - Run_state
175 | ```ocaml
176 | let run_state (State f) s = f s
177 | ```
178 | - Definiing join
179 | ```OCaml
180 | val ssa : ('s, ('s, 'a) state) state
181 | val run_state ssa : 's -> (('s, 'a) state, 's)
182 | ```
183 | - join
184 | ```ocaml
185 | let join : ('s, ('s, 'a) state) state -> ('s, 'a) state = fun ssa ->
186 | State (uncurry run_state <.> run_state ssa)
187 | ```
188 | - Not every adjunction gives rise to a monad but every monad can be factorized into a composition of two adjoint functors
189 |
--------------------------------------------------------------------------------
/chapter22/dune:
--------------------------------------------------------------------------------
1 | (rule
2 | (with-stdout-to dune.gen
3 | (run ocaml-mdx rule --direction=to-ml README.md --prelude=prelude.ml)))
4 |
5 | (alias
6 | (name runtest)
7 | (deps README.md)
8 | (action (diff dune.inc dune.gen)))
9 |
10 | (include dune.inc)
--------------------------------------------------------------------------------
/chapter22/dune.inc:
--------------------------------------------------------------------------------
1 | (alias
2 | (name runtest)
3 | (deps
4 | (:x README.md)
5 | prelude.ml)
6 | (action
7 | (progn
8 | (run ocaml-mdx test --prelude=prelude.ml --direction=to-ml %{x})
9 | (diff? %{x} %{x}.corrected))))
10 |
--------------------------------------------------------------------------------
/chapter22/prelude.ml:
--------------------------------------------------------------------------------
1 | #require "core,core.top,ppx_jane";;
2 |
3 | open Base
4 |
5 | let () = Printexc.record_backtrace false
6 |
--------------------------------------------------------------------------------
/chapter23/README.md:
--------------------------------------------------------------------------------
1 | # Comonads
2 | ## Utilities used by code below
3 | ```ocaml
4 | module type Functor = sig
5 | type 'a t
6 | val fmap : ('a -> 'b) -> 'a t -> 'b t
7 | end
8 | let id a = a
9 | let compose f g x = f (g x)
10 | type ('s, 'a) prod = Prod of 'a * 's
11 | type ('s, 'a) reader = Reader of ('s -> 'a)
12 | ```
13 | ## Introduction
14 | - Monad - composing kleisli arrows
15 | ```OCaml
16 | 'a -> 'b m
17 | ```
18 | - Comonad
19 | ```OCaml
20 | 'a w -> 'b
21 | ```
22 | - CoKleisli arrow - analog of the fish operator
23 | ```ocaml
24 | module type CoKleisli = sig
25 | type 'a w
26 | val (=>=) : ('a w -> 'b) -> ('b w -> 'c) -> ('a w -> 'c)
27 | end
28 | ```
29 | - CoKleisli - identity arrow - dual of return
30 | ```OCaml
31 | val extract : 'a w -> 'a
32 | ```
33 | - Comonad type
34 | ```ocaml
35 | module type Comonad = sig
36 | type 'a w
37 | include Functor with type 'a t := 'a w
38 | val extract : 'a w -> 'a
39 | val (=>=) : ('a w -> 'b) -> ('b w -> 'c) -> ('a w -> 'c)
40 | end
41 | ```
42 | - Reader monad dissection
43 | ```OCaml
44 | 'a * 'e -> 'b
45 | ```
46 | - With currying
47 | ```OCaml
48 | 'a -> ('e -> 'b)
49 | ```
50 | - They already have the co-Kleisli arrows
51 | ```ocaml
52 | type ('e, 'a) product = P of 'e * 'a
53 | ```
54 | - Implementing composition for product
55 | ```ocaml
56 | let (=>=) f g = fun (P (e, a)) ->
57 | let b = f (P (e, a)) in
58 | let c = g (P (e, b)) in
59 | c
60 | ```
61 | - Implementing extract for product
62 | ```ocaml
63 | let extract (P (e, a)) = a
64 | ```
65 | - Product comonad can be used to perform exactly the same computations as the reader monad.
66 | - Reader functor is the right adjoint of the product functor
67 | ### Dissecting the composition
68 | ```OCaml
69 | module CoKleisliImpl = struct
70 | type 'a w
71 | let (=>=) : ('a w -> 'b) -> ('b w -> 'c) -> ('a w -> 'c) = fun f g ->
72 | g ...
73 | end
74 | ```
75 | - Dual of bind is extend
76 | ```OCaml
77 | val extend : ('a w -> 'b) -> 'a w -> 'b w
78 | ```
79 | - Implementing composition using extend
80 | ```ocaml
81 | module type CoKleisliExtend = sig
82 | type 'a w
83 | val extend : ('a w -> 'b) -> 'a w -> 'b w
84 | end
85 | module CoKleisliImpl(C : CoKleisliExtend) = struct
86 | type 'a w = 'a C.w
87 | let (=>=) : ('a w -> 'b) -> ('b w -> 'c) -> ('a w -> 'c) = fun f g ->
88 | compose g (C.extend f)
89 | end
90 | ```
91 | - Duplicate
92 | ```OCaml
93 | val duplicate : 'a w -> 'a w w
94 | ```
95 | - Three equivalent definitions of co-monad - Co-Kleisli arrows, extends or duplicate
96 | ```ocaml
97 | module type ComonadBase = sig
98 | type 'a w
99 | include Functor with type 'a t = 'a w
100 | val extract : 'a w -> 'a
101 | end
102 |
103 | module type ComonadDuplicate = sig
104 | type 'a w
105 | val duplicate : 'a w -> 'a w w
106 | end
107 |
108 | module type ComonadExtend = sig
109 | type 'a w
110 | val extend : ('a w -> 'b) -> 'a w -> 'b w
111 | end
112 |
113 | module type Comonad = sig
114 | type 'a w
115 | include ComonadBase with type 'a w := 'a w
116 | include ComonadExtend with type 'a w := 'a w
117 | include ComonadDuplicate with type 'a w := 'a w
118 | end
119 |
120 | (* Construct a full comonad instance using one of the following modules *)
121 | module ComonadImplViaExtend: functor(C:ComonadBase)(D:ComonadDuplicate with type 'a w = 'a C.w) -> Comonad with type 'a w = 'a C.w = functor(C:ComonadBase)(D:ComonadDuplicate with type 'a w = 'a C.w) -> struct
122 | include C
123 | include D
124 | let extend f wa = (C.fmap f) (D.duplicate wa)
125 | end
126 |
127 | module ComonadImplViaDuplicate: functor (C:ComonadBase)(E:ComonadExtend with type 'a w = 'a C.w) -> Comonad with type 'a w = 'a C.w = functor(C:ComonadBase)(E:ComonadExtend with type 'a w = 'a C.w) -> struct
128 | include C
129 | include E
130 | let duplicate (wa : 'a w):'a w w = E.extend id wa
131 | end
132 | ```
133 | ### Stream comonad
134 | ```ocaml
135 | type 'a stream = Cons of 'a * 'a stream Lazy.t;;
136 | ```
137 | - Functor instance
138 | ```ocaml
139 | module StreamFunctor : Functor with type 'a t = 'a stream = struct
140 | type 'a t = 'a stream
141 | let rec fmap f = function
142 | | Cons (x, xs) -> Cons (f x, Lazy.from_val (fmap f (Lazy.force xs)))
143 | end
144 | ```
145 | - Get the first element of stream - extract
146 | ```ocaml
147 | let extract (Cons (x, _)) = x
148 | ```
149 | - Duplicate produces stream of streams
150 | ```ocaml
151 | let rec duplicate (Cons (x, xs)) = Cons (Cons (x, xs), Lazy.from_val (duplicate (Lazy.force xs)))
152 | ```
153 | - Complete comonad instance
154 | ```ocaml
155 | (* Implement Extract *)
156 | module StreamComonadBase(F:Functor with type 'a t = 'a stream):ComonadBase with type 'a w = 'a stream = struct
157 | type 'a w = 'a stream
158 | include F
159 | let extract (Cons (x, _)) = x
160 | end
161 |
162 | (* Implement duplicate *)
163 | module StreamComonadDuplicate : ComonadDuplicate with type 'a w = 'a stream = struct
164 | type 'a w = 'a stream
165 | let rec duplicate (Cons (x, xs)) = Cons (Cons (x, xs), Lazy.from_val (duplicate (Lazy.force xs)))
166 | end
167 |
168 | (* Generate full Comonad Instance *)
169 | module StreamComonad : Comonad with type 'a w = 'a stream = ComonadImplViaExtend(StreamComonadBase(StreamFunctor))(StreamComonadDuplicate)
170 | ```
171 | - Analog of advance
172 | ```ocaml
173 | let tail (Cons (_, xs)) = Lazy.force xs
174 | ```
175 | - sum
176 | ```ocaml
177 | let rec sum_s n (Cons (x, xs)) =
178 | if n <= 0 then 0 else x + sum_s (n - 1) (Lazy.force xs)
179 | ```
180 | - average
181 | ```ocaml
182 | let average n stm = Float.(of_int (sum_s n stm) /. of_int n)
183 | ```
184 | - movingAverage
185 | ```ocaml
186 | let moving_average n = StreamComonad.extend (average n)
187 | ```
188 | ### Comonad Categorically
189 | - NT reversed for comonad. E : T -> I and D : T -> T^2
190 | - components of these transformations correspond to extract and duplicate
191 | - Monad can be derived from adjunction - R `compose` L - Monad
192 | - L `compose` R - Comonad
193 | - counit of the adjunction - E : L `compose` R -> I - extract
194 | - D : L `compose` R `compose` L `compose` R - duplicate
195 | - monad is a monoid
196 | - Is Comonad a `comonoid`
197 | - `monoid` - an object in the monoidal category
198 | - U : m * m -> m
199 | - N : i -> m
200 | - Comonoid - Reversing the above morphisms
201 | - D : m -> m * m
202 | - E : m -> i
203 | ```ocaml
204 | module type Comonoid = sig
205 | type m
206 | val split : m -> m * m
207 | val destroy : m -> unit
208 | end
209 | ```
210 | - destroy
211 | ```ocaml
212 | let destroy _ = ()
213 | ```
214 | - split
215 | ```OCaml
216 | let split x = (f x, g x)
217 | ```
218 | - Comonoid laws dual to monoid laws
219 | ```OCaml
220 | (* lambda is the left unitor and rho is the right unitor *)
221 | (* <.> is used as compose below *)
222 | lambda <.> (bimap destroy id) <.> split = id
223 | rho <.> (bimap id destroy) <.> split = id
224 | ```
225 | - Plugging in the definitions
226 | ```OCaml
227 | lambda (bimap destroy id (split x))
228 | = lambda (bimap destroy id (f x, g x))
229 | = lambda ((), g x)
230 | = g x
231 | ```
232 | - So we can conclude that g = id and f = id
233 | - split becomes
234 | ```ocaml
235 | let split x = (x, x)
236 | ```
237 | - Every object is a trivial comonoid
238 | - Monad is a monoid in the category of endofunctors
239 | - Comonad is a Comonoid in the category of endofunctors
240 | ### Store Comonad
241 | - Dual of a state monad - store comonad
242 | - L z = z * s
243 | - R a = s => a
244 | - For costate(Store) comonad
245 | - Comonad - L `compose` R
246 | - L (R a) = (s => a) * s
247 | - Prod as L and Reader as R
248 | ```ocaml
249 | type ('s, 'a) store = Store of (('s -> 'a) * 's)
250 | ```
251 | - counit of the adjunction Ea : ((s => a) * s) -> a
252 | ```ocaml
253 | let counit (Prod (Reader f, s)) = f s
254 | ```
255 | - extract function
256 | ```ocaml
257 | let extract (Store (f, s)) = f s
258 | ```
259 | - unit of adjunction
260 | ```ocaml
261 | let unit a = Reader (fun s -> Prod (a, s))
262 | ```
263 | - Partial construction of Store
264 | ```ocaml
265 | let make_store f = fun s -> Store (f, s)
266 | ```
267 | - duplicate - D : L `compose` R -> L `compose` R `compose` L `compose` R -> L `compose` Eta `compose` R
268 | ```ocaml
269 | let duplicate (Store (f, s)) = Store (make_store f, s)
270 | ```
271 | - complete defintion
272 | ```ocaml
273 | module StoreComonadBase(S: sig type s end)(F: Functor with type 'a t = (S.s, 'a) store):ComonadBase with type 'a w = (S.s, 'a) store = struct
274 | type 'a w = (S.s, 'a) store
275 | include F
276 | let extract (Store (f, s)) = f s
277 | end
278 |
279 | module StoreComonadDuplicate(S: sig type s end) : ComonadDuplicate with type 'a w = (S.s, 'a) store = struct
280 | type 'a w = (S.s, 'a) store
281 | let duplicate (Store (f, s)) = Store (make_store f, s)
282 | end
283 |
284 | (* Generate Full comonad *)
285 | module StoreComonad(S : sig type s end)(F:Functor with type 'a t = (S.s, 'a) store) : Comonad with type 'a w = (S.s, 'a) store = ComonadImplViaExtend(StoreComonadBase(S)(F))(StoreComonadDuplicate(S))
286 | ```
287 | - Reader of the store - generalized container of `a`s that are keyed using elements of type s
288 | - Second argument of the store - current position in the stream
289 | - duplicate - creates an infinite stream indexed by an element of type s
290 | - Basis for Lens
291 | ```OCaml
292 | 'a -> ('s, 'a) store
293 | ```
294 | - Equivalent to
295 | ```OCaml
296 | val get : 'a -> 's
297 | val set : 'a -> 's -> 'a
298 | ```
299 |
--------------------------------------------------------------------------------
/chapter23/dune:
--------------------------------------------------------------------------------
1 | (rule
2 | (with-stdout-to dune.gen
3 | (run ocaml-mdx rule --direction=to-ml README.md --prelude=prelude.ml)))
4 |
5 | (alias
6 | (name runtest)
7 | (deps README.md)
8 | (action (diff dune.inc dune.gen)))
9 |
10 | (include dune.inc)
--------------------------------------------------------------------------------
/chapter23/dune.inc:
--------------------------------------------------------------------------------
1 | (alias
2 | (name runtest)
3 | (deps
4 | (:x README.md)
5 | prelude.ml)
6 | (action
7 | (progn
8 | (run ocaml-mdx test --prelude=prelude.ml --direction=to-ml %{x})
9 | (diff? %{x} %{x}.corrected))))
10 |
--------------------------------------------------------------------------------
/chapter23/prelude.ml:
--------------------------------------------------------------------------------
1 | #require "core,core.top,ppx_jane";;
2 |
3 | open Base
4 |
5 | let () = Printexc.record_backtrace false
6 |
--------------------------------------------------------------------------------
/chapter24/README.md:
--------------------------------------------------------------------------------
1 | # F-Algebras
2 | ### Utilities used by code below
3 | ```ocaml
4 | module type Algebra = functor (F : sig type 'a f end) -> sig
5 | type 'a algebra = 'a F.f -> 'a
6 | end
7 | module Algebra : Algebra = functor (F : sig type 'a f end) -> struct
8 | type 'a algebra = 'a F.f -> 'a
9 | end
10 | module type Functor = sig
11 | type 'a t
12 | val fmap : ('a -> 'b) -> 'a t -> 'b t
13 | end
14 | ```
15 | ### Introduction
16 | - Monoid - set, single object category, object in monoidal category
17 | - F Algebra
18 | ```ocaml
19 | module type Algebra = functor(F : sig type 'a f end) -> sig
20 | type 'a algebra = 'a F.f -> 'a
21 | end
22 | ```
23 | - MonoidF functor
24 | ```ocaml
25 | type 'a mon_f = MEmpty | Mappend of ('a * 'a)
26 | ```
27 | - RingF functor
28 | ```ocaml
29 | type 'a ring_f = RZero
30 | | ROne
31 | | RAdd of ('a * 'a)
32 | | RMul of ('a * 'a)
33 | | RNeg of 'a
34 | ```
35 | - evalZ function
36 | ```ocaml
37 | module Ring = struct
38 |
39 | module RingAlg = Algebra(struct type 'a f = 'a ring_f end)
40 |
41 | let eval_z : 'a RingAlg.algebra = function
42 | | RZero -> 0
43 | | ROne -> 1
44 | | RAdd (m, n) -> m + n
45 | | RMul (m, n) -> m * n
46 | | RNeg n -> -n
47 | end
48 | ```
49 | - Recursion
50 | ```ocaml
51 | type expr =
52 | RZero
53 | | ROne
54 | | RAdd of (expr * expr)
55 | | RMul of (expr * expr)
56 | | RNeg of expr
57 | ```
58 | - Ring Evaluator with a recursive definition
59 | ```ocaml
60 | let rec eval_z : expr -> int = function
61 | | RZero -> 0
62 | | ROne -> 1
63 | | RAdd (e1, e2) -> eval_z e1 + eval_z e2
64 | | RMul (e1, e2) -> eval_z e1 * eval_z e2
65 | | RNeg e -> - eval_z e
66 | ```
67 | - Depth-one tree
68 | ```ocaml
69 | type 'a ring_f1 = ('a ring_f) ring_f
70 | ```
71 | - Depth two tree
72 | ```ocaml
73 | type 'a ring_f2 = (('a ring_f) ring_f) ring_f
74 | ```
75 | - D2 via D1
76 | ```ocaml
77 | type 'a ring_f2 = 'a ring_f ring_f1
78 | ```
79 | - Applying an endofunctor infinitely many times produces a fixed point
80 | ```ocaml
81 | module Fix(F : Functor) = struct
82 | type 'a fix = Fix of (('a fix) F.t)
83 | end
84 | ```
85 | - Constructor name - Fix is a convention
86 | ```ocaml
87 | module Fix(F : Functor) = struct
88 | type 'a fix = In of (('a fix) F.t)
89 | end
90 | ```
91 | - Fix as a function
92 | ```ocaml
93 | module Fix(F : Functor) = struct
94 | type 'a fix = Fix of (('a fix) F.t)
95 | let fix : 'a fix F.t -> 'a fix = fun f -> Fix f
96 | end
97 | ```
98 | - unfix
99 | ```ocaml
100 | module Fix(F : Functor) = struct
101 | type 'a fix = Fix of (('a fix) F.t)
102 | let unfix : 'a fix -> 'a fix F.t = fun (Fix f) -> f
103 | end
104 | ```
105 | ### Category of F-Algebras
106 | - F Algebras form a category
107 | - carrier object : a
108 | - morphism : f : F a -> a
109 | - Objects in that category are a pair (a, f)
110 | - Morphisms in the F-algebra category : (a, f) -> (b, g)
111 | - m: a -> b
112 | - Homomorphism of F-algebras
113 | - F m : F a -> F b
114 | - g : F b -> b
115 | - g compose F m = m compose f
116 | - Initial Algebra
117 | - carrier i
118 | - j :: F i -> i
119 | - Lambek's theorem : j is an isomorphism
120 | - There is a unique homomorphism m from initial object to any other F-algebra
121 | - j : F i -> i ; m : j -> i ; F m : F i -> F a ; f : F a -> a
122 | - A new algebra
123 | - Carrier : F i
124 | - morphism : F j : F (F i) -> F i
125 | - (i, j) is the initial algebra. Unique homomorphism 'm' must connect initial algebra (i, j) with (F i, F j)
126 | - j : F i -> i ; m : i -> F i ; F m : F i -> F (F i); F j : F (F i) -> F i
127 | - A new algebra
128 | - F j : F (F i) -> F i
129 | - j : F i -> i
130 | - j is a homomorphism of algebras (F i, F j) to (i, j)
131 | - j compose m is a homomorphism of two algebras (i, j) and (F i, F j)
132 | - i compose m = id_i
133 | - m compose j = id_Fi
134 | - i is the inverse of m and m is the inverse of j
135 | - j is an isomorphism between F i and i
136 | - j is the constructor Fix
137 | - i is the Fix f
138 | - m is the inverse unFix
139 | ### Natural Numbers
140 | - zero : 1 -> N ; succ : N -> N
141 | - 1 + N -> N
142 | - As functor
143 | ```ocaml
144 | type 'a nat_f = ZeroF | SuccF of 'a
145 | ```
146 | - Fixed point (Initial algebra)
147 | ```ocaml
148 | type nat = Zero | Succ of nat
149 | ```
150 | - Peano representation for natural numbers
151 | ### Catamorphisms
152 | - Initial algebra - Fix f
153 | - Evaluator is the constructor Fix
154 | - Unique morphism m : Initial algebra to any other algebra
155 | - Algebra : carrier a and evaluator is alg
156 | - Fix : f (Fix f) -> Fix f
157 | - m : Fix f -> a
158 | - fmap m (f (Fix f)) -> f a
159 | - alg : f a -> a
160 | - m is the evaluator of the fixed point
161 | - m evaluates the whole expression tree
162 | - m = alg . fmap m . unfix
163 | - cata in OCaml
164 | ```ocaml
165 | module Cata(F : Functor) = struct
166 | type 'a fix = Fix of 'a fix F.t
167 | let fix : 'a fix F.t -> 'a fix = fun f -> Fix f
168 | let unfix : 'a fix -> 'a fix F.t = fun (Fix f) -> f
169 | let rec cata : ('a F.t -> 'a) -> 'a fix -> 'a = fun alg fixf -> alg (F.fmap (cata alg) (unfix fixf))
170 | end
171 | ```
172 | - Functor for natural numbers
173 | ```ocaml
174 | type 'a nat_f = ZeroF | SuccF of 'a
175 | ```
176 | - Carrier Type : (int, int)
177 | - Algebra
178 | ```ocaml
179 | let rec fib = function
180 | | ZeroF -> (1, 1)
181 | | SuccF (m, n) -> (n, m + n)
182 | ```
183 | - Algebra for NatF defines the recurrence relation and the catmorphism just evaluates the n-th element of that sequence
184 | ### Folds
185 | ```ocaml
186 | type ('e, 'a) list_f = NilF | ConsF of ('e * 'a)
187 | ```
188 | - Replacing 'a with the result of recursion - 'e list
189 | ```ocaml
190 | type 'e list' = Nil | Cons of ('e * 'e list')
191 | ```
192 | - Algebra for a list functor picks a particular carrier type and defines a function that does pattern matching on the two constructors
193 | ```ocaml
194 | let len_alg = function
195 | | ConsF (e, n) -> n + 1
196 | | NilF -> 0
197 | ```
198 | - Traditional list length
199 | ```ocaml
200 | let length xs = List.fold_right (fun e n -> n + 1) xs 0
201 | ```
202 | - Two arguments to fold_r are the two components of the algebra
203 | ```ocaml
204 | let sum_alg = function
205 | | ConsF (e, s) -> e +. s
206 | | NilF -> 0.0
207 | ```
208 | - sum using foldr
209 | ```ocaml
210 | let sum xs = List.fold_right (fun e s -> e +. s) xs 0.0
211 | ```
212 | ### CoAlgebras
213 | - Direction of the morphism is reversed
214 | - a -> F a
215 | - Coalgebras for a given functor also form a category
216 | - Homomorphisms preserve the coalgebraic structure
217 | - The terminal object (t, u) is the final coalgebra
218 | - For every alg (a, f), there is a unique homomorphism m such that
219 | - u : t -> F t; m : a -> t; F m : F a -> F t; f : a -> F a
220 | - Terminal coalgebra is a fixed point of the functor
221 | - morphism : u : t -> F t is an isomorphism
222 | - Terminal coalgebra -> recipe for generating infinite data structures
223 | - Cata is used to evaluate initial algebra
224 | - Ana is used to evaluate final coalgebra
225 | ```ocaml
226 | module Ana(F:Functor) = struct
227 |
228 | type 'a fix = Fix of 'a fix F.t
229 |
230 | let rec ana : ('a -> 'a F.t) -> 'a -> 'a fix = fun coalg a -> Fix (F.fmap (ana coalg) (coalg a))
231 | end
232 | ```
233 | - Stream as an example
234 | ```ocaml
235 | type ('e, 'a) stream_f = StreamF of ('e * 'a)
236 |
237 | module Stream_Functor(E : sig type e end) : Functor with type 'a t = (E.e, 'a) stream_f = struct
238 | type 'a t = (E.e, 'a) stream_f
239 | let fmap f = function
240 | | StreamF (e, a) -> StreamF (e, f a)
241 | end
242 | ```
243 | - Fixed point
244 | ```ocaml
245 | type 'e stream = Stream of ('e * 'e stream)
246 | ```
247 | - Generating Sieve of eratosthenes
248 | ```ocaml
249 | (* OCaml library `gen` provides useful helpers for
250 | potentially infinite iterators. You can install it
251 | with `opam install gen`. To use it in the toplevel,
252 | you need to `#require "gen"` *)
253 | let era : int Gen.t -> (int, int Gen.t) stream_f =
254 | fun ilist ->
255 | let notdiv = fun p n -> (mod) n p != 0 in
256 | let p = Gen.get_exn ilist in
257 | StreamF (p, Gen.filter (notdiv p) ilist)
258 | ```
259 | - Primes
260 | ```ocaml
261 | module Stream_Int = Stream_Functor(struct type e = int end)
262 | module Ana_Stream = Ana(Stream_Int)
263 |
264 | (* The fixpoint translated to OCaml is eager in its evaluation.
265 | Hence, executing the following function will cause overflow.
266 | So, wrapping it inside a lazy *)
267 | let primes = lazy (Ana_Stream.ana era (Gen.init (fun i -> i + 2)))
268 | ```
269 | - to_list_c
270 | ```ocaml
271 | module List_C(E : sig type e end) = struct
272 | module Stream_F: Functor with type 'a t = (E.e, 'a) stream_f = Stream_Functor(E)
273 | module Cata_Stream = Cata(Stream_F)
274 |
275 | let to_list_c : E.e list Cata_Stream.fix -> E.e list =
276 | fun s_fix ->
277 | Cata_Stream.cata (fun (StreamF (e, a)) -> e :: a) s_fix
278 |
279 | end
280 | ```
281 | - Fixed point is the initial algebra and final coalgebra
282 | - Endofunctor may have many fixed points
283 | - Initial algebra is the least fixed point
284 | - Final Coalgebra is the greatest fixed point
285 | - unfold
286 | ```OCaml
287 | (* Gen.t is used to represent infinite data structures like haskell's lazy list *)
288 | val unfold : ('b -> ('a * 'b) option) -> 'b -> 'a Gen.t
289 | ```
290 | - A lens can be represented as a pair of getter and setter.
291 | - set
292 | ```OCaml
293 | val set : 'a -> 's -> 'a
294 | val get : 'a -> 's
295 | ```
296 | - a is a product type; s is the field type
297 | ```OCaml
298 | (a, (s, s -> a))
299 | ```
300 | ```OCaml
301 | 'a -> ('s, 'a) store
302 | ```
303 | - Functor
304 | ```ocaml
305 | (* Store is the comonad version of State *)
306 | type ('s, 'a) store = Store of ('s -> 'a) * 's
307 | ```
308 | - Lens is a coalgebra for functor with carrier type a
309 | - Lens is a coalgebra that is compatible with comonad structure
310 |
--------------------------------------------------------------------------------
/chapter24/dune:
--------------------------------------------------------------------------------
1 | (rule
2 | (with-stdout-to dune.gen
3 | (run ocaml-mdx rule --direction=to-ml README.md --prelude=prelude.ml)))
4 |
5 | (alias
6 | (name runtest)
7 | (deps README.md)
8 | (action (diff dune.inc dune.gen)))
9 |
10 | (include dune.inc)
--------------------------------------------------------------------------------
/chapter24/dune.inc:
--------------------------------------------------------------------------------
1 | (alias
2 | (name runtest)
3 | (deps
4 | (:x README.md)
5 | prelude.ml)
6 | (action
7 | (progn
8 | (run ocaml-mdx test --prelude=prelude.ml --direction=to-ml %{x})
9 | (diff? %{x} %{x}.corrected))))
10 |
--------------------------------------------------------------------------------
/chapter24/prelude.ml:
--------------------------------------------------------------------------------
1 | #require "gen";;
2 |
3 | let () = Printexc.record_backtrace false
4 |
--------------------------------------------------------------------------------
/chapter25/README.md:
--------------------------------------------------------------------------------
1 | # Algebra for monads
2 | ### Utilities used by code below
3 | ```ocaml
4 | let compose f g x = f (g x)
5 | let ( <.> ) = compose
6 | module type Functor = sig
7 | type 'a t
8 | val fmap : ('a -> 'b) -> 'a t -> 'b t
9 | end
10 | module type MonadJoin = sig
11 | type 'a t
12 | include Functor with type 'a t := 'a t
13 | val join : 'a t t -> 'a t
14 | val return : 'a -> 'a t
15 | end
16 | module type Comonad = sig
17 | type 'a w
18 | include Functor with type 'a t := 'a w
19 | val extract : 'a w -> 'a
20 | val duplicate : 'a w -> 'a w w
21 | end
22 | ```
23 | ### Introduction
24 | - Endofunctors - defines expressions
25 | - Algebras - Evaluate them
26 | - Monads - Allows us to form and manipulate expressions
27 | - Algebras + Monads
28 | - Relation between monads and adjunctions
29 | - Every adjunction defines a monad and a comonad
30 | - Monad is an endofunctor m equipped with two natural transformations that satisfy some coherence conditions
31 | - N_a : a -> m a
32 | - U_a : m (m a) -> m a
33 | - alg : m a -> a
34 | - First coherence condition
35 | - alg compose N_a = id_a
36 | - Second coherence condition
37 | - alg compose U_a = alg compose (m alg)
38 | ```OCaml
39 | compose alg return = id
40 | compose alg join = compose alg (fmap alg)
41 | ```
42 | - Algebra for a list endofunctor
43 | - type a
44 | - function that produces a from [a]
45 | - foldr can be used to express that algebra
46 | ```OCaml
47 | val fold_right : ('a -> 'b -> 'b) -> 'a list -> 'b -> 'b
48 | ```
49 | - List Algebra - foldr f z
50 | ```OCaml
51 | (* List module in the OCaml standard library accepts list before z *)
52 | List.fold_right f [x] z = f x z
53 | ```
54 | - List Algebra is compatible with the monad if
55 | ```OCaml
56 | f x z = x
57 | ```
58 | - z is the right unit
59 | ### T-algebras
60 | - T - Monads
61 | - Algebras compatible with monads - T algebras
62 | - T algebras for a Monad T in category C form a Eilenberg-Moore category C^T
63 | - Morphisms in that category are homomorphisms of algebras
64 | - Forgetful functor U^T from C^T to C ; maps (a, f) -> a
65 | - Maps homomorphism of T algebras to a corresponding morphism between carrier objects in C
66 | - Free functor(left adjoint to U^T) - F^T
67 | - maps an object a in C to C^T
68 | - Left adjoint functor aka Free functor (F^T) - goes from C to C^T
69 | - Right adjoint functor aka Forgetful functor (U^T) - goes from C^T to C
70 | - F^T maps object a in C to an Object(Free algebra) in C^T. This object is T a
71 | - morphisms in C^T are T (T a) -> T a
72 | - To show that the Free algebra is a T algebra
73 | - compose alg (N_a at T a) = id at T a
74 | - compose alg U_a = compose alg (T alg)
75 | - These are monadic laws
76 | - Every adjunction defines a monad
77 | - Adjunction between F^T and U^T also forms a monad and that monad is T.
78 | - T was used to construct C^T
79 | - Since we can form the category C^T for any monad and this category C^T forms a nice adjunction which leads to the formation of T monad, we can say that every monad can be formed from an adjunction
80 | - Adjunction between F^T and U^T
81 | - To prove: F^T is the left adjoint of U^T
82 | - unit and counit for this adjunction
83 | - Triangular identities are satisfied
84 | - Monad generated by this adjunction is the original monad T
85 | - unit of this adjunction
86 | - N :: I -> U^T `compose` F^T
87 | - Free functor -> Free algebra -> (T a, U_a)
88 | - Forgetful functor -> reduces the free algebra to T a
89 | - This is just a mapping from a to T a
90 | - unit of monad T provides this mapping
91 | - counit of this adjunction
92 | - E :: F^T `compose` U^T -> I
93 | - T-algebra (a, f)
94 | - Free algebra created bt F^T is (T a, U_a)
95 | - Forgetful functor F^T drops the evaluator
96 | - U^T `compose` F^T = T
97 | - counit of the adjunction produces monadic multiplication
98 | - U = R `compose` E `compose` L
99 | ### Kleisli Category
100 | - Kleisli category
101 | - Constructed from C and a monad T - C_T
102 | - Objects of C_T are objects of C but morphisms are different
103 | - f_K from a to b in C_T corresponds to a morphism f from a to T b in C
104 | - f_K is the kleisli arrow from a to b
105 | - Composition of morphisms in the Kleisli category is defined in terms of monadic composition of Kleisli arrows
106 | - In C_T
107 | - f_K : a -> b
108 | - g_K : b -> c
109 | - In C
110 | - f : a -> T b
111 | - g : b -> T c
112 | - Composition
113 | - h_K = g_K `compose` f_K
114 | - is a kleisli arrow in C
115 | - h : a -> T c
116 | - h = U `compose` T g `compose` f
117 | ```ocaml
118 | module Kleisli_Composition(T : MonadJoin) = struct
119 | let h g f = T.join <.> T.fmap g <.> f
120 | end
121 | ```
122 | - Functor F from C to C_T
123 | ```OCaml
124 | module C_to_CT(T : Monad) = struct
125 | let on_objects = T.return <.> f
126 | end
127 | ```
128 | - Functor G from C_T to C
129 | - on_objects : a -> T a
130 | - on_morphisms : f_K which corresponds to f : a -> T b in C
131 | - It produces a morphism T a -> T b in C
132 | - U at T b `compose` T f (Takes T a and produces T b)
133 | - Two functors F and G form an adjunction
134 | - G `compose` F forms the monad T
135 | - THere is a whole category of adjunctions Adj(C, T) that result in monad T on C
136 | - Kleisli adjunction is the initial object in this category
137 | - EM adjunction is the terminal object in this category
138 | ### Coalgebras for Comonads
139 | - coa : a -> W a
140 | - E(extract) and D(duplicate) are the nat trans defining comonad.
141 | ### Lenses
142 | - A lens can be written as a coalgebra
143 | - coalg_s :: a -> ('s, 'a) store
144 | ```ocaml
145 | type ('s, 'a) store = Store of ('s -> 'a) * 's
146 | ```
147 | - Coalgebra as a pair of functions
148 | - set : 'a -> 's -> 'a
149 | - get : 'a -> 's
150 | - coalg_s a = Store ((set a), (get a))
151 | - Store is a comonad
152 | ```ocaml
153 | module Store_comonad(S: sig type s end)(F : Functor with type 'a t = (S.s, 'a) store) : Comonad with type 'a w = (S.s, 'a) store = struct
154 | type 'a w = (S.s, 'a) store
155 | include F
156 | let extract : 'a w -> 'a = fun (Store (f, s)) -> f s
157 | let duplicate : 'a w -> ('a w) w = fun (Store (f, s)) -> Store ((fun s -> Store (f, s)), s)
158 | end
159 | ```
160 | - When is a lens a coalgebra?
161 | ```ocaml
162 | module Store_Functor(S : sig type s end) : Functor with type 'a t = (S.s, 'a) store = struct
163 | type 'a w = (S.s, 'a) store
164 | type 'a t = 'a w
165 |
166 | let fmap g (Store (f, s)) = Store ((compose g f), s)
167 | end
168 | ```
169 | - coalg_s a = Store ((set a), (get a))
170 | - fmap coalg to result of coalg
171 | ```OCaml
172 | (* Assume <.> acts as compose *)
173 | Store ((coalg_store <.> set a), (get a))
174 | ```
175 | - Applying duplicate to result of coalg
176 | ```OCaml
177 | Store ((fun s -> Store (set a, s)), (get a))
178 | ```
179 | - Coalg must be equal to arbitrary s
180 | ```OCaml
181 | (* Pseudo OCaml *)
182 | let coalg_store (set a s) = Store ((set a), s)
183 | ```
184 | - Expaning coalg
185 | ```OCaml
186 | (* Expaning coalg_store *)
187 | Store ((set (set a s)), (get (set a s))) = Store ((set a), s)
188 | ```
189 | - Using the lens laws#1
190 | ```OCaml
191 | set (set a s) = set a
192 | ```
193 | - Using lens law#2
194 | ```OCaml
195 | get (set a s) = s
196 | ```
197 | - A well-behaved lens is a comonad coalgebra for the Store functor
198 |
--------------------------------------------------------------------------------
/chapter25/dune:
--------------------------------------------------------------------------------
1 | (rule
2 | (with-stdout-to dune.gen
3 | (run ocaml-mdx rule --direction=to-ml README.md --prelude=prelude.ml)))
4 |
5 | (alias
6 | (name runtest)
7 | (deps README.md)
8 | (action (diff dune.inc dune.gen)))
9 |
10 | (include dune.inc)
--------------------------------------------------------------------------------
/chapter25/dune.inc:
--------------------------------------------------------------------------------
1 | (alias
2 | (name runtest)
3 | (deps
4 | (:x README.md)
5 | prelude.ml)
6 | (action
7 | (progn
8 | (run ocaml-mdx test --prelude=prelude.ml --direction=to-ml %{x})
9 | (diff? %{x} %{x}.corrected))))
10 |
--------------------------------------------------------------------------------
/chapter25/prelude.ml:
--------------------------------------------------------------------------------
1 | #require "gen";;
2 |
3 | let () = Printexc.record_backtrace false
4 |
--------------------------------------------------------------------------------
/chapter26/README.md:
--------------------------------------------------------------------------------
1 | # Ends and Coends
2 | ### Utilities used by code below
3 | ### Introduction
4 | - Morphism : a -> b
5 | - a and b are related
6 | - Existence of the morphism is a proof of this relation
7 | - poset category
8 | - morphism is a relation
9 | - There may be mant proofs of the same relation between two objects
10 | - These proofs form a set called hom-set
11 | - Vary the objects, we get a mapping from pairs of objects to sets of "proofs"
12 | - Hom Functor : C(-, =) :: C^op x C -> Set
13 | - A relation may also involve two different categories C and D
14 | - p :: D^op x C -> Set
15 | - A profunctor from C to D
16 | ```ocaml
17 | module type Functor = sig
18 | type 'a t
19 | val fmap : ('a -> 'b) -> 'a t -> 'b t
20 | end
21 | module type Profunctor = sig
22 | type ('a,'b) p
23 | val dimap : ('c -> 'a) -> ('b -> 'd) -> ('a, 'b) p -> ('c, 'd) p
24 | end
25 | let id a = a
26 | ```
27 | - Functoriality of the profunctor tells us that if we have a proof that a is related to b then we get the proof that c is related to d
28 | - as long as there is a morphism from c to a
29 | - another from b to d
30 | ```OCaml
31 | let dimap f id (P (b, b)) : ('a, 'b) p
32 | ```
33 | - p (a, a) to p (a, b)
34 | ```OCaml
35 | let dimap id f (P (a, a)) : ('a, 'b) p
36 | ```
37 | ### Dinatural transformations
38 | - Profunctors are functors.
39 | - NT between them in the standard way
40 | - Dinatural transformation between two profunctor p and q which are members of the functor category [C^op x C, Set] is a family of morphisms
41 | - f : a -> b
42 | - alpha_a : p a a -> q a a
43 | - p b a -> p f id_a -> p a a
44 | - p b a -> p id_b f -> p b b
45 | - p a a -> alpha_a -> q a a
46 | - p b b -> alpha_a -> q b b
47 | - q a a -> q id_a f -> q a b
48 | - q b b -> q f id_b -> q a b
49 | - This commuting condition is strictly weaker than naturality condition
50 | - Natural transformation alpha in [C^op x C, Set] is indexed by a pair of objects
51 | - Dinatural transformation is indexed by only one object
52 | ### Ends
53 | - Calculus of category theory
54 | - Calculus of ends and coends borrows ideas and notation from calculus
55 | - coend - infinite sum or integral
56 | - end - infinite product
57 | - End is the generalization of a limit
58 | ```OCaml
59 | (* There is no compose operator in OCaml *)
60 | compose (dimap id f) (alpha) = compose (dimap f id) alpha
61 | ```
62 | - End formula
63 | ```OCaml
64 | 'a. ('a, 'a) p
65 | ```
66 | - Wedge condition
67 | ```OCaml
68 | compose (dimap f id) pi = compose (dimap id f) pi
69 | ```
70 | - Profunctor requirement
71 | ```ocaml
72 | module type Polymorphic_Projection = functor(P : Profunctor) -> sig
73 | type rank2_p = { p : 'c. ('c, 'c) P.p }
74 | val pi : rank2_p -> ('a, 'b) P.p
75 | end
76 | ```
77 | - pi is the polymorphic projection
78 | ```ocaml
79 | module Pi(P : Profunctor) = struct
80 | type rank2_p = { p : 'a. ('a, 'a) P.p }
81 | let pi : rank2_p -> ('c, 'c) P.p = fun e -> e.p
82 | end
83 | ```
84 | - Generalization of a constant functor to a constant profunctor
85 | - maps all pairs of objects to a single object c
86 | - maps all pairs of morphisms to identity morphism
87 | - A wedge is a dinatural transformation from that functor to the profunctor p
88 | - Dinatural hexagon to wedge diamond
89 | ### Ends as Equalizers
90 | - Commutation conditions as equalizer.
91 | ```ocaml
92 | module EndsEqualizer(P : Profunctor) = struct
93 | let lambda : ('a, 'a) P.p -> ('a -> 'b) -> ('a, 'b) P.p = fun paa f -> P.dimap id f paa
94 | let rho : ('b, 'b) P.p -> ('a -> 'b) -> ('a, 'b) P.p = fun pbb f -> P.dimap f id pbb
95 | end
96 | ```
97 | - prod p
98 | ```ocaml
99 | module type ProdP = sig
100 | type ('a, 'b) p
101 | type ('a, 'b) prod_p = ('a -> 'b) -> ('a, 'b) p
102 | end
103 | ```
104 | - diaprod
105 | ```ocaml
106 | module type DiaProd = sig
107 | type ('a, 'b) p
108 | type 'a diaprod = DiaProd of ('a, 'a) p
109 | end
110 | ```
111 | - mappings from this prod
112 | ```ocaml
113 | module EndsWithDiaProd(P : Profunctor)(D : DiaProd with type ('a, 'b) p = ('a, 'b) P.p)(PP : ProdP with type ('a, 'b) p = ('a, 'b) P.p) = struct
114 | module E = EndsEqualizer(P)
115 | let lambdaP : 'a D.diaprod -> ('a, 'b) PP.prod_p = fun (DiaProd paa) -> E.lambda paa
116 | let rhoP : 'b D.diaprod -> ('a, 'b) PP.prod_p = fun (DiaProd pbb) -> E.rho pbb
117 | end
118 | ```
119 | ### Natural Transformations as Ends
120 | ```ocaml
121 | (* Higher rank types can be introduced via records *)
122 | module NT_as_Ends(F : Functor)(G : Functor) = struct
123 | type set_of_nt = { nt : 'a. 'a F.t -> 'a G.t}
124 | end
125 | ```
126 | - Naturality follows from parametricity
127 | - Coend
128 | ```ocaml
129 | module Coend(P : Profunctor) = struct
130 | type coend = Coend of {c : 'a. ('a, 'a) P.p }
131 | end
132 | ```
133 | - Coequalizer
134 | - cowedge conditions can be summarized
135 | ```ocaml
136 | module type SumP = sig
137 | type a
138 | type b
139 | type ('a, 'b) p
140 | val f : b -> a
141 | val pab : (a, b) p
142 | end
143 | ```
144 | ```ocaml
145 | module type DiagSum = sig
146 | type a
147 | type ('a, 'b) p
148 | val paa : (a, a) p
149 | end
150 |
151 | module CoEndImpl(P : Profunctor) = struct
152 | type a
153 | type b
154 | module type Sum_P = SumP with type ('a, 'b) p = ('a, 'b) P.p and type a = a and type b = b
155 | let lambda (module S : Sum_P) =
156 | (module struct type a = S.b type ('a, 'b) p = ('a, 'b) P.p let paa = P.dimap S.f id S.pab end : DiagSum)
157 | let rho (module S : Sum_P) =
158 | (module struct type a = S.a type ('a, 'b) p = ('a, 'b) P.p let paa = P.dimap id S.f S.pab end : DiagSum)
159 | end
160 | ```
161 | - DiagSum
162 | ```ocaml
163 | module type DiagSum = sig
164 | type a
165 | type ('a, 'b) p
166 | val paa : (a, a) p
167 | end
168 | ```
169 | - Profunctor Composition
170 | ```ocaml
171 | module type Procompose = sig
172 | type ('a, 'b) p
173 | type ('a, 'b) q
174 | type (_, _) procompose =
175 | | Procompose : (('a, 'c) q -> ('c, 'b) p) -> ('a, 'b) procompose
176 | end
177 | ```
178 |
--------------------------------------------------------------------------------
/chapter26/dune:
--------------------------------------------------------------------------------
1 | (rule
2 | (with-stdout-to dune.gen
3 | (run ocaml-mdx rule --direction=to-ml README.md --prelude=prelude.ml)))
4 |
5 | (alias
6 | (name runtest)
7 | (deps README.md)
8 | (action (diff dune.inc dune.gen)))
9 |
10 | (include dune.inc)
--------------------------------------------------------------------------------
/chapter26/dune.inc:
--------------------------------------------------------------------------------
1 | (alias
2 | (name runtest)
3 | (deps
4 | (:x README.md)
5 | prelude.ml)
6 | (action
7 | (progn
8 | (run ocaml-mdx test --prelude=prelude.ml --direction=to-ml %{x})
9 | (diff? %{x} %{x}.corrected))))
10 |
--------------------------------------------------------------------------------
/chapter26/prelude.ml:
--------------------------------------------------------------------------------
1 | #require "gen";;
2 |
3 | let () = Printexc.record_backtrace false
4 |
--------------------------------------------------------------------------------
/chapter27/README.md:
--------------------------------------------------------------------------------
1 | # Kan Extensions
2 | ### Utilities used by code below
3 | ```ocaml
4 | module type Functor = sig
5 | type 'a t
6 | val fmap : ('a -> 'b) -> 'a t -> 'b t
7 | end
8 | module type Monoid = sig
9 | type m
10 | val mempty : m
11 | val mappend : m -> m -> m
12 | end
13 | module ListMonoid(T1 : sig type a end) : (Monoid with type m = T1.a list) = struct
14 | type m = T1.a list
15 | let mempty = []
16 | let mappend xs ys = List.append xs ys
17 | end
18 | ```
19 | ### Kan
20 | ```ocaml
21 | module type Ran = sig
22 | type 'a k
23 | type 'a d
24 | type 'a ran = Ran of { r : 'i. ('a -> 'i k) -> 'i d }
25 | end
26 | ```
27 | ```OCaml
28 | val f : string -> int tree
29 | ```
30 | ```OCaml
31 | (* Higher rank polymorphic functions can be achieved using records *)
32 | { r : 'i. (a -> 'i k) -> 'i }
33 | ```
34 | ```ocaml
35 | module type Lst = sig
36 | type a
37 | type m
38 | module M : Monoid with type m = m
39 | type lst = (a -> M.m) -> M.m
40 | val f : lst
41 | end
42 | ```
43 | ```ocaml
44 | let fold_map (type i) (module M : Monoid with type m = i) xs f = List.fold_left (fun acc -> fun a -> M.mappend acc (f a)) M.mempty xs
45 |
46 | let to_lst (type x) (xs : x list) =
47 | let module LM : Monoid with type m = x list = ListMonoid(struct type a = x end) in
48 | (module struct
49 | type a = x
50 | type m = x list
51 | module M = LM
52 | type lst = (a -> LM.m) -> LM.m
53 | let f = fun g -> fold_map (module LM) xs g
54 | end : Lst with type a = x)
55 |
56 | let from_lst (type x) (module LstImpl : Lst with type a = x and type m = x list) =
57 | LstImpl.f (fun x -> [x])
58 | ```
59 | ```ocaml
60 | module type Lan = sig
61 | type 'a k
62 | type 'a d
63 | type a
64 | type i
65 | val fk : i k -> a
66 | val di : i d
67 | end
68 | ```
69 | ```ocaml
70 | module type Exp = sig
71 | type a
72 | type b
73 | type 'a d = I of 'a
74 | type 'a k = ('a * a)
75 | include Lan with type 'a k := a * 'a and type 'a d := 'a d and type a := b
76 | end
77 | ```
78 | ```ocaml
79 | let to_exp (type a') (type b') = fun f ->
80 | (module struct
81 | type a = a'
82 | type b = b'
83 | type 'a d = I of 'a
84 | type 'a k = ('a * a)
85 | type i = unit
86 | let fk = fun (a, _) -> f a
87 | let di = I ()
88 | end : Exp with type a = a' and type b = b')
89 |
90 | let from_exp (type a') (type b') (module E : Exp with type a = a' and type b = b') = fun a ->
91 | let (I i) = E.di in
92 | E.fk (a, i)
93 | ```
94 | ### Free Functor
95 | ```ocaml
96 | module type FreeF = sig
97 | type 'a f
98 | type a
99 | type i
100 | val h : i -> a
101 | val fi : i -> i f
102 | end
103 | ```
104 | ```ocaml
105 | module FreeFunctor(F : sig type 'a f end) : Functor = struct
106 | module type F = FreeF with type 'a f = 'a F.f
107 | type 'a t = (module F with type a = 'a)
108 |
109 | let fmap (type a') (type b') (f : a' -> b') = fun (module FF : F with type a = a') -> (module struct
110 | type 'a f = 'a F.f
111 | type a = b'
112 | type i = FF.i
113 | let h = fun i -> f (FF.h i)
114 | let fi = FF.fi
115 | end : F with type a = b')
116 |
117 | end
118 | ```
119 | ```ocaml
120 | module type FreeF_Alt = sig
121 | type a
122 | type 'a f
123 | val freeF : (a -> 'i) -> 'i f
124 | end
125 | ```
126 | ```ocaml
127 | module FreeFunctorAlt(F : sig type 'a f end) : Functor = struct
128 | module type F = FreeF_Alt with type 'a f = 'a F.f
129 | type 'a t = (module F with type a = 'a)
130 |
131 | let fmap (type a') (type b') f = fun (module FF : F with type a = a') ->
132 | (module struct
133 | type a = b'
134 | type 'a f = 'a F.f
135 | let freeF = fun bi ->
136 | FF.freeF (fun a -> bi (f a))
137 | end : F with type a = b')
138 | end
139 | ```
140 |
--------------------------------------------------------------------------------
/chapter27/dune:
--------------------------------------------------------------------------------
1 | (rule
2 | (with-stdout-to dune.gen
3 | (run ocaml-mdx rule --direction=to-ml README.md --prelude=prelude.ml)))
4 |
5 | (alias
6 | (name runtest)
7 | (deps README.md)
8 | (action (diff dune.inc dune.gen)))
9 |
10 | (include dune.inc)
--------------------------------------------------------------------------------
/chapter27/dune.inc:
--------------------------------------------------------------------------------
1 | (alias
2 | (name runtest)
3 | (deps
4 | (:x README.md)
5 | prelude.ml)
6 | (action
7 | (progn
8 | (run ocaml-mdx test --prelude=prelude.ml --direction=to-ml %{x})
9 | (diff? %{x} %{x}.corrected))))
10 |
--------------------------------------------------------------------------------
/chapter27/prelude.ml:
--------------------------------------------------------------------------------
1 | #require "gen";;
2 |
3 | let () = Printexc.record_backtrace false
4 |
--------------------------------------------------------------------------------
/chapter3/README.md:
--------------------------------------------------------------------------------
1 | # Categories Great and Small
2 | ## No Objects
3 | * Categories with no objects
4 | * No morphisms
5 | ### Monoid
6 | * Definition
7 | 1. Requires the operation to be associative.
8 | 2. There must be a special element that behaves like a unit.
9 | ```ocaml
10 | module type Monoid = sig
11 | type a
12 | val mempty : a
13 | val mappend : a -> a -> a
14 | end
15 | ```
16 | * String Instance of Monoid
17 | ```ocaml
18 | module StringMonoid:Monoid = struct
19 | type a = string
20 | let mempty = ""
21 | let mappend = (^)
22 | end
23 | ```
24 | * Function equality without specifying its arguments is described as "point-free".
25 | ### Monoid as Category
26 | * Monoid is a single object category.
27 |
--------------------------------------------------------------------------------
/chapter3/dune:
--------------------------------------------------------------------------------
1 | (rule
2 | (with-stdout-to dune.gen
3 | (run ocaml-mdx rule --direction=to-ml README.md --prelude=prelude.ml)))
4 |
5 | (alias
6 | (name runtest)
7 | (deps README.md)
8 | (action (diff dune.inc dune.gen)))
9 |
10 | (include dune.inc)
--------------------------------------------------------------------------------
/chapter3/dune.inc:
--------------------------------------------------------------------------------
1 | (alias
2 | (name runtest)
3 | (deps (:x README.md)
4 | prelude.ml)
5 | (action (progn
6 | (run ocaml-mdx test --prelude=prelude.ml --direction=to-ml %{x})
7 | (diff? %{x} %{x}.corrected)
8 | )))
9 |
--------------------------------------------------------------------------------
/chapter3/prelude.ml:
--------------------------------------------------------------------------------
1 | #require "core,core.top,ppx_jane";;
2 |
3 | open Base
4 |
5 | let () = Printexc.record_backtrace false
6 |
--------------------------------------------------------------------------------
/chapter30/README.md:
--------------------------------------------------------------------------------
1 | # Lawvere Theories
2 | ```ocaml
3 | type ('a, 'b) either = Left of 'a | Right of 'b
4 | type two = (unit, unit) either
5 | ```
6 | ```OCaml
7 | val raise : unit -> 'a
8 | ```
9 | ```ocaml
10 | type 'a option = (unit, 'a) either
11 | ```
12 | ```ocaml
13 | type 'a option = None | Some of 'a
14 | ```
15 |
--------------------------------------------------------------------------------
/chapter30/dune:
--------------------------------------------------------------------------------
1 | (rule
2 | (with-stdout-to dune.gen
3 | (run ocaml-mdx rule --direction=to-ml README.md --prelude=prelude.ml)))
4 |
5 | (alias
6 | (name runtest)
7 | (deps README.md)
8 | (action (diff dune.inc dune.gen)))
9 |
10 | (include dune.inc)
--------------------------------------------------------------------------------
/chapter30/dune.inc:
--------------------------------------------------------------------------------
1 | (alias
2 | (name runtest)
3 | (deps
4 | (:x README.md)
5 | prelude.ml)
6 | (action
7 | (progn
8 | (run ocaml-mdx test --prelude=prelude.ml --direction=to-ml %{x})
9 | (diff? %{x} %{x}.corrected))))
10 |
--------------------------------------------------------------------------------
/chapter30/prelude.ml:
--------------------------------------------------------------------------------
1 | #require "gen";;
2 |
3 | let () = Printexc.record_backtrace false
4 |
--------------------------------------------------------------------------------
/chapter4/README.md:
--------------------------------------------------------------------------------
1 | # Kleisli Categories
2 | ### Writer in Haskell
3 | ```ocaml
4 | type 'a writer = 'a * string
5 | ```
6 | * Morphisms from an arbitrary type to Writer type
7 | ```OCaml
8 | 'a -> 'b writer
9 | ```
10 | * Kleisli for Writer
11 | ```ocaml
12 | module type Kleisli =
13 | sig
14 | type a
15 | type b
16 | type c
17 | val ( >=> ) : (a -> b writer) -> (b -> c writer) -> a -> c writer
18 | end
19 | ```
20 | * Pure for Writer
21 | ```ocaml
22 | # let pure x = (x, "");;
23 | val pure : 'a -> 'a * string =
24 | ```
25 | * upCase for Writer
26 | ```ocaml
27 | # let up_case : (string -> string writer) = fun s -> (String.uppercase s, "up_case ")
28 | val up_case : string -> string writer =
29 | ```
30 | * toWords for Writer
31 | ```ocaml
32 | # let to_words : (string -> string list writer) = fun s -> (String.split s ~on:' ', "to_words ")
33 | val to_words : string -> string list writer =
34 | ```
35 | * Example Kleisli application
36 | ```ocaml
37 | module KleisiExample(K : Kleisli with type a = string and type b = string and type c = string list) = struct
38 | let up_case_and_to_words : string -> string list writer = K.(>=>) up_case to_words
39 | end
40 | ```
41 |
--------------------------------------------------------------------------------
/chapter4/dune:
--------------------------------------------------------------------------------
1 | (rule
2 | (with-stdout-to dune.gen
3 | (run ocaml-mdx rule --direction=to-ml README.md --prelude=prelude.ml)))
4 |
5 | (alias
6 | (name runtest)
7 | (deps README.md)
8 | (action (diff dune.inc dune.gen)))
9 |
10 | (include dune.inc)
--------------------------------------------------------------------------------
/chapter4/dune.inc:
--------------------------------------------------------------------------------
1 | (alias
2 | (name runtest)
3 | (deps (:x README.md)
4 | prelude.ml)
5 | (action (progn
6 | (run ocaml-mdx test --prelude=prelude.ml --direction=to-ml %{x})
7 | (diff? %{x} %{x}.corrected)
8 | )))
9 |
--------------------------------------------------------------------------------
/chapter4/prelude.ml:
--------------------------------------------------------------------------------
1 | #require "core,core.top,ppx_jane";;
2 |
3 | open Base
4 |
5 | let () = Printexc.record_backtrace false
6 |
--------------------------------------------------------------------------------
/chapter5/README.md:
--------------------------------------------------------------------------------
1 | # Products and Coproducts
2 | ### Utilities needed to compile the code below
3 | ```ocaml
4 | # let compose f g x = f (g x)
5 | val compose : ('a -> 'b) -> ('c -> 'a) -> 'c -> 'b =
6 | # let id x = x
7 | val id : 'a -> 'a =
8 | ```
9 | ## Universal Construction
10 | * Universal Construction
11 | - Defining objects in terms of their relationships.
12 | * Initial Object
13 | - The object that has one and only arrow to any object in the category.
14 | - This object is unique upto isomorphism.
15 | * Absurd definition
16 | ```OCaml
17 | type void (* Uninhabited type *)
18 | val absurd : void -> 'a
19 | ```
20 | * Terminal Object
21 | - One and only morphism coming to it from any object in the category.
22 | - Unique upto isomorphism.
23 | ```ocaml
24 | # let unit x = ()
25 | val unit : 'a -> unit =
26 | ```
27 | ```ocaml
28 | # let yes _ = true
29 | val yes : 'a -> bool =
30 | ```
31 | ```ocaml
32 | # let no _ = false
33 | val no : 'a -> bool =
34 | ```
35 | * For any Category C, we can reverse the arrows and define opposite category.
36 | * Constructions in the opposite category are prefixed with "co".
37 | ## Isomorphisms
38 | * Propositional equality, intensional equality, extensional equality and equality as a path in homotopy type theory.
39 | * Isomorphism is an even weaker notion of equivalence.
40 | * Isomorphism - Object that look the same and have an one to one mapping between them(Invertible morphism)
41 | * Pseudo Ocaml for expression function equality
42 | ```OCaml
43 | compose f g = id
44 | compose g f = id
45 | ```
46 | * Initial and Terminal objects are *unique upto unique isomorphism*.
47 | * This uniqueness upto unique isomorphism is the basis for all universal construction.
48 | ## Products
49 | ```ocaml
50 | # let fst (a,b) = a
51 | val fst : 'a * 'b -> 'a =
52 | ```
53 | ```ocaml
54 | # let snd (a, b) = b
55 | val snd : 'a * 'b -> 'b =
56 | ```
57 | ```ocaml
58 | let fst (a,_) = a
59 | let snd (_, b) = b
60 | ```
61 | * Object *c* and two morphisms *p* and *q* connecting it to *a* and *b*
62 | ```ocaml
63 | module type Chapter5_Product = sig
64 | type a
65 | type c
66 | type b
67 | val p : c -> a
68 | val q : c -> b
69 | end
70 | ```
71 | * Example with *Int* and *Bool*
72 | ```ocaml
73 | module Chapter5_Product_Example: Chapter5_Product with type a = int and type b = bool and type c = int = struct
74 | type a = int
75 | type b = bool
76 | type c = int
77 | let p x = x
78 | let q _ = true
79 | end
80 | ```
81 | * Example with *c* as (int, int, bool)
82 | ```ocaml
83 | module Chapter5_Product_Example2: Chapter5_Product = struct
84 | type a = int
85 | type b = bool
86 | type c = int * int * bool
87 | let p (x,_,_) = x
88 | let q (_,_,b) = b
89 | end
90 | ```
91 | * P' and Q' from *p* and *q* using *m*
92 | ```OCaml
93 | let p' = compose Chapter5_Product_Example.p m
94 | let q' = compose Chapter5_Product_Example.q m
95 | ```
96 | * m as a function returning pair (int, bool)
97 | ```ocaml
98 | let m (x:int) = (x, true)
99 | ```
100 | ```ocaml
101 | let p x = fst (m x)
102 | let q x = snd (m x)
103 | ```
104 | * With, m as a function taking (int, int, bool)
105 | ```ocaml
106 | let m ((x,_,b): int * int * bool) = (x, b)
107 | ```
108 | * Pseudo OCaml showing function equivalence
109 | ```OCaml
110 | fst = compose p m'
111 | snd = compose q m'
112 | ```
113 | * m' example
114 | ```ocaml
115 | # let m' ((x, b): int * bool) = (x, x, b)
116 | val m' : int * bool -> int * int * bool =
117 | ```
118 | * m' another example
119 | ```ocaml
120 | # let m' ((x, b): int * bool) = (x, 42, b)
121 | val m' : int * bool -> int * int * bool =
122 | ```
123 | * Projection example
124 | ```ocaml
125 | module type Chapter5_product_projection_example = functor (Product : Chapter5_Product) ->
126 | sig
127 | val m : Product.c -> Product.a * Product.b
128 | end
129 | module ProjectionImpl(Product:Chapter5_Product) = struct
130 | let m c = (Product.p c, Product.q c)
131 | end
132 | ```
133 | * factorizer example
134 | ```ocaml
135 | module type Factorizer = functor (Product: Chapter5_Product) ->
136 | sig
137 | val factorizer : (Product.c -> Product.a) -> (Product.c -> Product.b) -> (Product.c -> Product.a * Product.b)
138 | end
139 | module FactorizerImpl(Product:Chapter5_Product) = struct
140 | let factorizer ca cb = (Product.p ca, Product.q cb)
141 | end
142 | ```
143 | * CoProduct
144 | ```ocaml
145 | module type CoProduct = sig
146 | type a
147 | type b
148 | type c
149 | val i : a -> c
150 | val j : b -> c
151 | end
152 | ```
153 | * Pseudo OCaml showing function equivalence
154 | ```OCaml
155 | i' == compose m i
156 | j' == compose m j
157 | ```
158 | * Coproduct is the disjoint union of two sets.
159 | * example
160 | ```ocaml
161 | type contact =
162 | | PhoneNum of int
163 | | EmailAddr of string
164 | ```
165 | * example function
166 | ```ocaml
167 | # let helpdesk = PhoneNum 2222222
168 | val helpdesk : contact = PhoneNum 2222222
169 | ```
170 | * Either type
171 | ```ocaml
172 | type ('a, 'b) either =
173 | | Left of 'a
174 | | Right of 'b
175 | ```
176 | * Factorizer
177 | ```ocaml
178 | let factorizer i j = function
179 | | Left a -> i a
180 | | Right b -> j b
181 | ```
182 | * Definition of terminal object can be obtained by reversing the arrows of an initial object.
183 | * Definition of coproduct can be obtained by reversing the arrows of product
184 | * Pseudo OCaml
185 | ```OCaml
186 | p = compose fst m
187 | q = compose snd m
188 | ```
189 | ```OCaml
190 | p () = fst (m ())
191 | q () = snd (m ())
192 | ```
193 | * Functions are asymmetric. Should be defined for every element of its domain but doesn't have to cover the whole codomain.
194 | * Functions that tightly fill their codomain are called *surjective* or *onto*.
195 | * Functions are allowed to map many elements from the domain to a single element in the codomain. Collapsing functions are called *injective* or *one-to-one*
196 | * Functions that are neither embedding nor collapsing called *bijections*. They are symmetric and invertible. Example: Isomorphic functions.
197 |
--------------------------------------------------------------------------------
/chapter5/dune:
--------------------------------------------------------------------------------
1 | (rule
2 | (with-stdout-to dune.gen
3 | (run ocaml-mdx rule --direction=to-ml README.md --prelude=prelude.ml)))
4 |
5 | (alias
6 | (name runtest)
7 | (deps README.md)
8 | (action (diff dune.inc dune.gen)))
9 |
10 | (include dune.inc)
--------------------------------------------------------------------------------
/chapter5/dune.inc:
--------------------------------------------------------------------------------
1 | (alias
2 | (name runtest)
3 | (deps (:x README.md)
4 | prelude.ml)
5 | (action (progn
6 | (run ocaml-mdx test --prelude=prelude.ml --direction=to-ml %{x})
7 | (diff? %{x} %{x}.corrected)
8 | )))
9 |
--------------------------------------------------------------------------------
/chapter5/prelude.ml:
--------------------------------------------------------------------------------
1 | #require "core,core.top,ppx_jane";;
2 |
3 | open Base
4 |
5 | let () = Printexc.record_backtrace false
6 |
--------------------------------------------------------------------------------
/chapter6/README.md:
--------------------------------------------------------------------------------
1 | # Simple Algebraic Data Types
2 | ### Product Types
3 | * Implemented using pairs.
4 | * Not commutative.
5 | * Commmutative upto isomorphism.
6 | ```ocaml
7 | # let swap (a, b) = (b, a)
8 | val swap : 'a * 'b -> 'b * 'a =
9 | ```
10 | * Nesting pairs are isomorphic.(Pseudo OCaml)
11 | ```OCaml
12 | (('a * 'b) * 'c)
13 | ```
14 | ```OCaml
15 | ('a * ('b * 'c))
16 | ```
17 | * Types are different but elements are in one-to-one correspondence.
18 | ```ocaml
19 | # let alpha ((a, b), c) = (a, (b, c))
20 | val alpha : ('a * 'b) * 'c -> 'a * ('b * 'c) =
21 | ```
22 | * Invertible function Alpha.
23 | ```ocaml
24 | # let alpha_inv (a, (b, c)) = ((a, b), c)
25 | val alpha_inv : 'a * ('b * 'c) -> ('a * 'b) * 'c =
26 | ```
27 | * Unit type is the unit of the product
28 | * Adding unit to a type 'a is isomorphic to 'a.
29 | ```OCaml
30 | 'a * unit
31 | ```
32 | * Isomorphism example
33 | ```ocaml
34 | # let rho (a, ()) = a
35 | val rho : 'a * unit -> 'a =
36 | ```
37 | ```ocaml
38 | # let rho_inv a = (a, ())
39 | val rho_inv : 'a -> 'a * unit =
40 | ```
41 | * _Set_ is a monoidal category. (A category that is also a monoid)
42 | * Pair as ADT
43 | ```ocaml
44 | type ('a, 'b) pair = P of 'a * 'b
45 | ```
46 | * Example construction
47 | ```ocaml
48 | # let stmt = P ("This statement is", false)
49 | val stmt : (string, bool) pair = P ("This statement is", false)
50 | ```
51 | * Type and Data constructors with same name. In Ocaml, data constructors start with an uppercase, though.
52 | ```ocaml
53 | type ('a, 'b) pair = Pair of ('a * 'b)
54 | ```
55 | * Pair and (,) are interchangeable.
56 | ```ocaml
57 | # let stmt = ("This statement is", false)
58 | val stmt : string * bool = ("This statement is", false)
59 | ```
60 | * Named products.
61 | ```ocaml
62 | type stmt = Stmt of string * int
63 | ```
64 | ## Records
65 | * Problem in working with unnamed tuples
66 | ```ocaml
67 | # let starts_with_symbol (name, symbol, _) = String.is_prefix name ~prefix:symbol
68 | val starts_with_symbol : string * string * 'a -> bool =
69 | ```
70 | * Element as a Record
71 | ```ocaml
72 | type element =
73 | { name: string;
74 | symbol: string;
75 | atomic_number: int;
76 | }
77 | ```
78 | * The two representations are isomorphic.
79 | ```ocaml
80 | # let tuple_to_elem (name, symbol, atomic_number) = {name; symbol; atomic_number}
81 | val tuple_to_elem : string * string * int -> element =
82 | ```
83 | ```ocaml
84 | # let elem_to_tuple {name; symbol; atomic_number} = (name, symbol, atomic_number)
85 | val elem_to_tuple : element -> string * string * int =
86 | ```
87 | ```ocaml
88 | # let atomic_number {atomic_number} = atomic_number
89 | val atomic_number : element -> int =
90 | ```
91 | * Using record syntax
92 | ```ocaml
93 | # let starts_with_symbol {name;symbol;_} = String.is_prefix name ~prefix:symbol
94 | val starts_with_symbol : element -> bool =
95 | ```
96 | * Infix application only available for special characters
97 | ```ocaml
98 | (* OCaml only allows special characters in the infix operator. So, the above function name cannot be applied be infix. *)
99 | ```
100 | ## Sum Types
101 | * Either type (Similar to OCaml's builtin Result type)
102 | ```ocaml
103 | type ('a, 'b) either = Left of 'a | Right of 'b
104 | ```
105 | * Sum Types are commutative upto isomorphism.
106 | ```ocaml
107 | type ('a, 'b, 'c) one_of_three = Sinistrial of 'a | Medial of 'b | Dextral of 'c
108 | ```
109 | * *Set* is a symmetric monoidal category with respect to coproduct.
110 | * Role of the binary operation is played by the disjoint sum(Either).
111 | * Role of the initial operation is played by the initial object(Void).
112 | * Pseudo OCaml
113 | ```OCaml
114 | 'a void either
115 | ```
116 | * Sum type example
117 | ```ocaml
118 | type color = Red | Green | Blue
119 | ```
120 | * Even simpler example
121 | ```ocaml
122 | type bool = True | False
123 | ```
124 | * Maybe type (Similar to OCaml's builtin Option type)
125 | ```ocaml
126 | type 'a maybe = Nothing | Just of 'a
127 | ```
128 | * Nothing type
129 | ```ocaml
130 | type nothing_type = Nothing
131 | ```
132 | * Just type
133 | ```ocaml
134 | type 'a just_type = Just of 'a
135 | ```
136 | * Maybe using Either
137 | ```ocaml
138 | type 'a maybe = (unit, 'a) either
139 | ```
140 | * List type
141 | ```ocaml
142 | type 'a list = Nil | Cons of 'a * 'a list
143 | ```
144 | * Maybe Tail
145 | ```ocaml
146 | type 'a maybe = Nothing | Just of 'a
147 | let maybe_tail = function | Nil -> Nothing | Cons (_, xs) -> Just xs
148 | ```
149 | ## Algebra of Types
150 | * Pseudo Ocaml representation of types
151 | ```OCaml
152 | 'a * ('b, 'c) either
153 | ```
154 | ```OCaml
155 | ('a * 'b, 'c * 'd) either
156 | ```
157 | * Isomorphic example
158 | ```ocaml
159 | # let prod_to_sum (x, e) = match e with
160 | | Left y -> Left (x, y)
161 | | Right z -> Right (x, z)
162 | val prod_to_sum : 'a * ('b, 'c) either -> ('a * 'b, 'a * 'c) either =
163 | ```
164 | ```ocaml
165 | # let sum_to_prod = function | Left (x, y) -> (x, Left y) | Right (x, z) -> (x, Right z)
166 | val sum_to_prod : ('a * 'b, 'a * 'c) either -> 'a * ('b, 'c) either =
167 | ```
168 | * Sample value
169 | ```ocaml
170 | # let prod1 = (2, Left "Hi!")
171 | val prod1 : int * (string, 'a) either = (2, Left "Hi!")
172 | ```
173 | * Defining list again
174 | ```ocaml
175 | type 'a list = Nil | Cons of 'a * 'a list
176 | ```
177 |
--------------------------------------------------------------------------------
/chapter6/dune:
--------------------------------------------------------------------------------
1 | (rule
2 | (with-stdout-to dune.gen
3 | (run ocaml-mdx rule --direction=to-ml README.md --prelude=prelude.ml)))
4 |
5 | (alias
6 | (name runtest)
7 | (deps README.md)
8 | (action (diff dune.inc dune.gen)))
9 |
10 | (include dune.inc)
--------------------------------------------------------------------------------
/chapter6/dune.inc:
--------------------------------------------------------------------------------
1 | (alias
2 | (name runtest)
3 | (deps (:x README.md)
4 | prelude.ml)
5 | (action (progn
6 | (run ocaml-mdx test --prelude=prelude.ml --direction=to-ml %{x})
7 | (diff? %{x} %{x}.corrected)
8 | )))
9 |
--------------------------------------------------------------------------------
/chapter6/prelude.ml:
--------------------------------------------------------------------------------
1 | #require "core,core.top,ppx_jane";;
2 |
3 | open Base
4 |
5 | let () = Printexc.record_backtrace false
6 |
--------------------------------------------------------------------------------
/chapter7/README.md:
--------------------------------------------------------------------------------
1 | # Functors
2 | - Functors are functions on objects.
3 | - Functors map both objects and morphisms.
4 | - Functors preserve connections when it maps morphisms.
5 | - Functors must preserve the structure of a category.
6 | - Collapsing Functor
7 | - Maps every object in the source category to one selected object in the target category.
8 | - Maps every morphism to identity morphism.
9 |
10 | ### Utitlities
11 | ```ocaml
12 | let compose f g x = f (g x)
13 | ```
14 | ### Maybe Functor
15 | - Maybe functor
16 | ```ocaml
17 | type 'a option = None | Some of 'a
18 | ```
19 | - Example function
20 | ```ocaml
21 | module type AtoB = sig
22 | type a
23 | type b
24 | val f : a -> b
25 | end
26 | ```
27 | - Function from 'a option to 'b option
28 | ```ocaml
29 | # let f' f = function | None -> None | Some x -> Some (f x)
30 | val f' : ('a -> 'b) -> 'a option -> 'b option =
31 | ```
32 | - Morphism mapping as `fmap`
33 | ```ocaml
34 | module type Maybe_Functor = sig
35 | type a
36 | type b
37 | val fmap : (a -> b) -> (a option -> b option)
38 | end
39 | ```
40 | - fmap as a function with two arguments.
41 | ```ocaml
42 | module type Maybe_Functor = sig
43 | type a
44 | type b
45 | val fmap : (a -> b) -> a option -> b option
46 | end
47 | ```
48 | - Maybe Functor Example implementation.
49 | ```ocaml
50 | # let fmap f = function
51 | | None -> None
52 | | Some x -> Some (f x)
53 | val fmap : ('a -> 'b) -> 'a option -> 'b option =
54 | ```
55 | - Id example
56 | ```ocaml
57 | # let id x = x
58 | val id : 'a -> 'a =
59 | ```
60 | ### Utilities needed to compile the code(Can skip this section)
61 | ```ocaml
62 | module type Functor = sig
63 | type 'a t
64 | val fmap : ('a -> 'b) -> 'a t -> 'b t
65 | end
66 | (* Functor for Option type *)
67 | module OptionF : (Functor with type 'a t = 'a option) = struct
68 | type 'a t = 'a option
69 | let fmap f = function | None -> None | Some x -> Some (f x)
70 | end
71 | ```
72 | ### Test functor laws
73 | - Test Id law (Syntactically correct OCaml but will not be compiled by mdx)
74 | ```OCaml
75 | module Test_Functor_Id(F: Functor) = struct
76 | open F
77 | let test_id x = assert ((fmap id x) = x)
78 | end
79 | ```
80 | - Test Compose law (Syntactically correct OCaml but will not be compiled by mdx)
81 | ```OCaml
82 | module Test_Functor_Compose(F: Functor) = struct
83 | open F
84 |
85 | (* Compose *)
86 | let <.> f g x = f (g x)
87 |
88 | let test_compose f g x = assert (fmap (f <.> g) x = fmap f (fmap g x))
89 | end
90 | ```
91 | ### Typeclasses
92 | - OCaml doesn't have typeclasses.
93 | - But it has functor modules.
94 | ```ocaml
95 | module type Eq = sig
96 | type a
97 | val (==) : a -> a -> bool
98 | end
99 | ```
100 | - Point data type
101 | ```ocaml
102 | type point = Pt of float * float
103 | ```
104 | - Eq instance for Point
105 | ```ocaml
106 | module Point_Eq(E:Eq with type a = float) = struct
107 | type a = point
108 | let (==) (Pt (p1x, p1y)) (Pt (p2x, p2y)) = E.(p1x == p2x) && E.(p2x == p2y)
109 | end
110 | ```
111 | - Functor for OCaml
112 | ```ocaml
113 | module type Functor = sig
114 | type 'a t
115 | val fmap : ('a -> 'b) -> 'a t -> 'b t
116 | end
117 | ```
118 | - Functor instance for Option
119 | ```ocaml
120 | module Option_Functor:(Functor with type 'a t = 'a option) = struct
121 | type 'a t = 'a option
122 | let fmap f = function
123 | | None -> None
124 | | Some x -> Some (f x)
125 | end
126 | ```
127 | - List Functor
128 | ```ocaml
129 | type 'a list = Nil | Cons of 'a * 'a list
130 | ```
131 | - Fmap for list
132 | ```ocaml
133 | module type List_Functor_Type = sig
134 | type 'a t = 'a list
135 | val fmap : ('a -> 'b) -> 'a list -> 'b list
136 | end
137 | ```
138 | - Fmap impl for list
139 | ```ocaml
140 | # let rec fmap f = function
141 | | Nil -> Nil
142 | | Cons (x, xs) -> Cons (f x, fmap f xs)
143 | val fmap : ('a -> 'b) -> 'a list -> 'b list =
144 | ```
145 | - Functor instance for List
146 | ```ocaml
147 | module List_Functor : (Functor with type 'a t = 'a list) = struct
148 | type 'a t = 'a list
149 | let rec fmap f = function
150 | | Nil -> Nil
151 | | Cons (x, xs) -> Cons (f x, fmap f xs)
152 | end
153 | ```
154 | ### Reader Functor
155 | - Function type
156 | ```ocaml
157 | type ('a, 'b) t = 'a -> 'b
158 | ```
159 | - Partially Applied Function Type
160 | ```ocaml
161 | module type T = sig
162 | type t
163 | end
164 | module Partially_Applied_FunctionType(T : T) = struct
165 | type 'b t = T.t -> 'b
166 | end
167 | ```
168 | - fmap for Reader
169 | ```ocaml
170 | module type Reader_Fmap_Example = sig
171 | val fmap : ('a -> 'b) -> ('r -> 'a) -> 'r -> 'b
172 | end
173 | ```
174 | - Functor Instance for Reader
175 | ```ocaml
176 | module Reader_Functor(T: T):Functor = struct
177 | type 'a t = T.t -> 'a
178 | let fmap f ra = fun r -> f (ra r)
179 | end
180 | ```
181 | - Reader Functor implementation - Even simpler
182 | ```ocaml
183 | # let fmap: ('a -> 'b) -> ('r -> 'a) -> ('r -> 'b) = compose
184 | val fmap : ('a -> 'b) -> ('r -> 'a) -> 'r -> 'b =
185 | ```
186 |
187 | ### Functors as Containers
188 | - Infinite list
189 | ```ocaml
190 | # let nats = Caml.Stream.from (fun i -> Some (i + 1))
191 | val nats : int Stream.t =
192 | ```
193 | - Functors can be considered as a container of value(s) of the type over which it is parameterized or as containing a recipe for generating those values.
194 | - It doesn't matter if we are able to access the values inside the functor. All that matters is if we are able to manipulate those values using functions and making sure that these manipulations compose correctly.
195 | - Const
196 | ```ocaml
197 | type ('c, 'a) const = Const of 'c
198 | ```
199 | - Const fmap signature example
200 | ```ocaml
201 | module type Const_Functor_Example = sig
202 | val fmap : ('a -> 'b) -> ('c, 'a) const -> ('c, 'b) const
203 | end
204 | ```
205 | - Const functor instance.
206 | ```ocaml
207 | module Const_Functor(T : T) : Functor = struct
208 | type 'a t = (T.t, 'a) const
209 | let fmap f (Const c) = Const c (* or even let fmap _ c = c *)
210 | end
211 | ```
212 | ### Functor Composition
213 | - A composition of two functors when acting on objects is just the composition of their respective object mappings.
214 | - Same for morphisms.
215 | ```ocaml
216 | # let maybe_tail = function
217 | | [] -> None
218 | | _ :: xs -> Some xs
219 | val maybe_tail : 'a list -> 'a list option =
220 | ```
221 | - Using fmap of respective functors
222 | ```ocaml
223 | let square x = x * x
224 | let mis = Some (Cons (1, Cons (2, Cons (3, Nil))))
225 | let mis2 = Option_Functor.fmap (List_Functor.fmap square) mis
226 | ```
227 | - Composing fmap of list and option functors
228 | ```ocaml
229 | let fmapO = Option_Functor.fmap
230 | let fmapL = List_Functor.fmap
231 | let fmapC f l = (compose fmapO fmapL) f l
232 | let mis2 = fmapC (square) mis
233 | ```
234 | - Viewing fmap as a function of one argument
235 | ```ocaml
236 | module type Fmap_Alt_Sig_Example = sig
237 | type 'a t
238 | val fmap : ('a -> 'b) -> ('a t -> 'b t)
239 | end
240 | ```
241 | - square signature
242 | ```ocaml
243 | module type Square_Signature = sig
244 | val square : int -> int
245 | end
246 | ```
247 | - Return type signature (Syntactically correct Ocaml but not compiled)
248 | ```OCaml
249 | int list -> int list
250 | ```
251 | - First fmap takes above signature and then returns a function.
252 | ```OCaml
253 | int list option -> int list option
254 | ```
255 | - Functors form a category.
256 | - Objects are categories. Morphisms are functors.
257 | - *Cat* category of all small categories.
258 |
--------------------------------------------------------------------------------
/chapter7/dune:
--------------------------------------------------------------------------------
1 | (rule
2 | (with-stdout-to dune.gen
3 | (run ocaml-mdx rule --direction=to-ml README.md --prelude=prelude.ml)))
4 |
5 | (alias
6 | (name runtest)
7 | (deps README.md)
8 | (action (diff dune.inc dune.gen)))
9 |
10 | (include dune.inc)
--------------------------------------------------------------------------------
/chapter7/dune.inc:
--------------------------------------------------------------------------------
1 | (alias
2 | (name runtest)
3 | (deps (:x README.md)
4 | prelude.ml)
5 | (action (progn
6 | (run ocaml-mdx test --prelude=prelude.ml --direction=to-ml %{x})
7 | (diff? %{x} %{x}.corrected)
8 | )))
9 |
--------------------------------------------------------------------------------
/chapter7/prelude.ml:
--------------------------------------------------------------------------------
1 | #require "core,core.top,ppx_jane";;
2 |
3 | open Base
4 |
5 | let () = Printexc.record_backtrace false
6 |
--------------------------------------------------------------------------------
/chapter8/README.md:
--------------------------------------------------------------------------------
1 | # Functoriality
2 | ### Utilities needed for the code below
3 | ```ocaml
4 | # let id : 'a -> 'a = fun x -> x
5 | val id : 'a -> 'a =
6 | # let compose f g x = f (g x)
7 | val compose : ('a -> 'b) -> ('c -> 'a) -> 'c -> 'b =
8 | ```
9 | ```ocaml
10 | (* Functor definition given in previous chapter *)
11 | module type Functor = sig
12 | type 'a t
13 | val fmap : ('a -> 'b) -> 'a t -> 'b t
14 | end
15 | ```
16 | ### Bifunctors
17 | - Functors are morphisms in Cat.
18 | - Bifunctors - Functors of two arguments.
19 | - Bifunctor maps every pair of objects, one from category C and one from category D, to category E.
20 | - Bifunctors map morphism from C and morphism from D to a morphism in E.
21 | - Pair of objects is an object in the category C x D and a pair of morphism is just a morphism in the category C x D.
22 | - Bifunctors - Functors in both arguments.
23 | ```ocaml
24 | (** You can represent bifunctor defintion in two forms and implement just and derive the other from it. *)
25 | module type BifunctorCore = sig
26 | type ('a, 'b) t
27 | val bimap : ('a -> 'c) -> ('b -> 'd) -> ('a, 'b) t -> ('c, 'd) t
28 | end
29 |
30 | module type BifunctorExt = sig
31 | type ('a, 'b) t
32 | val first : ('a -> 'c) -> ('a, 'b) t -> ('c, 'b) t
33 | val second : ('b -> 'd) -> ('a, 'b) t -> ('a, 'd) t
34 | end
35 |
36 | module BifunctorCore_Using_Ext(M : BifunctorExt):BifunctorCore = struct
37 | type ('a, 'b) t = ('a, 'b) M.t
38 | let bimap g h x = M.first g (M.second h x)
39 | end
40 |
41 | module BifunctorExt_Using_Core(M : BifunctorCore):BifunctorExt = struct
42 | type ('a, 'b) t = ('a, 'b) M.t
43 | let first g x = M.bimap g id x
44 | let second h x = M.bimap id h x
45 | end
46 | ```
47 | - Example of bifunctor - Product type
48 | ```ocaml
49 | module Bifunctor_Product : BifunctorCore = struct
50 | type ('a, 'b) t = 'a * 'b
51 | let bimap f g (l, r) = (f l, g r)
52 | end
53 | ```
54 | - bimap signature for product type.
55 | ```OCaml
56 | val bimap : ('a -> 'c) -> ('b -> 'd) -> ('a, 'b) Bifunctor_Product.t -> ('c, 'd) Bifunctor_Product.t
57 | ```
58 | - Coproduct
59 | ```ocaml
60 | type ('a, 'b) either = Left of 'a | Right of 'b
61 | module Bifunctor_Either : BifunctorCore = struct
62 | type ('a, 'b) t = ('a, 'b) either
63 | let bimap f g = function | Left a -> Left (f a) | Right b -> Right (g b)
64 | end
65 | ```
66 | - Monoidal category defines
67 | - a binary operator(must be a bifunctor) acting on objects.
68 | - a unit object
69 | - Set is a monoidal category with respect to cartesian product.
70 | - Set is a monoidal category with respect to disjoint union.
71 | ### Functoral ADT
72 | - ADTs are made of sum and product types.
73 | - Sum and Product types are functorial.
74 | - Functors compose.
75 | - Identity type
76 | ```ocaml
77 | type 'a id = Id of 'a
78 | ```
79 | - Functor for Identity.
80 | ```ocaml
81 | module Identity_Functor : Functor = struct
82 | type 'a t = 'a id
83 | let fmap f (Id a) = Id (f a)
84 | end
85 | ```
86 | - Maybe type
87 | ```ocaml
88 | type 'a option = None | Some of 'a
89 | ```
90 | - None part can be represented using Const () functor.
91 | - Just part can be represented using Id functor.
92 | - Maybe type using Either
93 | ```ocaml
94 | (** OCaml doesn't have a built in Const type *)
95 | type ('a, 'b) const = Const of 'a;;
96 | (** OCaml doesn't have a built in either type *)
97 | type ('a, 'b) either = Left of 'a | Right of 'b
98 | (** Either type *)
99 | type 'a option = ((unit, 'a) const, 'a id) either
100 | ```
101 | - Composition of functors is a functor.
102 | - In OCaml, abstracting over type constructors requires some extra work.
103 | ```ocaml
104 | (** OCaml doesn't support higher kinded types. So, we have to use module functors to emulate the behavior higher kinded types. There's less verbose options using type defunctionalization but it's more advanced and obscures the flow of this book *)
105 | module type BiComp = functor(BF: sig type ('a, 'b) t end)(FU : sig type 'a t end)(GU: sig type 'b t end) -> sig
106 | type ('a, 'b) bicomp = BiComp of ('a FU.t, 'b GU.t) BF.t
107 | end
108 | ```
109 | - Bifunctor instance
110 | ```ocaml
111 | module BiCompBifunctor(BF: BifunctorCore)(FU:Functor)(GU:Functor):BifunctorCore = struct
112 | type ('a, 'b) t = BiComp of ('a FU.t, 'b GU.t) BF.t
113 | let bimap f g (BiComp x) = BiComp (BF.bimap (FU.fmap f) (GU.fmap g) x)
114 | end
115 | ```
116 | - type of x in the definition (Pseudo OCaml)
117 | ```OCaml
118 | type ('a FU.t, 'b GU.t) BF.t
119 | ```
120 | - Types of f1 and f2 (Pseudo OCaml)
121 | ```OCaml
122 | val f1 : a -> a'
123 | val f2 : b -> b'
124 | ```
125 | - then final result of type bf (Pseudo OCaml)
126 | ```OCaml
127 | val bimap : (a FU.t -> a' FU.t) -> (b GU.t -> b' GU.t) -> (a FU.t, b GU.t) -> (a' FU.t, b' GU.t)
128 | ```
129 | - Functors
130 | ```ocaml
131 | (** Deriving a functor in OCaml is not available as a language extension. You could try experimental library like ocsigen to derive functors.*)
132 | type 'a tree = Leaf of 'a | Node of 'a tree * 'a tree
133 | ```
134 | - Functor for tree
135 | ```ocaml
136 | module TreeFunctor: Functor = struct
137 | type 'a t = 'a tree
138 | let rec fmap f = function
139 | | Leaf a -> Leaf (f a)
140 | | Node (l, r) -> Node (fmap f l, fmap f r)
141 | end
142 | ```
143 | - Writer type
144 | ```ocaml
145 | type 'a writer = 'a * string
146 | ```
147 | - Kleisli Composition (Using Writer)
148 | ```ocaml
149 | module KleisliComposition = struct
150 | let (>=>) : ('a -> 'b writer) -> ('b -> 'c writer) -> ('a -> 'c writer) = fun m1 m2 ->
151 | fun x ->
152 | let (y, s1) = m1 x in
153 | let (z, s2) = m2 y in
154 | (z, StringLabels.concat ~sep:"" [s1; s2])
155 | end
156 | ```
157 | - Kleisli Identity (Using writer)
158 | ```ocaml
159 | module KleisliIdentity = struct
160 | let return : 'a -> 'a writer = fun a -> (a, "")
161 | end
162 | ```
163 | - Kleisli Fmap implementation - (Using Writer)
164 | ```ocaml
165 | module KleisliFunctor : Functor = struct
166 | type 'a t = 'a writer
167 | let fmap f = KleisliComposition.(>=>) id (fun x -> KleisliIdentity.return (f x))
168 | end
169 | ```
170 | - Covariant Functors
171 | ```ocaml
172 | module PartialArrow(T : sig type r end) = struct
173 | type 'a t = T.r -> 'a
174 | end
175 | ```
176 | - Reader type
177 | ```ocaml
178 | type ('r, 'a) reader = 'r -> 'a
179 | ```
180 | - Functor for Reader type
181 | ```ocaml
182 | module ReaderFunctor(In: sig type r end): Functor = struct
183 | type 'a t = (In.r, 'a) reader
184 | let fmap f g = compose f g
185 | end
186 | ```
187 | - Reader flipped - Op
188 | ```ocaml
189 | type ('r, 'a) op = 'a -> 'r
190 | ```
191 | - Fmap for Op
192 | ```OCaml
193 | val fmap : 'a 'b. ('a -> 'b) -> ('a -> 'r) -> ('b -> 'r)
194 | ```
195 | - For every category C, there is a dual category C^op(Same objects as C but arrows reversed)
196 | - Mapping of categories that inverts the direction of morphisms is called contravariant functor.
197 | - Contravariant functor is a regular functor from the opposite category.
198 | ```ocaml
199 | module type Contravariant = sig
200 | type 'a t
201 | val contramap : ('b -> 'a) -> 'a t -> 'b t
202 | end
203 | ```
204 | - Contravariant instance for op
205 | ```ocaml
206 | module OpContravariant(In : sig type r end) : Contravariant = struct
207 | type 'a t = (In.r, 'a) op
208 | let contramap f g = compose g f
209 | end
210 | ```
211 | - Flip
212 | ```ocaml
213 | # let flip f b a = f a b
214 | val flip : ('a -> 'b -> 'c) -> 'b -> 'a -> 'c =
215 | ```
216 | - Contramap and flip
217 | ```ocaml
218 | # let contramap : ('b -> 'a) -> ('r, 'a) op -> ('r, 'b) op = fun f g -> flip compose f g
219 | val contramap : ('b -> 'a) -> ('r, 'a) op -> ('r, 'b) op =
220 | ```
221 | ### Profunctors
222 | - Function arrow is contravariant in its first argument and covariant in its second argument.
223 | - If the target category is *Set*, then we can describe this as Profunctor.
224 | ```ocaml
225 | (* Profunctor definition *)
226 | module type Profunctor = sig
227 | type ('a,'b) p
228 | val dimap : ('a -> 'b) -> ('c -> 'd) -> ('b, 'c) p -> ('a, 'd) p
229 | end
230 |
231 | (* Profunctor alternate definition *)
232 | module type ProfunctorExt = sig
233 | type ('a, 'b) p
234 | val lmap : ('a -> 'b) -> ('b, 'c) p -> ('a, 'c) p
235 | val rmap : ('b -> 'c) -> ('a, 'b) p -> ('a, 'c) p
236 | end
237 |
238 | (* Profunctor dimap defined using lmap and rmap *)
239 | module Profunctor_Using_Ext(PF: ProfunctorExt):Profunctor = struct
240 | type ('a, 'b) p = ('a, 'b) PF.p
241 | let dimap f g = compose (PF.lmap f) (PF.rmap g)
242 | end
243 |
244 | (** Profunctor lmap and rmap defined using dimap *)
245 | module ProfunctorExt_Using_Dimap(PF: Profunctor): ProfunctorExt = struct
246 | type ('a, 'b) p = ('a, 'b) PF.p
247 | let lmap f = PF.dimap f id
248 | let rmap g = PF.dimap id g
249 | end
250 | ```
251 | - Profunctor Implementation for function type
252 | ```ocaml
253 | module ProfunctorArrow : Profunctor = struct
254 | type ('a, 'b) p = 'a -> 'b
255 | let dimap f g p = compose g (compose p f)
256 | end
257 | module ProfunctorExtArrow : ProfunctorExt = struct
258 | type ('a, 'b) p = 'a -> 'b
259 | let lmap f p = (flip compose) f p
260 | let rmap = compose
261 | end
262 | ```
263 | - Profunctor : C^op x D -> Set
264 | - Hom-Functor: C^op x C -> Hom-Set (a, b)
265 | - Hom-Functor is a special case of Profunctor.
266 |
--------------------------------------------------------------------------------
/chapter8/dune:
--------------------------------------------------------------------------------
1 | (rule
2 | (with-stdout-to dune.gen
3 | (run ocaml-mdx rule --direction=to-ml README.md --prelude=prelude.ml)))
4 |
5 | (alias
6 | (name runtest)
7 | (deps README.md)
8 | (action (diff dune.inc dune.gen)))
9 |
10 | (include dune.inc)
--------------------------------------------------------------------------------
/chapter8/dune.inc:
--------------------------------------------------------------------------------
1 | (alias
2 | (name runtest)
3 | (deps (:x README.md)
4 | prelude.ml)
5 | (action (progn
6 | (run ocaml-mdx test --prelude=prelude.ml --direction=to-ml %{x})
7 | (diff? %{x} %{x}.corrected)
8 | )))
9 |
--------------------------------------------------------------------------------
/chapter8/prelude.ml:
--------------------------------------------------------------------------------
1 | #require "core,core.top,ppx_jane";;
2 |
3 | open Base
4 |
5 | let () = Printexc.record_backtrace false
6 |
--------------------------------------------------------------------------------
/chapter9/README.md:
--------------------------------------------------------------------------------
1 | # Function Types
2 | ### Utilities
3 | ```ocaml
4 | (* Utilities needed for the rest of the scripts in the document to run. *)
5 | type ('a, 'b) either = Left of 'a | Right of 'b
6 | ```
7 | - Function type is a set of morphisms between two sets.
8 | - A set of morphisms between any two objects in a category is called a hom-set.
9 | - In the category *Set*, every hom-set is itself an object in the same category, because it's also a set.
10 | - In other categories, hom-set is external to a category - external hom-sets
11 | - Internal hom-set - an object constructed in a category that represent the hom-sets.
12 | ### Universal Construction
13 | - Constructing an internal hom-set(function type) from scratch.
14 | - A pattern that involves three objects - function type we are constructing, argument type and result type.
15 | - Function application/evaluation connects these three types.
16 | - Pick an object z and a.
17 | - Product of them z x a is an object.
18 | - Arrow g from that object to b.
19 | - g maps every such object(z x a) to b.
20 | - *There is no function type, if there is no product type*
21 | ### Currying
22 | - Curring is built into the syntax of OCaml as well.(Pseudo OCaml)
23 | ```OCaml
24 | 'a -> ('b -> 'c)
25 | ```
26 | - Unparenthesized signature
27 | ```OCaml
28 | 'a -> 'b -> 'c
29 | ```
30 | - Multi argument functions
31 | ```ocaml
32 | # let catstr s s' = String.concat ~sep:"" [s;s']
33 | val catstr : string -> string -> string =
34 | ```
35 | - Same function written using one argument functions
36 | ```ocaml
37 | # let catstr = fun s -> fun s' -> String.concat ~sep:"" [s;s']
38 | val catstr : string -> string -> string =
39 | ```
40 | - Greet
41 | ```ocaml
42 | # let greet = catstr "Hello"
43 | val greet : string -> string =
44 | ```
45 | - A Function of two variables
46 | ```OCaml
47 | 'a * 'b -> 'a
48 | ```
49 | - curry
50 | ```ocaml
51 | # let curry f a b = f (a, b)
52 | val curry : ('a * 'b -> 'c) -> 'a -> 'b -> 'c =
53 | ```
54 | - uncurry
55 | ```ocaml
56 | # let uncurry f p = f (fst p) (snd p)
57 | val uncurry : ('a -> 'b -> 'c) -> 'a * 'b -> 'c =
58 | ```
59 | - Factorizer
60 | ```ocaml
61 | # let factorizer g = fun a -> (fun b -> g (a, b))
62 | val factorizer : ('a * 'b -> 'c) -> 'a -> 'b -> 'c =
63 | ```
64 | ### Exponentials
65 | - Function object or internal hom object between a and b, is often called the exponential denoted by b^a
66 | ### Cartesian Closed Categories
67 | - Larger family of categories called *Cartesian closed*
68 | - *Set* is just one example of such a category.
69 | - Cartesian closed category must contain
70 | - The terminal object
71 | - A product of any pair of objects
72 | - An exponential for any pair of objects.
73 | - Terminal object is a product of zero arity.
74 | - CCC provides models for the simply typed lambda calculus.
75 | - Dual of product and terminal object is the coproduct and initial object.
76 | - *Bicartesian closed category* - CCC that also supports coproduct and initial object and in which product can be distributed over coproduct
77 | ### Exponentials and ADT
78 | - Function types as exponentials fits very well into the scheme of ADTs.
79 | - Algebra vs BiCartesian Closed Category
80 | - Zero -> Initial object
81 | - One -> Terminal object
82 | - product -> product
83 | - sums -> coproduct
84 | - exponential -> exponentials (internal hom object)
85 | - Singleton set is the terminal object in *Set*
86 | - Exponentials of sums
87 | ```ocaml
88 | module type Exponential_Of_Sums_Example = sig
89 | val f : (int, float) either -> string
90 | end
91 | ```
92 | - Implementation
93 | ```ocaml
94 | module Exp_Sum_Impl : Exponential_Of_Sums_Example = struct
95 | let f = function
96 | | Left n -> if n < 0 then "Negative int" else "Positive int"
97 | | Right x -> if Float.compare x 0.4 < 0 then "Negative double" else "Positive double"
98 | end
99 | ```
100 | ### Curry-Howard Isomorphism
101 | - Correspondence between logic and ADT
102 | - Void - false
103 | - unit -> true
104 | - Product -> AND
105 | - Sum type -> OR
106 | - Function type -> logical implication
107 | - Every type can be interpreted as a proposition.
108 | - Writing programs is same as proving theorems.
109 | - eval example (pseudo OCaml)
110 | ```OCaml
111 | val eval : (('a -> 'b), 'a) -> 'b
112 | ```
113 | - eval implementation
114 | ```ocaml
115 | # let eval (f,a) = f a
116 | val eval : ('a -> 'b) * 'a -> 'b =
117 | ```
118 | - Mapping a V b => a to types (pseudo OCaml)
119 | ```OCaml
120 | ('a, 'b) either -> 'a
121 | ```
122 | - Absurd (pseudo OCaml)
123 | ```OCaml
124 | val absurd : void -> 'a
125 | ```
126 |
--------------------------------------------------------------------------------
/chapter9/dune:
--------------------------------------------------------------------------------
1 | (rule
2 | (with-stdout-to dune.gen
3 | (run ocaml-mdx rule --direction=to-ml README.md --prelude=prelude.ml)))
4 |
5 | (alias
6 | (name runtest)
7 | (deps README.md)
8 | (action (diff dune.inc dune.gen)))
9 |
10 | (include dune.inc)
--------------------------------------------------------------------------------
/chapter9/dune.inc:
--------------------------------------------------------------------------------
1 | (alias
2 | (name runtest)
3 | (deps (:x README.md)
4 | prelude.ml)
5 | (action (progn
6 | (run ocaml-mdx test --prelude=prelude.ml --direction=to-ml %{x})
7 | (diff? %{x} %{x}.corrected)
8 | )))
9 |
--------------------------------------------------------------------------------
/chapter9/prelude.ml:
--------------------------------------------------------------------------------
1 | #require "core,core.top,ppx_jane";;
2 |
3 | open Base
4 |
5 | let () = Printexc.record_backtrace false
6 |
--------------------------------------------------------------------------------
/dune:
--------------------------------------------------------------------------------
1 | (alias
2 | (name generate)
3 | (deps chapter1.ml))
4 |
5 | (rule
6 | (targets chapter1/chapter.ml)
7 | (deps chapter1/chapter1.md)
8 | (action
9 | (run ocaml-mdx )))
--------------------------------------------------------------------------------
/dune-project:
--------------------------------------------------------------------------------
1 | (lang dune 1.8)
2 |
--------------------------------------------------------------------------------
/ocaml-ctfp.install:
--------------------------------------------------------------------------------
1 | lib: [
2 | "_build/install/default/lib/ocaml-ctfp/META" {"META"}
3 | "_build/install/default/lib/ocaml-ctfp/dune-package" {"dune-package"}
4 | "_build/install/default/lib/ocaml-ctfp/opam" {"opam"}
5 | ]
6 | doc: [
7 | "_build/install/default/doc/ocaml-ctfp/LICENSE"
8 | "_build/install/default/doc/ocaml-ctfp/README.org"
9 | ]
10 |
--------------------------------------------------------------------------------
/ocaml-ctfp.opam:
--------------------------------------------------------------------------------
1 | opam-version: "2.0"
2 | version: "0.0.1"
3 | synopsis: "OCaml code snippets for Category Theory For Programmers"
4 | maintainer: "Arulselvan Madhavan "
5 | authors: "Arulselvan Madhavan "
6 | license: "GPL 3.0"
7 | homepage: "https://github.com/ArulselvanMadhavan/ocaml-ctfp"
8 | bug-reports: "https://github.com/ArulselvanMadhavan/ocaml-ctfp/issues"
9 | depends: [
10 | "ocaml" {>= "4.07.1"}
11 | "dune" {build}
12 | "patdiff" #For running diff based checks in tests
13 | "core"
14 | ]
15 | build: [
16 | # ["dune" "subst"] {pinned}
17 | ["dune" "build" "-p" name "-j" jobs]
18 | ["dune" "runtest" "-p" name] {with-test}
19 | ]
20 | install: [make "install"]
21 | dev-repo: "git+https://"
22 | url {
23 | src: "git+file:///Users/arul.madhavan/dev/ocaml-projects/ocaml-ctfp#master"
24 | }
25 |
--------------------------------------------------------------------------------
/playground/.merlin:
--------------------------------------------------------------------------------
1 | EXCLUDE_QUERY_DIR
2 | B _build/default/.playground.eobjs/byte
3 | S .
4 | FLG -w @a-4-29-40-41-42-44-45-48-58-59-60-40 -strict-sequence -strict-formats -short-paths -keep-locs
5 |
--------------------------------------------------------------------------------
/playground/dune:
--------------------------------------------------------------------------------
1 | (rule
2 | (targets playground.ml)
3 | (deps playground.md)
4 | (action
5 | (progn
6 | (with-stdout-to %{targets} (run ocaml-mdx pp %{deps})))))
7 |
8 | (executable
9 | (name playground))
10 |
11 | (rule
12 | (with-stdout-to playground.md.out (run ./playground.exe)))
13 |
14 | (alias
15 | (name runtest)
16 | (deps (:x playground.md.out) (:y playground.md.out.expected))
17 | (action (progn
18 | (run ocaml-mdx test --direction=infer-timestamp %{x})
19 | (diff %{x} %{y}))))
--------------------------------------------------------------------------------
/playground/dune-project:
--------------------------------------------------------------------------------
1 | (lang dune 1.8)
2 |
--------------------------------------------------------------------------------
/playground/playground.md:
--------------------------------------------------------------------------------
1 | * mdx Playground
2 | ```ocaml
3 | print_endline "42"
4 | ```
5 |
--------------------------------------------------------------------------------
/playground/playground.md.out.expected:
--------------------------------------------------------------------------------
1 | 42
2 |
--------------------------------------------------------------------------------