[
  {
    "path": ".editorconfig",
    "content": "root = true\n\n[*]\ncharset = utf-8\nend_of_line = lf\ninsert_final_newline = true\ntrim_trailing_whitespace = true\n\n[*.md]\ntrim_trailing_whitespace = false\n\n[*.js]\nindent_size = 2\nindent_style = space\nmax_line_length = 100\n"
  },
  {
    "path": ".generate-summary.pl",
    "content": "#!/usr/bin/env perl -n\n\nBEGIN {\n  print \"# Summary\\n\\n\"\n}\n\n# Trim whitespace\ns/^\\s+|\\s+$//g;\n\n# Print headlines\nif (/^# (.*)/) {\n  print \"* [$1]($ARGV)\\n\"\n}\n\n# Print subheadlines\nif (/^## (.*)/) {\n  my $subheadline = $1;\n  my $anchor = lc $subheadline;\n\n  # Remove all but word characters and whitespace\n  $anchor =~ s/[^\\wö ]//g;\n  # Replace whitespace with dashes\n  $anchor =~ tr/ /-/d;\n\n  print \"  * [$subheadline]($ARGV#$anchor)\\n\"\n}\n"
  },
  {
    "path": ".github/workflows/build.yml",
    "content": "name: build\n\non:\n  push:\n    branches:\n      - master\n\nenv:\n  BOOK_FILENAME: mostly-adequate-guide-to-functional-programming\n\njobs:\n  build:\n    runs-on: ubuntu-22.04\n    steps:\n      - name: Checkout source code\n        uses: actions/checkout@v4\n\n      - name: Install Calibre\n        run: |\n          sudo apt install -y libopengl0 libegl1 libxcb-cursor0\n          wget -nv -O- https://download.calibre-ebook.com/linux-installer.sh | sh /dev/stdin\n          mkdir -p ~/.local/bin\n          ln -s /opt/calibre/calibre ~/.local/bin/calibre\n          ln -s /opt/calibre/ebook-convert ~/.local/bin/ebook-convert\n\n      - name: Setup Node.js\n        uses: actions/setup-node@v4\n        with:\n          node-version: 10.22.1\n\n      - name: Generate summary\n        run: |\n          npm run generate-summary\n\n      - name: Setup gitbook\n        run: |\n          npm install\n          npm run setup\n\n      - name: Generate PDF\n        run: |\n          npm run generate-pdf\n          mv book.pdf ${BOOK_FILENAME}.pdf\n\n      - name: Generate EPUB\n        run: |\n          npm run generate-epub\n          mv book.epub ${BOOK_FILENAME}.epub\n\n      - uses: actions/upload-artifact@v4\n        with:\n          name: PDF\n          path: ${{ env.BOOK_FILENAME }}.pdf\n\n      - uses: actions/upload-artifact@v4\n        with:\n          name: EPUB\n          path: ${{ env.BOOK_FILENAME }}.epub\n\n      - run: echo \"ID=$(git describe --tags --always)\" >> $GITHUB_OUTPUT\n        id: release-id\n\n      - uses: softprops/action-gh-release@v2\n        with:\n          tag_name: ${{ steps.release-id.outputs.ID }}\n          files: |\n            ${{ env.BOOK_FILENAME }}.pdf\n            ${{ env.BOOK_FILENAME }}.epub\n"
  },
  {
    "path": ".gitignore",
    "content": "node_modules\ngrunt\nless\nGruntfile.js\nnpm-debug.log\n.DS_Store\n*.md#*\n_book\n/book.pdf\n/book.epub\nexercises/index.js\npackage-lock.json\n"
  },
  {
    "path": ".nvmrc",
    "content": "v10.22.1\n"
  },
  {
    "path": "CONTRIBUTING.md",
    "content": "\n# Contributing to Mostly Adequate Guide to Functional Programming\n\n## Licensing\n\nBy opening a pull request to this repository, you agree to provide your work under the [project license](LICENSE). Also, you agree to grant such license of your work as is required for the purposes of future print editions to @DrBoolean. Should your changes appear in a printed edition, you'll be included in the contributors list.\n\n## Small Corrections\n\nErrata and basic clarifications will be accepted if we agree that they improve the content. You can also open an issue so we can figure out how or if it needs to be addressed. If you've never done this before, the [flow guide](https://guides.github.com/introduction/flow/) might be useful.\n\n## Questions or Clarifications\n\nPlease, have a look at the [FAQ](FAQ.md) before you open an issue. Your question may already\nhave been answered. Should you still need to ask something? Feel free to open an issue and to\nexplain yourself.\n\n## Translations\n\nTranslations to other languages are highly encouraged. Each official translation will be held as a separate repository in the [MostlyAdequate organization](https://github.com/MostlyAdequate) and linked from the English version book.\nSince each translation is a different repository, we can also have different maintainers for each project.\n\n### Creating a New Translation Repo\n\nIn order to create a new translation, you need to follow these steps:\n\n* Fork the [main repo](https://github.com/MostlyAdequate/mostly-adequate-guide).\n* Add yourself to the watch list of the main repo, to keep up with changes.\n* When translating chapters, **create NEW files with suffix of your language**.\n  * For example, Spanish tranlation for `ch01.md` will be on `ch01-es.md`.\n* Open a [new issue](https://github.com/MostlyAdequate/mostly-adequate-guide/issues/new) and ask to be part of the organization.\n* Transfer the repo to the organization.\n* Merge new content from the main repo.\n* keep translating...\n* Rinse/repeat last two steps until the book is done.\n"
  },
  {
    "path": "FAQ.md",
    "content": "## FAQ\n\n- [Why are snippets written sometimes with semicolons and sometimes\n  without?](#why-are-snippets-written-sometimes-with-semicolons-and-sometimes-without)\n- [Aren't external libraries like _ (ramda) or $ (jquery) making calls impure?](#arent-external-libraries-like-_-ramda-or--jquery-making-calls-impure)\n- [What is the meaning of `f a` in signature?](#what-is-the-meaning-of-f-a-in-signature)\n- [Is there any \"real world\" examples available?](#is-there-any-real-world-examples-available)\n- [Why does the book uses ES5? Is any ES6 version available?](#why-does-the-book-uses-es5-is-any-es6-version-available)\n- [What the heck is that reduce function about?](#what-the-heck-is-that-reduce-function-about)\n- [Wouldn't you use a simplified English rather than the current style?](#wouldnt-you-use-a-simplified-english-rather-than-the-current-style)\n- [What is Either? What is Future? What is Task?](#what-is-either-what-is-future-what-is-task)\n- [Where do map, filter, compose ... methods come from?](#where-do-map-filter-compose--methods-come-from)\n\n### Why are snippets written sometimes with semicolons and sometimes without?\n\n> see [#6]\n\nThere are two schools in JavaScript, people who use them, and people who don't.  We've made the\nchoice here to use them, and now, we strive to be consistent with that choice. If some are\nmissing, please let us know and we will take care of the oversight.\n\n### Aren't external libraries like _ (ramda) or $ (jquery) making calls impure?\n\n> see [#50]\n\nThose dependencies are available as if they were in the global context, part of the language.\nSo, no, calls can still be considered as pure.\nFor further reading, have a look at [this article about\nCoEffects](http://tomasp.net/blog/2014/why-coeffects-matter/)\n\n### What is the meaning of `f a` in signature?\n\n> see [#62]\n\nIn a signature, like:\n\n`map :: Functor f => (a -> b) -> f a -> f b`\n\n`f` refers to a `functor` that could be, for instance, Maybe or IO. Thus, the signature abstracts\nthe choice of that functor by using a type variable which basically means that any functor\nmight be used where `f` stands as long as all `f` are of the same type (if the first `f a` in\nthe signature represents a `Maybe a`, then the second one **cannot refer to** an `IO b` but\nshould be a `Maybe b`. For instance:\n\n```javascript\nlet maybeString = Maybe.of(\"Patate\")\nlet f = function (x) { return x.length }\nlet maybeNumber = map(f, maybeString) // Maybe(6)\n\n// With the following 'refined' signature:\n// map :: (string -> number) -> Maybe string -> Maybe number\n```\n\n### Is there any \"real world\" examples available?\n\n> see [#77], [#192]\n\nShould you haven't reached it yet, you may have a look at the [Chapter\n6](https://github.com/MostlyAdequate/mostly-adequate-guide/blob/master/ch06.md) which presents a\nsimple flickr application.\nOther examples are likely to come later on. By the way, feel free to share with us your\nexperience!\n\n### Why does the book uses ES5? Is any ES6 version available?\n\n> see [#83], [#235]\n\nThe book aims at being widely accessible. It started before ES6 went out, and now, as the new\nstandard is being more and more accepted, we are considering making two separated editions with\nES5 and ES6. Members of the community are already working on the ES6 version (have a look to\n[#235] for more information).\n\n### What the heck is that reduce function about?\n\n> see [#109]\n\nReduce, accumulate, fold, inject are all usual functions in functional programming used to\ncombine the elements of a data structure successively. You might have a look at [this\ntalk](https://www.youtube.com/watch?v=JZSoPZUoR58&ab_channel=NewCircleTraining) to get some\nmore insights about the reduce function.\n\n### Wouldn't you use a simplified English rather than the current style?\n\n> see [#176]\n\nThe book is written in its own style which contributes to make it consistent as a whole. If\nyou're not familiar with English, see it as good training. Nevertheless, should you need help\nto understand the meaning sometimes, there are now [several\ntranslations](https://github.com/MostlyAdequate/mostly-adequate-guide/blob/master/TRANSLATIONS.md)\navailable that could probably help you.\n\n### What is Either? What is Future? What is Task?\n\n> see [#194]\n\nWe introduce all of those structures throughout the book. Therefore, you won't find any use of a\nstructure that hasn't previously be defined. Do not hesitate to read again some old parts if\nyou ever feel uncomfortable with those types.\nA glossary/vade mecum will come at the end to synthesize all these notions.\n\n### Where do map, filter, compose ... methods come from?\n\n> see [#198]\n\nMost of the time, those methods are defined in specific vendor libraries such as `ramda` or\n`underscore`. You should also have a look at [Appendix A](./appendix_a.md), \n[Appendix B](./appendix_b.md) and [Appendix C](./appendix_c.md) in which we define\nseveral implementations used for the exercises. Those functions are really\ncommon in functional programming and even though their implementations may vary a bit, their\nmeanings remain fairly consistent between libraries.\n\n\n[#6]: https://github.com/MostlyAdequate/mostly-adequate-guide/issues/6\n[#50]: https://github.com/MostlyAdequate/mostly-adequate-guide/issues/50\n[#62]: https://github.com/MostlyAdequate/mostly-adequate-guide/issues/62\n[#77]: https://github.com/MostlyAdequate/mostly-adequate-guide/issues/77\n[#83]: https://github.com/MostlyAdequate/mostly-adequate-guide/issues/83\n[#109]: https://github.com/MostlyAdequate/mostly-adequate-guide/issues/109\n[#176]: https://github.com/MostlyAdequate/mostly-adequate-guide/issues/176\n[#192]: https://github.com/MostlyAdequate/mostly-adequate-guide/issues/192\n[#194]: https://github.com/MostlyAdequate/mostly-adequate-guide/issues/194\n[#198]: https://github.com/MostlyAdequate/mostly-adequate-guide/issues/198\n[#235]: https://github.com/MostlyAdequate/mostly-adequate-guide/pull/235\n"
  },
  {
    "path": "LICENSE",
    "content": "* All text in this book is under:\n  Attribution-ShareAlike 4.0 International (CC BY-SA 4.0)\n  http://creativecommons.org/licenses/by-sa/4.0/\n\n* All artwork randomly stolen from google image search so the license doesn't apply. Please let me know if any artwork is yours and I'll give credit or remove.\n"
  },
  {
    "path": "README.md",
    "content": "[![cover](images/cover.png)](SUMMARY.md)\n\n## About this book\n\nThis is a book on the functional paradigm in general. We'll use the world's most popular functional programming language: JavaScript. Some may feel this is a poor choice as it's against the grain of the current culture which, at the moment, feels predominately imperative. However, I believe it is the best way to learn FP for several reasons:\n\n * **You likely use it every day at work.**\n\n    This makes it possible to practice and apply your acquired knowledge each day on real world programs rather than pet projects on nights and weekends in an esoteric FP language.\n\n\n * **We don't have to learn everything up front to start writing programs.**\n\n    In a pure functional language, you cannot log a variable or read a DOM node without using monads. Here we can cheat a little as we learn to purify our codebase. It's also easier to get started in this language since it's mixed paradigm and you can fall back on your current practices while there are gaps in your knowledge.\n\n\n * **The language is fully capable of writing top notch functional code.**\n\n    We have all the features we need to mimic a language like Scala or Haskell with the help of a tiny library or two. Object-oriented programming currently dominates the industry, but it's clearly awkward in JavaScript. It's akin to camping off of a highway or tap dancing in galoshes. We have to `bind` all over the place lest `this` change out from under us, we have various work arounds for the quirky behavior when the `new` keyword is forgotten, private members are only available via closures. To a lot of us, FP feels more natural anyways.\n\nThat said, typed functional languages will, without a doubt, be the best place to code in the style presented by this book. JavaScript will be our means of learning a paradigm, where you apply it is up to you. Luckily, the interfaces are mathematical and, as such, ubiquitous. You'll find yourself at home with Swiftz, Scalaz, Haskell, PureScript, and other mathematically inclined environments.\n\n\n## Read it Online\n\nFor a best reading experience, [read it online via Gitbook](https://mostly-adequate.gitbooks.io/mostly-adequate-guide/).\n\n- Quick-access side-bar\n- In-browser exercises\n- In-depth examples\n\n\n## Play Around with Code\n\nTo make the training efficient and not get too bored while I am telling you another story, make sure to play around with the concepts introduced in this book. Some can be tricky to catch at first and are better understood by getting your hands dirty.\nAll functions and algebraic data-structures presented in the book are gathered in the appendixes. The corresponding code is also available as an npm module:\n\n```bash\n$ npm i @mostly-adequate/support\n```\n\nAlternatively, exercises of each chapter are runnable and can be completed in your editor! For example, complete the `exercise_*.js` in `exercises/ch04` and then run:\n\n```bash\n$ npm run ch04\n```\n\n## Download it\n\nFind pre-generated **PDF** and **EPUB** as [build artifacts of the latest release](https://github.com/MostlyAdequate/mostly-adequate-guide/releases/latest).\n\n## Do it yourself\n\n> ⚠️ This project setup is now a bit old and thus, you may run into various issues when building this locally. We recommend to use node v10.22.1 and the latest version of Calibre if possible. \n\n### About the nodejs version\n\nAs the recommended node version (v10.22.1) is a bit old now, is more than likely that you do not have it installed on your system. You can have multiple versions of nodejs installed on your system using [nvm](https://github.com/nvm-sh/nvm). Refer to that project to install it and then you will be able to:\n\n - Install any node version that you need:\n```\nnvm install 10.22.1\nnvm install 20.2.0\n```\n - Then you will be able to switch between node versions:\n```\nnvm use 10.22.1\nnode -v // will show v10.22.1 \nnvm use 20.2.0\nnode -v // will show v20.2.0\n```\n\nAs this project has a .nvmrc file you can call `nvm install` and `nvm use` without specifying the node version:\n```\n// being anywhere inside this project\nnvm install\nnode -v // will show v10.22.1\n```\n\n\n### Complete sequence of commands\n\nConsidering the above about having nvm installed on your system, here is the complete sequence of commands to generate pdf and epub files by yourself:\n\n```\ngit clone https://github.com/MostlyAdequate/mostly-adequate-guide.git\ncd mostly-adequate-guide/\nnvm install\nnpm install\nnpm run setup\nnpm run generate-pdf\nnpm run generate-epub\n```\n\n> Note! To generate the ebook version you will need to install `ebook-convert`. [Installation instructions](https://gitbookio.gitbooks.io/documentation/content/build/ebookconvert.html).\n\n# Table of Contents\n\nSee [SUMMARY.md](SUMMARY.md)\n\n### Contributing\n\nSee [CONTRIBUTING.md](CONTRIBUTING.md)\n\n### Translations\n\nSee [TRANSLATIONS.md](TRANSLATIONS.md)\n\n### FAQ\n\nSee [FAQ.md](FAQ.md)\n\n\n\n# Plans for the future\n\n* **Part 1** (chapters 1-7) is a guide to the basics. I'm updating as I find errors since this is the initial draft. Feel free to help!\n* **Part 2** (chapters 8-13) address type classes like functors and monads all the way through to traversable. I hope to squeeze in transformers and a pure application.\n* **Part 3** (chapters 14+) will start to dance the fine line between practical programming and academic absurdity. We'll look at comonads, f-algebras, free monads, yoneda, and other categorical constructs.\n\n\n---\n\n\n<p align=\"center\">\n  <a rel=\"license\" href=\"http://creativecommons.org/licenses/by-sa/4.0/\">\n    <img alt=\"Creative Commons License\" style=\"border-width:0\" src=\"https://i.creativecommons.org/l/by-sa/4.0/88x31.png\" />\n  </a>\n  <br />\n  This work is licensed under a <a rel=\"license\" href=\"http://creativecommons.org/licenses/by-sa/4.0/\">Creative Commons Attribution-ShareAlike 4.0 International License</a>.\n</p>\n"
  },
  {
    "path": "SUMMARY.md",
    "content": "# Summary\n\n* [Chapter 01: What Ever Are We Doing?](ch01.md)\n  * [Introductions](ch01.md#introductions)\n  * [A Brief Encounter](ch01.md#a-brief-encounter)\n* [Chapter 02: First Class Functions](ch02.md)\n  * [A Quick Review](ch02.md#a-quick-review)\n  * [Why Favor First Class?](ch02.md#why-favor-first-class)\n* [Chapter 03: Pure Happiness with Pure Functions](ch03.md)\n  * [Oh to Be Pure Again](ch03.md#oh-to-be-pure-again)\n  * [Side Effects May Include...](ch03.md#side-effects-may-include)\n  * [8th Grade Math](ch03.md#8th-grade-math)\n  * [The Case for Purity](ch03.md#the-case-for-purity)\n  * [In Summary](ch03.md#in-summary)\n* [Chapter 04: Currying](ch04.md)\n  * [Can't Live If Livin' Is without You](ch04.md#cant-live-if-livin-is-without-you)\n  * [More Than a Pun / Special Sauce](ch04.md#more-than-a-pun--special-sauce)\n  * [In Summary](ch04.md#in-summary)\n  * [Exercises](ch04.md#exercises)\n* [Chapter 05: Coding by Composing](ch05.md)\n  * [Functional Husbandry](ch05.md#functional-husbandry)\n  * [Pointfree](ch05.md#pointfree)\n  * [Debugging](ch05.md#debugging)\n  * [Category Theory](ch05.md#category-theory)\n  * [In Summary](ch05.md#in-summary)\n  * [Exercises](ch05.md#exercises)\n* [Chapter 06: Example Application](ch06.md)\n  * [Declarative Coding](ch06.md#declarative-coding)\n  * [A Flickr of Functional Programming](ch06.md#a-flickr-of-functional-programming)\n  * [A Principled Refactor](ch06.md#a-principled-refactor)\n  * [In Summary](ch06.md#in-summary)\n* [Chapter 07: Hindley-Milner and Me](ch07.md)\n  * [What's Your Type?](ch07.md#whats-your-type)\n  * [Tales from the Cryptic](ch07.md#tales-from-the-cryptic)\n  * [Narrowing the Possibility](ch07.md#narrowing-the-possibility)\n  * [Free as in Theorem](ch07.md#free-as-in-theorem)\n  * [Constraints](ch07.md#constraints)\n  * [In Summary](ch07.md#in-summary)\n* [Chapter 08: Tupperware](ch08.md)\n  * [The Mighty Container](ch08.md#the-mighty-container)\n  * [My First Functor](ch08.md#my-first-functor)\n  * [Schrödinger's Maybe](ch08.md#schrödingers-maybe)\n  * [Use Cases](ch08.md#use-cases)\n  * [Releasing the Value](ch08.md#releasing-the-value)\n  * [Pure Error Handling](ch08.md#pure-error-handling)\n  * [Old McDonald Had Effects...](ch08.md#old-mcdonald-had-effects)\n  * [Asynchronous Tasks](ch08.md#asynchronous-tasks)\n  * [A Spot of Theory](ch08.md#a-spot-of-theory)\n  * [In Summary](ch08.md#in-summary)\n  * [Exercises](ch08.md#exercises)\n* [Chapter 09: Monadic Onions](ch09.md)\n  * [Pointy Functor Factory](ch09.md#pointy-functor-factory)\n  * [Mixing Metaphors](ch09.md#mixing-metaphors)\n  * [My Chain Hits My Chest](ch09.md#my-chain-hits-my-chest)\n  * [Power Trip](ch09.md#power-trip)\n  * [Theory](ch09.md#theory)\n  * [In Summary](ch09.md#in-summary)\n  * [Exercises](ch09.md#exercises)\n* [Chapter 10: Applicative Functors](ch10.md)\n  * [Applying Applicatives](ch10.md#applying-applicatives)\n  * [Ships in Bottles](ch10.md#ships-in-bottles)\n  * [Coordination Motivation](ch10.md#coordination-motivation)\n  * [Bro, Do You Even Lift?](ch10.md#bro-do-you-even-lift)\n  * [Operators](ch10.md#operators)\n  * [Free Can Openers](ch10.md#free-can-openers)\n  * [Laws](ch10.md#laws)\n  * [In Summary](ch10.md#in-summary)\n  * [Exercises](ch10.md#exercises)\n* [Chapter 11: Transform Again, Naturally](ch11.md)\n  * [Curse This Nest](ch11.md#curse-this-nest)\n  * [A Situational Comedy](ch11.md#a-situational-comedy)\n  * [All Natural](ch11.md#all-natural)\n  * [Principled Type Conversions](ch11.md#principled-type-conversions)\n  * [Feature Envy](ch11.md#feature-envy)\n  * [Isomorphic JavaScript](ch11.md#isomorphic-javascript)\n  * [A Broader Definition](ch11.md#a-broader-definition)\n  * [One Nesting Solution](ch11.md#one-nesting-solution)\n  * [In Summary](ch11.md#in-summary)\n  * [Exercises](ch11.md#exercises)\n* [Chapter 12: Traversing the Stone](ch12.md)\n  * [Types n' Types](ch12.md#types-n-types)\n  * [Type Feng Shui](ch12.md#type-feng-shui)\n  * [Effect Assortment](ch12.md#effect-assortment)\n  * [Waltz of the Types](ch12.md#waltz-of-the-types)\n  * [No Law and Order](ch12.md#no-law-and-order)\n  * [In Summary](ch12.md#in-summary)\n  * [Exercises](ch12.md#exercises)\n* [Chapter 13: Monoids bring it all together](ch13.md)\n  * [Wild combination](ch13.md#wild-combination)\n  * [Abstracting addition](ch13.md#abstracting-addition)\n  * [All my favourite functors are semigroups.](ch13.md#all-my-favourite-functors-are-semigroups)\n  * [Monoids for nothing](ch13.md#monoids-for-nothing)\n  * [Folding down the house](ch13.md#folding-down-the-house)\n  * [Not quite a monoid](ch13.md#not-quite-a-monoid)\n  * [Grand unifying theory](ch13.md#grand-unifying-theory)\n  * [Group theory or Category theory?](ch13.md#group-theory-or-category-theory)\n  * [In summary](ch13.md#in-summary)\n  * [Exercises](ch13.md#exercises)\n* [Appendix A: Essential Functions Support](appendix_a.md)\n  * [always](appendix_a.md#always)\n  * [compose](appendix_a.md#compose)\n  * [curry](appendix_a.md#curry)\n  * [either](appendix_a.md#either)\n  * [identity](appendix_a.md#identity)\n  * [inspect](appendix_a.md#inspect)\n  * [left](appendix_a.md#left)\n  * [liftA2](appendix_a.md#lifta2)\n  * [liftA3](appendix_a.md#lifta3)\n  * [maybe](appendix_a.md#maybe)\n  * [nothing](appendix_a.md#nothing)\n  * [reject](appendix_a.md#reject)\n* [Appendix B: Algebraic Structures Support](appendix_b.md)\n  * [Compose](appendix_b.md#compose)\n  * [Either](appendix_b.md#either)\n  * [Identity](appendix_b.md#identity)\n  * [IO](appendix_b.md#io)\n  * [List](appendix_b.md#list)\n  * [Map](appendix_b.md#map)\n  * [Maybe](appendix_b.md#maybe)\n  * [Task](appendix_b.md#task)\n* [Appendix C: Pointfree Utilities](appendix_c.md)\n  * [add](appendix_c.md#add)\n  * [append](appendix_c.md#append)\n  * [chain](appendix_c.md#chain)\n  * [concat](appendix_c.md#concat)\n  * [eq](appendix_c.md#eq)\n  * [filter](appendix_c.md#filter)\n  * [flip](appendix_c.md#flip)\n  * [forEach](appendix_c.md#foreach)\n  * [head](appendix_c.md#head)\n  * [intercalate](appendix_c.md#intercalate)\n  * [join](appendix_c.md#join)\n  * [last](appendix_c.md#last)\n  * [map](appendix_c.md#map)\n  * [match](appendix_c.md#match)\n  * [prop](appendix_c.md#prop)\n  * [reduce](appendix_c.md#reduce)\n  * [replace](appendix_c.md#replace)\n  * [reverse](appendix_c.md#reverse)\n  * [safeHead](appendix_c.md#safehead)\n  * [safeLast](appendix_c.md#safelast)\n  * [safeProp](appendix_c.md#safeprop)\n  * [sequence](appendix_c.md#sequence)\n  * [sortBy](appendix_c.md#sortby)\n  * [split](appendix_c.md#split)\n  * [take](appendix_c.md#take)\n  * [toLowerCase](appendix_c.md#tolowercase)\n  * [toString](appendix_c.md#tostring)\n  * [toUpperCase](appendix_c.md#touppercase)\n  * [traverse](appendix_c.md#traverse)\n  * [unsafePerformIO](appendix_c.md#unsafeperformio)\n"
  },
  {
    "path": "TRANSLATIONS.md",
    "content": "# Available Translations\n\n* [中文版 (Chinese)](https://github.com/llh911001/mostly-adequate-guide-chinese)  by Linghao Li @llh911001\n* [Русский (Russian)](https://github.com/MostlyAdequate/mostly-adequate-guide-ru)  by Maksim Filippov @maksimf\n* [Українська (Ukrainian)](https://github.com/ivanzusko/mostly-adequate-guide-uk) by Ivan Zusko @ivanzusko\n* [Français (French)](https://github.com/MostlyAdequate/mostly-adequate-guide-fr) by Benkort Matthias @KtorZ\n* [Português (Portuguese)](https://github.com/MostlyAdequate/mostly-adequate-guide-pt-BR) by Palmer Oliveira @expalmer\n* [Español (Spanish)](https://github.com/MostlyAdequate/mostly-adequate-guide-es) by Gustavo Marin @guumaster\n* [Italiano (Italian)](https://github.com/MostlyAdequate/mostly-adequate-guide-it) by Elia Gentili @eliagentili\n* [한국어 (Korean)](https://github.com/enshahar/mostly-adequate-guide-kr) by Frank Hyunsok Oh @enshahar\n* [bahasa Indonesia (Indonesian)](https://github.com/MostlyAdequate/mostly-adequate-guide-id) by Ahmad Naufal Mukhtar @anaufalm\n\n\n## Creating new Translations\n\nSee [Creating new translations](CONTRIBUTING.md#Translations)\n"
  },
  {
    "path": "appendix_a.md",
    "content": "# Appendix A: Essential Functions Support\n\nIn this appendix, you'll find some basic JavaScript implementations of various functions\ndescribed in the book. Keep in mind that these implementations may not be the fastest or the\nmost efficient implementation out there; they *solely serve an educational purpose*.\n\nIn order to find functions that are more production-ready, have a peek at\n[ramda](https://ramdajs.com/), [lodash](https://lodash.com/), or [folktale](http://folktale.origamitower.com/).\n\nNote that some functions also refer to algebraic structures defined in the [Appendix B](./appendix_b.md)\n\n## always\n\n```js\n// always :: a -> b -> a\nconst always = curry((a, b) => a);\n```\n\n\n## compose\n\n```js\n// compose :: ((y -> z), (x -> y),  ..., (a -> b)) -> a -> z\nconst compose = (...fns) => (...args) => fns.reduceRight((res, fn) => [fn.call(null, ...res)], args)[0];\n```\n\n\n## curry\n\n```js\n// curry :: ((a, b, ...) -> c) -> a -> b -> ... -> c\nfunction curry(fn) {\n  const arity = fn.length;\n\n  return function $curry(...args) {\n    if (args.length < arity) {\n      return $curry.bind(null, ...args);\n    }\n\n    return fn.call(null, ...args);\n  };\n}\n```\n\n\n## either\n\n```js\n// either :: (a -> c) -> (b -> c) -> Either a b -> c\nconst either = curry((f, g, e) => {\n  if (e.isLeft) {\n    return f(e.$value);\n  }\n\n  return g(e.$value);\n});\n```\n\n\n## identity\n\n```js\n// identity :: x -> x\nconst identity = x => x;\n```\n\n\n## inspect\n\n```js\n// inspect :: a -> String\nconst inspect = (x) => {\n  if (x && typeof x.inspect === 'function') {\n    return x.inspect();\n  }\n\n  function inspectFn(f) {\n    return f.name ? f.name : f.toString();\n  }\n\n  function inspectTerm(t) {\n    switch (typeof t) {\n      case 'string':\n        return `'${t}'`;\n      case 'object': {\n        const ts = Object.keys(t).map(k => [k, inspect(t[k])]);\n        return `{${ts.map(kv => kv.join(': ')).join(', ')}}`;\n      }\n      default:\n        return String(t);\n    }\n  }\n\n  function inspectArgs(args) {\n    return Array.isArray(args) ? `[${args.map(inspect).join(', ')}]` : inspectTerm(args);\n  }\n\n  return (typeof x === 'function') ? inspectFn(x) : inspectArgs(x);\n};\n```\n\n\n## left\n\n```js\n// left :: a -> Either a b\nconst left = a => new Left(a);\n```\n\n\n## liftA2\n\n```js\n// liftA2 :: (Applicative f) => (a1 -> a2 -> b) -> f a1 -> f a2 -> f b\nconst liftA2 = curry((fn, a1, a2) => a1.map(fn).ap(a2));\n```\n\n\n## liftA3\n\n```js\n// liftA3 :: (Applicative f) => (a1 -> a2 -> a3 -> b) -> f a1 -> f a2 -> f a3 -> f b\nconst liftA3 = curry((fn, a1, a2, a3) => a1.map(fn).ap(a2).ap(a3));\n```\n\n\n## maybe\n\n```js\n// maybe :: b -> (a -> b) -> Maybe a -> b\nconst maybe = curry((v, f, m) => {\n  if (m.isNothing) {\n    return v;\n  }\n\n  return f(m.$value);\n});\n```\n\n\n## nothing\n\n```js\n// nothing :: Maybe a\nconst nothing = Maybe.of(null);\n```\n\n\n## reject \n\n```js\n// reject :: a -> Task a b\nconst reject = a => Task.rejected(a);\n```\n"
  },
  {
    "path": "appendix_b.md",
    "content": "# Appendix B: Algebraic Structures Support\n\nIn this appendix, you'll find some basic JavaScript implementations of various algebraic\nstructures described in the book. Keep in mind that these implementations may not be the fastest or the\nmost efficient implementation out there; they *solely serve an educational purpose*.\n\nIn order to find structures that are more production-ready, have a peek at [folktale](http://folktale.origamitower.com/)\nor [fantasy-land](https://github.com/fantasyland).\n\nNote that some methods also refer to functions defined in the [Appendix A](./appendix_a.md)\n\n## Compose\n\n```js\nconst createCompose = curry((F, G) => class Compose {\n  constructor(x) {\n    this.$value = x;\n  }\n\n  [util.inspect.custom]() {\n    return `Compose(${inspect(this.$value)})`;\n  }\n\n  // ----- Pointed (Compose F G)\n  static of(x) {\n    return new Compose(F(G(x)));\n  }\n\n  // ----- Functor (Compose F G)\n  map(fn) {\n    return new Compose(this.$value.map(x => x.map(fn)));\n  }\n\n  // ----- Applicative (Compose F G)\n  ap(f) {\n    return f.map(this.$value);\n  }\n});\n```\n\n\n## Either\n\n```js\nclass Either {\n  constructor(x) {\n    this.$value = x;\n  }\n\n  // ----- Pointed (Either a)\n  static of(x) {\n    return new Right(x);\n  }\n}\n```\n\n#### Left\n\n```js\nclass Left extends Either {\n  get isLeft() {\n    return true;\n  }\n\n  get isRight() {\n    return false;\n  }\n\n  static of(x) {\n    throw new Error('`of` called on class Left (value) instead of Either (type)');\n  }\n\n  [util.inspect.custom]() {\n    return `Left(${inspect(this.$value)})`;\n  }\n\n  // ----- Functor (Either a)\n  map() {\n    return this;\n  }\n\n  // ----- Applicative (Either a)\n  ap() {\n    return this;\n  }\n\n  // ----- Monad (Either a)\n  chain() {\n    return this;\n  }\n\n  join() {\n    return this;\n  }\n\n  // ----- Traversable (Either a)\n  sequence(of) {\n    return of(this);\n  }\n\n  traverse(of, fn) {\n    return of(this);\n  }\n}\n```\n\n#### Right\n\n```js\nclass Right extends Either {\n  get isLeft() {\n    return false;\n  }\n\n  get isRight() {\n    return true;\n  }\n\n  static of(x) {\n    throw new Error('`of` called on class Right (value) instead of Either (type)');\n  }\n\n  [util.inspect.custom]() {\n    return `Right(${inspect(this.$value)})`;\n  }\n\n  // ----- Functor (Either a)\n  map(fn) {\n    return Either.of(fn(this.$value));\n  }\n\n  // ----- Applicative (Either a)\n  ap(f) {\n    return f.map(this.$value);\n  }\n\n  // ----- Monad (Either a)\n  chain(fn) {\n    return fn(this.$value);\n  }\n\n  join() {\n    return this.$value;\n  }\n\n  // ----- Traversable (Either a)\n  sequence(of) {\n    return this.traverse(of, identity);\n  }\n\n  traverse(of, fn) {\n    return fn(this.$value).map(Either.of);\n  }\n}\n```\n\n## Identity\n\n```js\nclass Identity {\n  constructor(x) {\n    this.$value = x;\n  }\n\n  [util.inspect.custom]() {\n    return `Identity(${inspect(this.$value)})`;\n  }\n\n  // ----- Pointed Identity\n  static of(x) {\n    return new Identity(x);\n  }\n\n  // ----- Functor Identity\n  map(fn) {\n    return Identity.of(fn(this.$value));\n  }\n\n  // ----- Applicative Identity\n  ap(f) {\n    return f.map(this.$value);\n  }\n\n  // ----- Monad Identity\n  chain(fn) {\n    return this.map(fn).join();\n  }\n\n  join() {\n    return this.$value;\n  }\n\n  // ----- Traversable Identity\n  sequence(of) {\n    return this.traverse(of, identity);\n  }\n\n  traverse(of, fn) {\n    return fn(this.$value).map(Identity.of);\n  }\n}\n```\n\n## IO\n\n```js\nclass IO {\n  constructor(fn) {\n    this.unsafePerformIO = fn;\n  }\n\n  [util.inspect.custom]() {\n    return 'IO(?)';\n  }\n\n  // ----- Pointed IO\n  static of(x) {\n    return new IO(() => x);\n  }\n\n  // ----- Functor IO\n  map(fn) {\n    return new IO(compose(fn, this.unsafePerformIO));\n  }\n\n  // ----- Applicative IO\n  ap(f) {\n    return this.chain(fn => f.map(fn));\n  }\n\n  // ----- Monad IO\n  chain(fn) {\n    return this.map(fn).join();\n  }\n\n  join() {\n    return new IO(() => this.unsafePerformIO().unsafePerformIO());\n  }\n}\n```\n\n## List\n\n```js\nclass List {\n  constructor(xs) {\n    this.$value = xs;\n  }\n\n  [util.inspect.custom]() {\n    return `List(${inspect(this.$value)})`;\n  }\n\n  concat(x) {\n    return new List(this.$value.concat(x));\n  }\n\n  // ----- Pointed List\n  static of(x) {\n    return new List([x]);\n  }\n\n  // ----- Functor List\n  map(fn) {\n    return new List(this.$value.map(fn));\n  }\n\n  // ----- Traversable List\n  sequence(of) {\n    return this.traverse(of, identity);\n  }\n\n  traverse(of, fn) {\n    return this.$value.reduce(\n      (f, a) => fn(a).map(b => bs => bs.concat(b)).ap(f),\n      of(new List([])),\n    );\n  }\n}\n```\n\n\n## Map\n\n```js\nclass Map {\n  constructor(x) {\n    this.$value = x;\n  }\n\n  [util.inspect.custom]() {\n    return `Map(${inspect(this.$value)})`;\n  }\n\n  insert(k, v) {\n    const singleton = {};\n    singleton[k] = v;\n    return Map.of(Object.assign({}, this.$value, singleton));\n  }\n\n  reduceWithKeys(fn, zero) {\n    return Object.keys(this.$value)\n      .reduce((acc, k) => fn(acc, this.$value[k], k), zero);\n  }\n\n  // ----- Functor (Map a)\n  map(fn) {\n    return this.reduceWithKeys(\n      (m, v, k) => m.insert(k, fn(v)),\n      new Map({}),\n    );\n  }\n\n  // ----- Traversable (Map a)\n  sequence(of) {\n    return this.traverse(of, identity);\n  }\n\n  traverse(of, fn) {\n    return this.reduceWithKeys(\n      (f, a, k) => fn(a).map(b => m => m.insert(k, b)).ap(f),\n      of(new Map({})),\n    );\n  }\n}\n```\n\n\n## Maybe\n\n> Note that `Maybe` could also be defined in a similar fashion as we did for `Either` with two \n> child classes `Just` and `Nothing`. This is simply a different flavor.\n\n```js\nclass Maybe {\n  get isNothing() {\n    return this.$value === null || this.$value === undefined;\n  }\n\n  get isJust() {\n    return !this.isNothing;\n  }\n\n  constructor(x) {\n    this.$value = x;\n  }\n\n  [util.inspect.custom]() {\n    return this.isNothing ? 'Nothing' : `Just(${inspect(this.$value)})`;\n  }\n\n  // ----- Pointed Maybe\n  static of(x) {\n    return new Maybe(x);\n  }\n\n  // ----- Functor Maybe\n  map(fn) {\n    return this.isNothing ? this : Maybe.of(fn(this.$value));\n  }\n\n  // ----- Applicative Maybe\n  ap(f) {\n    return this.isNothing ? this : f.map(this.$value);\n  }\n\n  // ----- Monad Maybe\n  chain(fn) {\n    return this.map(fn).join();\n  }\n\n  join() {\n    return this.isNothing ? this : this.$value;\n  }\n\n  // ----- Traversable Maybe\n  sequence(of) {\n    return this.traverse(of, identity);\n  }\n\n  traverse(of, fn) {\n    return this.isNothing ? of(this) : fn(this.$value).map(Maybe.of);\n  }\n}\n```\n\n## Task\n\n```js\nclass Task {\n  constructor(fork) {\n    this.fork = fork;\n  }\n\n  [util.inspect.custom]() {\n    return 'Task(?)';\n  }\n\n  static rejected(x) {\n    return new Task((reject, _) => reject(x));\n  }\n\n  // ----- Pointed (Task a)\n  static of(x) {\n    return new Task((_, resolve) => resolve(x));\n  }\n\n  // ----- Functor (Task a)\n  map(fn) {\n    return new Task((reject, resolve) => this.fork(reject, compose(resolve, fn)));\n  }\n\n  // ----- Applicative (Task a)\n  ap(f) {\n    return this.chain(fn => f.map(fn));\n  }\n\n  // ----- Monad (Task a)\n  chain(fn) {\n    return new Task((reject, resolve) => this.fork(reject, x => fn(x).fork(reject, resolve)));\n  }\n\n  join() {\n    return this.chain(identity);\n  }\n}\n```\n"
  },
  {
    "path": "appendix_c.md",
    "content": "# Appendix C: Pointfree Utilities\n\nIn this appendix, you'll find pointfree versions of rather classic JavaScript functions\ndescribed in the book. All of the following functions are seemingly available in exercises, as\npart of the global context. Keep in mind that these implementations may not be the fastest or\nthe most efficient implementation out there; they *solely serve an educational purpose*.\n\nIn order to find functions that are more production-ready, have a peek at\n[ramda](https://ramdajs.com/), [lodash](https://lodash.com/), or [folktale](http://folktale.origamitower.com/).\n\nNote that functions refer to the `curry` & `compose` functions defined in [Appendix A](./appendix_a.md)\n\n## add \n\n```js\n// add :: Number -> Number -> Number\nconst add = curry((a, b) => a + b);\n```\n\n## append\n\n```js\n// append :: String -> String -> String\nconst append = flip(concat);\n```\n\n## chain\n\n```js\n// chain :: Monad m => (a -> m b) -> m a -> m b\nconst chain = curry((fn, m) => m.chain(fn));\n```\n\n## concat\n\n```js\n// concat :: String -> String -> String\nconst concat = curry((a, b) => a.concat(b));\n```\n\n## eq\n\n```js\n// eq :: Eq a => a -> a -> Boolean\nconst eq = curry((a, b) => a === b);\n```\n\n## filter\n\n```js\n// filter :: (a -> Boolean) -> [a] -> [a]\nconst filter = curry((fn, xs) => xs.filter(fn));\n```\n\n## flip\n\n```js\n// flip :: (a -> b -> c) -> b -> a -> c\nconst flip = curry((fn, a, b) => fn(b, a));\n```\n\n## forEach \n\n```js\n// forEach :: (a -> ()) -> [a] -> ()\nconst forEach = curry((fn, xs) => xs.forEach(fn));\n```\n\n## head\n\n```js\n// head :: [a] -> a\nconst head = xs => xs[0];\n```\n\n## intercalate\n\n```js\n// intercalate :: String -> [String] -> String\nconst intercalate = curry((str, xs) => xs.join(str));\n```\n\n## join\n\n```js\n// join :: Monad m => m (m a) -> m a\nconst join = m => m.join();\n```\n\n## last\n\n```js\n// last :: [a] -> a\nconst last = xs => xs[xs.length - 1];\n```\n\n## map\n\n```js\n// map :: Functor f => (a -> b) -> f a -> f b\nconst map = curry((fn, f) => f.map(fn));\n```\n\n## match\n\n```js\n// match :: RegExp -> String -> Boolean\nconst match = curry((re, str) => re.test(str));\n```\n\n## prop \n\n```js\n// prop :: String -> Object -> a\nconst prop = curry((p, obj) => obj[p]);\n```\n\n## reduce\n\n```js\n// reduce :: (b -> a -> b) -> b -> [a] -> b\nconst reduce = curry((fn, zero, xs) => xs.reduce(fn, zero));\n```\n\n## replace\n\n```js\n// replace :: RegExp -> String -> String -> String\nconst replace = curry((re, rpl, str) => str.replace(re, rpl));\n```\n\n## reverse\n\n```js\n// reverse :: [a] -> [a]\nconst reverse = x => (Array.isArray(x) ? x.reverse() : x.split('').reverse().join(''));\n```\n\n## safeHead\n\n```js\n// safeHead :: [a] -> Maybe a\nconst safeHead = compose(Maybe.of, head);\n```\n\n## safeLast\n\n```js\n// safeLast :: [a] -> Maybe a\nconst safeLast = compose(Maybe.of, last);\n```\n\n## safeProp\n\n```js\n// safeProp :: String -> Object -> Maybe a\nconst safeProp = curry((p, obj) => compose(Maybe.of, prop(p))(obj));\n```\n\n## sequence\n\n```js\n// sequence :: (Applicative f, Traversable t) => (a -> f a) -> t (f a) -> f (t a)\nconst sequence = curry((of, f) => f.sequence(of));\n```\n\n## sortBy\n\n```js\n// sortBy :: Ord b => (a -> b) -> [a] -> [a]\nconst sortBy = curry((fn, xs) => xs.sort((a, b) => {\n  if (fn(a) === fn(b)) {\n    return 0;\n  }\n\n  return fn(a) > fn(b) ? 1 : -1;\n}));\n```\n\n## split\n\n```js\n// split :: String -> String -> [String]\nconst split = curry((sep, str) => str.split(sep));\n```\n\n## take\n\n```js\n// take :: Number -> [a] -> [a]\nconst take = curry((n, xs) => xs.slice(0, n));\n```\n\n## toLowerCase\n\n```js\n// toLowerCase :: String -> String\nconst toLowerCase = s => s.toLowerCase();\n```\n\n## toString\n\n```js\n// toString :: a -> String\nconst toString = String;\n```\n\n## toUpperCase\n\n```js\n// toUpperCase :: String -> String\nconst toUpperCase = s => s.toUpperCase();\n```\n\n## traverse\n\n```js\n// traverse :: (Applicative f, Traversable t) => (a -> f a) -> (a -> f b) -> t a -> f (t b)\nconst traverse = curry((of, fn, f) => f.traverse(of, fn));\n```\n\n## unsafePerformIO\n\n```js\n// unsafePerformIO :: IO a -> a\nconst unsafePerformIO = io => io.unsafePerformIO();\n```\n"
  },
  {
    "path": "book.json",
    "content": "{\n  \"gitbook\": \"3.2.2\",\n  \"root\": \".\",\n  \"title\": \"Professor Frisby's Mostly Adequate Guide to Functional Programming\",\n  \"cover\": \"images/cover.png\",\n  \"plugins\": [\n    \"exercises@git+https://github.com/MostlyAdequate/plugin-exercises.git\",\n    \"include-codeblock@3.2.2\"\n  ]\n}\n\n"
  },
  {
    "path": "ch01.md",
    "content": "# Chapter 01: What Ever Are We Doing?\n\n## Introductions\n\nHi there! I'm Professor Franklin Frisby. Pleased to make your acquaintance. We'll be spending some time together, as I'm supposed to teach you a bit about functional programming. But enough about me, what about you? I'm hoping that you're at least a bit familiar with the JavaScript language, have a teensy bit of Object-Oriented experience, and fancy yourself a working class programmer. You don't need to have a PhD in Entomology, you just need to know how to find and kill some bugs.\n\nI won't assume that you have any previous functional programming knowledge, because we both know what happens when you assume. I will, however, expect you to have run into some of the unfavorable situations that arise when working with mutable state, unrestricted side effects, and unprincipled design. Now that we've been properly introduced, let's get on with it.\n\nThe purpose of this chapter is to give you a feel for what we're after when we write functional programs. In order to be able to understand the following chapters, we must have some idea about what makes a program *functional*. Otherwise we'll find ourselves scribbling aimlessly, avoiding objects at all costs - a clumsy endeavor indeed. We need a clear bullseye to hurl our code at, some celestial compass for when the waters get rough.\n\nNow, there are some general programming principles - various acronymic credos that guide us through the dark tunnels of any application: DRY (don't repeat yourself), YAGNI (ya ain't gonna need it), loose coupling high cohesion, the principle of least surprise, single responsibility, and so on.\n\nI won't belabor you by listing each and every guideline I've heard throughout the years... The point of the matter is that they hold up in a functional setting, although they're merely tangential to our ultimate goal. What I'd like you to get a feel for now, before we get any further, is our intention when we poke and prod at the keyboard; our functional Xanadu.\n\n<!--BREAK-->\n\n## A Brief Encounter\n\nLet's start with a touch of insanity. Here is a seagull application. When flocks conjoin they become a larger flock, and when they breed, they increase by the number of seagulls with whom they're breeding. Now, this is not intended to be good Object-Oriented code, mind you, it is here to highlight the perils of our modern, assignment based approach. Behold:\n\n```js\nclass Flock {\n  constructor(n) {\n    this.seagulls = n;\n  }\n\n  conjoin(other) {\n    this.seagulls += other.seagulls;\n    return this;\n  }\n\n  breed(other) {\n    this.seagulls = this.seagulls * other.seagulls;\n    return this;\n  }\n}\n\nconst flockA = new Flock(4);\nconst flockB = new Flock(2);\nconst flockC = new Flock(0);\nconst result = flockA\n  .conjoin(flockC)\n  .breed(flockB)\n  .conjoin(flockA.breed(flockB))\n  .seagulls;\n// 32\n```\n\nWho on earth would craft such a ghastly abomination? It is unreasonably difficult to keep track of the mutating internal state. And, good heavens, the answer is even incorrect! It should have been `16`, but `flockA` wound up permanently altered in the process. Poor `flockA`. This is anarchy in the I.T.! This is wild animal arithmetic!\n\nIf you don't understand this program, it's okay, neither do I. The point to remember here is that state and mutable values are hard to follow, even in such a small example.\n\nLet's try again, this time using a more functional approach:\n\n```js\nconst conjoin = (flockX, flockY) => flockX + flockY;\nconst breed = (flockX, flockY) => flockX * flockY;\n\nconst flockA = 4;\nconst flockB = 2;\nconst flockC = 0;\nconst result =\n    conjoin(breed(flockB, conjoin(flockA, flockC)), breed(flockA, flockB));\n// 16\n```\n\nWell, this time we got the right answer. With much less code. The function nesting is a tad confusing... (we'll remedy this situation in ch5). It's better, but let's dig a little bit deeper. There are benefits to calling a spade a spade. Had we scrutinized our custom functions more closely, we would have discovered that we're just working with simple addition (`conjoin`) and multiplication (`breed`).\n\nThere's really nothing special at all about these two functions other than their names. Let's rename our custom functions to `multiply` and `add` in order to reveal their true identities.\n\n```js\nconst add = (x, y) => x + y;\nconst multiply = (x, y) => x * y;\n\nconst flockA = 4;\nconst flockB = 2;\nconst flockC = 0;\nconst result =\n    add(multiply(flockB, add(flockA, flockC)), multiply(flockA, flockB));\n// 16\n```\nAnd with that, we gain the knowledge of the ancients:\n\n```js\n// associative\nadd(add(x, y), z) === add(x, add(y, z));\n\n// commutative\nadd(x, y) === add(y, x);\n\n// identity\nadd(x, 0) === x;\n\n// distributive\nmultiply(x, add(y,z)) === add(multiply(x, y), multiply(x, z));\n```\n\nAh yes, those old faithful mathematical properties should come in handy. Don't worry if you didn't know them right off the top of your head. For a lot of us, it's been a while since we learned about these laws of arithmetic. Let's see if we can use these properties to simplify our little seagull program.\n\n```js\n// Original line\nadd(multiply(flockB, add(flockA, flockC)), multiply(flockA, flockB));\n\n// Apply the identity property to remove the extra add\n// (add(flockA, flockC) == flockA)\nadd(multiply(flockB, flockA), multiply(flockA, flockB));\n\n// Apply distributive property to achieve our result\nmultiply(flockB, add(flockA, flockA));\n```\n\nBrilliant! We didn't have to write a lick of custom code other than our calling function. We include `add` and `multiply` definitions here for completeness, but there is really no need to write them - we surely have an `add` and `multiply` provided by some existing library.\n\nYou may be thinking \"how very strawman of you to put such a mathy example up front\". Or \"real programs are not this simple and cannot be reasoned about in such a way.\" I've chosen this example because most of us already know about addition and multiplication, so it's easy to see how math is very useful for us here.\n\nDon't despair - throughout this book, we'll sprinkle in some category theory, set theory, and lambda calculus and write real world examples that achieve the same elegant simplicity and results as our flock of seagulls example. You needn't be a mathematician either. It will feel natural and easy, just like you were using a \"normal\" framework or API.\n\nIt may come as a surprise to hear that we can write full, everyday applications along the lines of the functional analog above. Programs that have sound properties. Programs that are terse, yet easy to reason about. Programs that don't reinvent the wheel at every turn. Lawlessness is good if you're a criminal, but in this book, we'll want to acknowledge and obey the laws of math.\n\nWe'll want to use a theory where every piece tends to fit together so politely. We'll want to represent our specific problem in terms of generic, composable bits and then exploit their properties for our own selfish benefit. It will take a bit more discipline than the \"anything goes\" approach of imperative programming (we'll go over the precise definition of \"imperative\" later in the book, but for now consider it anything other than functional programming). The payoff of working within a principled, mathematical framework will truly astound you.\n\nWe've seen a flicker of our functional northern star, but there are a few concrete concepts to grasp before we can really begin our journey.\n\n[Chapter 02: First Class Functions](ch02.md)\n"
  },
  {
    "path": "ch02.md",
    "content": "# Chapter 02: First Class Functions\n\n## A Quick Review\nWhen we say functions are \"first class\", we mean they are just like everyone else... so in other words a normal class. We can treat functions like any other data type and there is nothing particularly special about them - they may be stored in arrays, passed around as function parameters, assigned to variables, and what have you.\n\nThat is JavaScript 101, but worth mentioning since a quick code search on github will reveal the collective evasion, or perhaps widespread ignorance of this concept. Shall we go for a feigned example? We shall.\n\n```js\nconst hi = name => `Hi ${name}`;\nconst greeting = name => hi(name);\n```\n\nHere, the function wrapper around `hi` in `greeting` is completely redundant. Why? Because functions are *callable* in JavaScript. When `hi` has the `()` at the end it will run and return a value. When it does not, it simply returns the function stored in the variable. Just to be sure, have a look yourself:\n\n\n```js\nhi; // name => `Hi ${name}`\nhi(\"jonas\"); // \"Hi jonas\"\n```\n\nSince `greeting` is merely in turn calling `hi` with the very same argument, we could simply write:\n\n```js\nconst greeting = hi;\ngreeting(\"times\"); // \"Hi times\"\n```\n\nIn other words, `hi` is already a function that expects one argument, why place another function around it that simply calls `hi` with the same bloody argument? It doesn't make any damn sense. It's like donning your heaviest parka in the dead of July just to blast the air and demand an ice lolly.\n\nIt is obnoxiously verbose and, as it happens, bad practice to surround a function with another function merely to delay evaluation (we'll see why in a moment, but it has to do with maintenance)\n\nA solid understanding of this is critical before moving on, so let's examine a few more fun examples excavated from the library of npm packages.\n\n```js\n// ignorant\nconst getServerStuff = callback => ajaxCall(json => callback(json));\n\n// enlightened\nconst getServerStuff = ajaxCall;\n```\n\nThe world is littered with ajax code exactly like this. Here is the reason both are equivalent:\n\n```js\n// this line\najaxCall(json => callback(json));\n\n// is the same as this line\najaxCall(callback);\n\n// so refactor getServerStuff\nconst getServerStuff = callback => ajaxCall(callback);\n\n// ...which is equivalent to this\nconst getServerStuff = ajaxCall; // <-- look mum, no ()'s\n```\n\nAnd that, folks, is how it is done. Once more so that we understand why I'm being so persistent.\n\n```js\nconst BlogController = {\n  index(posts) { return Views.index(posts); },\n  show(post) { return Views.show(post); },\n  create(attrs) { return Db.create(attrs); },\n  update(post, attrs) { return Db.update(post, attrs); },\n  destroy(post) { return Db.destroy(post); },\n};\n```\n\nThis ridiculous controller is 99% fluff. We could either rewrite it as:\n\n```js\nconst BlogController = {\n  index: Views.index,\n  show: Views.show,\n  create: Db.create,\n  update: Db.update,\n  destroy: Db.destroy,\n};\n```\n\n... or scrap it altogether since it does nothing more than just bundle our Views and Db together.\n\n## Why Favor First Class?\n\nOkay, let's get down to the reasons to favor first class functions. As we saw in the `getServerStuff` and `BlogController` examples, it's easy to add layers of indirection that provide no added value and only increase the amount of redundant code to maintain and search through.\n\nIn addition, if such a needlessly wrapped function must be changed, we must also need to change our wrapper function as well.\n\n```js\nhttpGet('/post/2', json => renderPost(json));\n```\n\nIf `httpGet` were to change to send a possible `err`, we would need to go back and change the \"glue\".\n\n```js\n// go back to every httpGet call in the application and explicitly pass err along.\nhttpGet('/post/2', (json, err) => renderPost(json, err));\n```\n\nHad we written it as a first class function, much less would need to change:\n\n```js\n// renderPost is called from within httpGet with however many arguments it wants\nhttpGet('/post/2', renderPost);\n```\n\nBesides the removal of unnecessary functions, we must name and reference arguments. Names are a bit of an issue, you see. We have potential misnomers - especially as the codebase ages and requirements change.\n\nHaving multiple names for the same concept is a common source of confusion in projects. There is also the issue of generic code. For instance, these two functions do exactly the same thing, but one feels infinitely more general and reusable:\n\n```js\n// specific to our current blog\nconst validArticles = articles =>\n  articles.filter(article => article !== null && article !== undefined),\n\n// vastly more relevant for future projects\nconst compact = xs => xs.filter(x => x !== null && x !== undefined);\n```\n\nBy using specific naming, we've seemingly tied ourselves to specific data (in this case `articles`). This happens quite a bit and is a source of much reinvention.\n\nI must mention that, just like with Object-Oriented code, you must be aware of `this` coming to bite you in the jugular. If an underlying function uses `this` and we call it first class, we are subject to this leaky abstraction's wrath.\n\n```js\nconst fs = require('fs');\n\n// scary\nfs.readFile('freaky_friday.txt', Db.save);\n\n// less so\nfs.readFile('freaky_friday.txt', Db.save.bind(Db));\n```\n\nHaving been bound to itself, the `Db` is free to access its prototypical garbage code. I avoid using `this` like a dirty nappy. There's really no need when writing functional code. However, when interfacing with other libraries, you might have to acquiesce to the mad world around us.\n\nSome will argue that `this` is necessary for optimizing speed. If you are the micro-optimization sort, please close this book. If you cannot get your money back, perhaps you can exchange it for something more fiddly.\n\nAnd with that, we're ready to move on.\n\n[Chapter 03: Pure Happiness with Pure Functions](ch03.md)\n"
  },
  {
    "path": "ch03.md",
    "content": "# Chapter 03: Pure Happiness with Pure Functions\n\n## Oh to Be Pure Again\n\nOne thing we need to get straight is the idea of a pure function.\n\n>A pure function is a function that, given the same input, will always return the same output and does not have any observable side effect.\n\nTake `slice` and `splice`. They are two functions that do the exact same thing - in a vastly different way, mind you, but the same thing nonetheless. We say `slice` is *pure* because it returns the same output per input every time, guaranteed. `splice`, however, will chew up its array and spit it back out forever changed which is an observable effect.\n\n```js\nconst xs = [1,2,3,4,5];\n\n// pure\nxs.slice(0,3); // [1,2,3]\n\nxs.slice(0,3); // [1,2,3]\n\nxs.slice(0,3); // [1,2,3]\n\n\n// impure\nxs.splice(0,3); // [1,2,3]\n\nxs.splice(0,3); // [4,5]\n\nxs.splice(0,3); // []\n```\n\nIn functional programming, we dislike unwieldy functions like `splice` that *mutate* data. This will never do as we're striving for reliable functions that return the same result every time, not functions that leave a mess in their wake like `splice`.\n\nLet's look at another example.\n\n```js\n// impure\nlet minimum = 21;\nconst checkAge = age => age >= minimum;\n\n// pure\nconst checkAge = (age) => {\n  const minimum = 21;\n  return age >= minimum;\n};\n```\n\nIn the impure portion, `checkAge` depends on the mutable variable `minimum` to determine the result. In other words, it depends on system state which is disappointing because it increases the [cognitive load](https://en.wikipedia.org/wiki/Cognitive_load) by introducing an external environment.\n\nIt might not seem like a lot in this example, but this reliance upon state is one of the largest contributors to system complexity (http://curtclifton.net/papers/MoseleyMarks06a.pdf). This `checkAge` may return different results depending on factors external to input, which not only disqualifies it from being pure, but also puts our minds through the wringer each time we're reasoning about the software.\n\nIts pure form, on the other hand, is completely self sufficient. We can  also make `minimum` immutable, which preserves the purity as the state will never change. To do this, we must create an object to freeze.\n\n```js\nconst immutableState = Object.freeze({ minimum: 21 });\n```\n\n## Side Effects May Include...\n\nLet's look more at these \"side effects\" to improve our intuition. So what is this undoubtedly nefarious *side effect* mentioned in the definition of *pure function*? We'll be referring to *effect* as anything that occurs in our computation other than the calculation of a result.\n\nThere's nothing intrinsically bad about effects and we'll be using them all over the place in the chapters to come. It's that *side* part that bears the negative connotation. Water alone is not an inherent larvae incubator, it's the *stagnant* part that yields the swarms, and I assure you, *side* effects are a similar breeding ground in your own programs.\n\n>A *side effect* is a change of system state or *observable interaction* with the outside world that occurs during the calculation of a result.\n\nSide effects may include, but are not limited to\n\n  * changing the file system\n  * inserting a record into a database\n  * making an http call\n  * mutations\n  * printing to the screen / logging\n  * obtaining user input\n  * querying the DOM\n  * accessing system state\n\nAnd the list goes on and on. Any interaction with the world outside of a function is a side effect, which is a fact that may prompt you to suspect the practicality of programming without them. The philosophy of functional programming postulates that side effects are a primary cause of incorrect behavior.\n\nIt is not that we're forbidden to use them, rather we want to contain them and run them in a controlled way. We'll learn how to do this when we get to functors and monads in later chapters, but for now, let's try to keep these insidious functions separate from our pure ones.\n\nSide effects disqualify a function from being *pure*. And it makes sense: pure functions, by definition, must always return the same output given the same input, which is not possible to guarantee when dealing with matters outside our local function.\n\nLet's take a closer look at why we insist on the same output per input. Pop your collars, we're going to look at some 8th grade math.\n\n## 8th Grade Math\n\nFrom mathisfun.com:\n\n> A function is a special relationship between values:\n> Each of its input values gives back exactly one output value.\n\nIn other words, it's just a relation between two values: the input and the output. Though each input has exactly one output, that output doesn't necessarily have to be unique per input. Below shows a diagram of a perfectly valid function from `x` to `y`;\n\n<img src=\"images/function-sets.gif\" alt=\"function sets\" />(https://www.mathsisfun.com/sets/function.html)\n\nTo contrast, the following diagram shows a relation that is *not* a function since the input value `5` points to several outputs:\n\n<img src=\"images/relation-not-function.gif\" alt=\"relation not function\" />(https://www.mathsisfun.com/sets/function.html)\n\nFunctions can be described as a set of pairs with the position (input, output): `[(1,2), (3,6), (5,10)]` (It appears this function doubles its input).\n\nOr perhaps a table:\n<table> <tr> <th>Input</th> <th>Output</th> </tr> <tr> <td>1</td> <td>2</td> </tr> <tr> <td>2</td> <td>4</td> </tr> <tr> <td>3</td> <td>6</td> </tr> </table>\n\nOr even as a graph with `x` as the input and `y` as the output:\n\n<img src=\"images/fn_graph.png\" width=\"300\" height=\"300\" alt=\"function graph\" />\n\n\nThere's no need for implementation details if the input dictates the output. Since functions are simply mappings of input to output, one could simply jot down object literals and run them with `[]` instead of `()`.\n\n```js\nconst toLowerCase = {\n  A: 'a',\n  B: 'b',\n  C: 'c',\n  D: 'd',\n  E: 'e',\n  F: 'f',\n};\ntoLowerCase['C']; // 'c'\n\nconst isPrime = {\n  1: false,\n  2: true,\n  3: true,\n  4: false,\n  5: true,\n  6: false,\n};\nisPrime[3]; // true\n```\n\nOf course, you might want to calculate instead of hand writing things out, but this illustrates a different way to think about functions. (You may be thinking \"what about functions with multiple arguments?\". Indeed, that presents a bit of an inconvenience when thinking in terms of mathematics. For now, we can bundle them up in an array or just think of the `arguments` object as the input. When we learn about *currying*, we'll see how we can directly model the mathematical definition of a function.)\n\nHere comes the dramatic reveal: Pure functions *are* mathematical functions and they're what functional programming is all about. Programming with these little angels can provide huge benefits. Let's look at some reasons why we're willing to go to great lengths to preserve purity.\n\n## The Case for Purity\n\n### Cacheable\n\nFor starters, pure functions can always be cached by input. This is typically done using a technique called memoization:\n\n```js\nconst squareNumber = memoize(x => x * x);\n\nsquareNumber(4); // 16\n\nsquareNumber(4); // 16, returns cache for input 4\n\nsquareNumber(5); // 25\n\nsquareNumber(5); // 25, returns cache for input 5\n```\n\nHere is a simplified implementation, though there are plenty of more robust versions available.\n\n```js\nconst memoize = (f) => {\n  const cache = {};\n\n  return (...args) => {\n    const argStr = JSON.stringify(args);\n    cache[argStr] = cache[argStr] || f(...args);\n    return cache[argStr];\n  };\n};\n```\n\nSomething to note is that you can transform some impure functions into pure ones by delaying evaluation:\n\n```js\nconst pureHttpCall = memoize((url, params) => () => $.getJSON(url, params));\n```\n\nThe interesting thing here is that we don't actually make the http call - we instead return a function that will do so when called. This function is pure because it will always return the same output given the same input: the function that will make the particular http call given the `url` and `params`.\n\nOur `memoize` function works just fine, though it doesn't cache the results of the http call, rather it caches the generated function.\n\nThis is not very useful yet, but we'll soon learn some tricks that will make it so. The takeaway is that we can cache every function no matter how destructive they seem.\n\n### Portable / Self-documenting\n\nPure functions are completely self contained. Everything the function needs is handed to it on a silver platter. Ponder this for a moment... How might this be beneficial? For starters, a function's dependencies are explicit and therefore easier to see and understand - no funny business going on under the hood.\n\n```js\n// impure\nconst signUp = (attrs) => {\n  const user = saveUser(attrs);\n  welcomeUser(user);\n};\n\n// pure\nconst signUp = (Db, Email, attrs) => () => {\n  const user = saveUser(Db, attrs);\n  welcomeUser(Email, user);\n};\n```\n\nThe example here demonstrates that the pure function must be honest about its dependencies and, as such, tell us exactly what it's up to. Just from its signature, we know that it will use a `Db`, `Email`, and `attrs` which should be telling to say the least.\n\nWe'll learn how to make functions like this pure without merely deferring evaluation, but the point should be clear that the pure form is much more informative than its sneaky impure counterpart which is up to who knows what.\n\nSomething else to notice is that we're forced to \"inject\" dependencies, or pass them in as arguments, which makes our app much more flexible because we've parameterized our database or mail client or what have you (don't worry, we'll see a way to make this less tedious than it sounds). Should we choose to use a different Db we need only to call our function with it. Should we find ourselves writing a new application in which we'd like to reuse this reliable function, we simply give this function whatever `Db` and `Email` we have at the time.\n\nIn a JavaScript setting, portability could mean serializing and sending functions over a socket. It could mean running all our app code in web workers. Portability is a powerful trait.\n\nContrary to \"typical\" methods and procedures in imperative programming rooted deep in their environment via state, dependencies, and available effects, pure functions can be run anywhere our hearts desire.\n\nWhen was the last time you copied a method into a new app? One of my favorite quotes comes from Erlang creator, Joe Armstrong: \"The problem with object-oriented languages is they’ve got all this implicit environment that they carry around with them. You wanted a banana but what you got was a gorilla holding the banana... and the entire jungle\".\n\n### Testable\n\nNext, we come to realize pure functions make testing much easier. We don't have to mock a \"real\" payment gateway or setup and assert the state of the world after each test. We simply give the function input and assert output.\n\nIn fact, we find the functional community pioneering new test tools that can blast our functions with generated input and assert that properties hold on the output. It's beyond the scope of this book, but I strongly encourage you to search for and try *Quickcheck* - a testing tool that is tailored for a purely functional environment.\n\n### Reasonable\n\nMany believe the biggest win when working with pure functions is *referential transparency*. A spot of code is referentially transparent when it can be substituted for its evaluated value without changing the behavior of the program.\n\nSince pure functions don't have side effects, they can only influence the behavior of a program through their output values. Furthermore, since their output values can reliably be calculated using only their input values, pure functions will always preserve referential transparency. Let's see an example.\n\n\n```js\nconst { Map } = require('immutable');\n\n// Aliases: p = player, a = attacker, t = target\nconst jobe = Map({ name: 'Jobe', hp: 20, team: 'red' });\nconst michael = Map({ name: 'Michael', hp: 20, team: 'green' });\nconst decrementHP = p => p.set('hp', p.get('hp') - 1);\nconst isSameTeam = (p1, p2) => p1.get('team') === p2.get('team');\nconst punch = (a, t) => (isSameTeam(a, t) ? t : decrementHP(t));\n\npunch(jobe, michael); // Map({name:'Michael', hp:19, team: 'green'})\n```\n\n`decrementHP`, `isSameTeam` and `punch` are all pure and therefore referentially transparent. We can use a technique called *equational reasoning* wherein one substitutes \"equals for equals\" to reason about code. It's a bit like manually evaluating the code without taking into account the quirks of programmatic evaluation. Using referential transparency, let's play with this code a bit.\n\nFirst we'll inline the function `isSameTeam`.\n\n```js\nconst punch = (a, t) => (a.get('team') === t.get('team') ? t : decrementHP(t));\n```\n\nSince our data is immutable, we can simply replace the teams with their actual value\n\n```js\nconst punch = (a, t) => ('red' === 'green' ? t : decrementHP(t));\n```\n\nWe see that it is false in this case so we can remove the entire if branch\n\n```js\nconst punch = (a, t) => decrementHP(t);\n```\n\nAnd if we inline `decrementHP`, we see that, in this case, punch becomes a call to decrement the `hp` by 1.\n\n```js\nconst punch = (a, t) => t.set('hp', t.get('hp') - 1);\n```\n\nThis ability to reason about code is terrific for refactoring and understanding code in general. In fact, we used this technique to refactor our flock of seagulls program. We used equational reasoning to harness the properties of addition and multiplication. Indeed, we'll be using these techniques throughout the book.\n\n### Parallel Code\n\nFinally, and here's the coup de grâce, we can run any pure function in parallel since it does not need access to shared memory and it cannot, by definition, have a race condition due to some side effect.\n\nThis is very much possible in a server side js environment with threads as well as in the browser with web workers though current culture seems to avoid it due to complexity when dealing with impure functions.\n\n\n## In Summary\n\nWe've seen what pure functions are and why we, as functional programmers, believe they are the cat's evening wear. From this point on, we'll strive to write all our functions in a pure way. We'll require some extra tools to help us do so, but in the meantime, we'll try to separate the impure functions from the rest of the pure code.\n\nWriting programs with pure functions is a tad laborious without some extra tools in our belt. We have to juggle data by passing arguments all over the place, we're forbidden to use state, not to mention effects. How does one go about writing these masochistic programs? Let's acquire a new tool called curry.\n\n[Chapter 04: Currying](ch04.md)\n"
  },
  {
    "path": "ch04.md",
    "content": "# Chapter 04: Currying\n\n## Can't Live If Livin' Is without You\nMy Dad once explained how there are certain things one can live without until one acquires them. A microwave is one such thing. Smart phones, another. The older folks among us will remember a fulfilling life sans internet. For me, currying is on this list.\n\nThe concept is simple: You can call a function with fewer arguments than it expects. It returns a function that takes the remaining arguments.\n\nYou can choose to call it all at once or simply feed in each argument piecemeal.\n\n```js\nconst add = x => y => x + y;\nconst increment = add(1);\nconst addTen = add(10);\n\nincrement(2); // 3\naddTen(2); // 12\n```\n\nHere we've made a function `add` that takes one argument and returns a function. By calling it, the returned function remembers the first argument from then on via the closure. Calling it with both arguments all at once is a bit of a pain, however, so we can use a special helper function called `curry` to make defining and calling functions like this easier.\n\nLet's set up a few curried functions for our enjoyment. From now on, we'll summon our `curry`\nfunction defined in the [Appendix A - Essential Function Support](./appendix_a.md). \n\n```js\nconst match = curry((what, s) => s.match(what));\nconst replace = curry((what, replacement, s) => s.replace(what, replacement));\nconst filter = curry((f, xs) => xs.filter(f));\nconst map = curry((f, xs) => xs.map(f));\n```\n\nThe pattern I've followed is a simple, but important one. I've strategically positioned the data we're operating on (String, Array) as the last argument. It will become clear as to why upon use.\n\n(The syntax `/r/g`  is a regular expression that means _match every letter 'r'_. Read [more about regular expressions](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions) if you like.)\n\n```js\nmatch(/r/g, 'hello world'); // [ 'r' ]\n\nconst hasLetterR = match(/r/g); // x => x.match(/r/g)\nhasLetterR('hello world'); // [ 'r' ]\nhasLetterR('just j and s and t etc'); // null\n\nfilter(hasLetterR, ['rock and roll', 'smooth jazz']); // ['rock and roll']\n\nconst removeStringsWithoutRs = filter(hasLetterR); // xs => xs.filter(x => x.match(/r/g))\nremoveStringsWithoutRs(['rock and roll', 'smooth jazz', 'drum circle']); // ['rock and roll', 'drum circle']\n\nconst noVowels = replace(/[aeiou]/ig); // (r,x) => x.replace(/[aeiou]/ig, r)\nconst censored = noVowels('*'); // x => x.replace(/[aeiou]/ig, '*')\ncensored('Chocolate Rain'); // 'Ch*c*l*t* R**n'\n```\n\nWhat's demonstrated here is the ability to \"pre-load\" a function with an argument or two in order to receive a new function that remembers those arguments.\n\nI encourage you to clone the Mostly Adequate repository (`git clone\nhttps://github.com/MostlyAdequate/mostly-adequate-guide.git`), copy the code above and have a\ngo at it in the REPL. The curry function, as well as actually anything defined in the appendixes,\nare available in the `support/index.js` module.\n\nAlternatively, have a look at a published version on `npm`:\n\n```\nnpm install @mostly-adequate/support\n```\n\n## More Than a Pun / Special Sauce\n\nCurrying is useful for many things. We can make new functions just by giving our base functions some arguments as seen in `hasLetterR`, `removeStringsWithoutRs`, and `censored`.\n\nWe also have the ability to transform any function that works on single elements into a function that works on arrays simply by wrapping it with `map`:\n\n```js\nconst getChildren = x => x.childNodes;\nconst allTheChildren = map(getChildren);\n```\n\nGiving a function fewer arguments than it expects is typically called *partial application*. Partially applying a function can remove a lot of boiler plate code. Consider what the above `allTheChildren` function would be with the uncurried `map` from lodash (note the arguments are in a different order):\n\n```js\nconst allTheChildren = elements => map(elements, getChildren);\n```\n\nWe typically don't define functions that work on arrays, because we can just call `map(getChildren)` inline. Same with `sort`, `filter`, and other higher order functions (a *higher order function* is a function that takes or returns a function).\n\nWhen we spoke about *pure functions*, we said they take 1 input to 1 output. Currying does exactly this: each single argument returns a new function expecting the remaining arguments. That, old sport, is 1 input to 1 output.\n\nNo matter if the output is another function - it qualifies as pure. We do allow more than one argument at a time, but this is seen as merely removing the extra `()`'s for convenience.\n\n\n## In Summary\n\nCurrying is handy and I very much enjoy working with curried functions on a daily basis. It is a tool for the belt that makes functional programming less verbose and tedious.\n\nWe can make new, useful functions on the fly simply by passing in a few arguments and as a bonus, we've retained the mathematical function definition despite multiple arguments.\n\nLet's acquire another essential tool called `compose`.\n\n[Chapter 05: Coding by Composing](ch05.md)\n\n## Exercises\n\n#### Note about Exercises\n\nThroughout the book, you might encounter an 'Exercises' section like this one. Exercises can be\ndone directly in-browser provided you're reading from [gitbook](https://mostly-adequate.gitbooks.io/mostly-adequate-guide) (recommended).\n\nNote that, for all exercises of the book, you always have a handful of helper functions\navailable in the global scope. Hence, anything that is defined in [Appendix A](./appendix_a.md),\n[Appendix B](./appendix_b.md) and [Appendix C](./appendix_c.md) is available for you! And, as\nif it wasn't enough, some exercises will also define functions specific to the problem\nthey present; as a matter of fact, consider them available as well.\n\n> Hint: you can submit your solution by doing `Ctrl + Enter` in the embedded editor!\n\n#### Running Exercises on Your Machine (optional)\n\nShould you prefer to do exercises directly in files using your own editor:\n\n- clone the repository (`git clone git@github.com:MostlyAdequate/mostly-adequate-guide.git`)\n- go in the *exercises* section (`cd mostly-adequate-guide/exercises`)\n- be sure to be using the recommended node version v10.22.1 (e.g. `nvm install`). More on this in [the readme of the book](./README.md#about-the-nodejs-version)\n- install the necessary plumbing using [npm](https://docs.npmjs.com/downloading-and-installing-node-js-and-npm) (`npm install`)\n- complete answers by modifying the files named *exercise\\_\\** in the corresponding chapter's folder \n- run the correction with npm (e.g. `npm run ch04`)\n\nUnit tests will run against your answers and provide hints in case of mistake. By the by, the\nanswers to the exercises are available in files named *solution\\_\\**.\n\n#### Let's Practice!\n\n{% exercise %}  \nRefactor to remove all arguments by partially applying the function.  \n  \n{% initial src=\"./exercises/ch04/exercise_a.js#L3;\" %}  \n```js  \nconst words = str => split(' ', str);  \n```  \n  \n{% solution src=\"./exercises/ch04/solution_a.js\" %}  \n{% validation src=\"./exercises/ch04/validation_a.js\" %}  \n{% context src=\"./exercises/support.js\" %}  \n{% endexercise %}  \n\n\n---\n\n\n{% exercise %}  \nRefactor to remove all arguments by partially applying the functions.  \n  \n{% initial src=\"./exercises/ch04/exercise_b.js#L3;\" %}  \n```js  \nconst filterQs = xs => filter(x => match(/q/i, x), xs);\n```  \n  \n{% solution src=\"./exercises/ch04/solution_b.js\" %}  \n{% validation src=\"./exercises/ch04/validation_b.js\" %}  \n{% context src=\"./exercises/support.js\" %}  \n{% endexercise %}  \n\n\n---\n\n\nConsidering the following function:\n\n```js  \nconst keepHighest = (x, y) => (x >= y ? x : y);  \n```  \n\n{% exercise %}  \nRefactor `max` to not reference any arguments using the helper function `keepHighest`.  \n  \n{% initial src=\"./exercises/ch04/exercise_c.js#L7;\" %}  \n```js  \nconst max = xs => reduce((acc, x) => (x >= acc ? x : acc), -Infinity, xs);  \n```  \n  \n{% solution src=\"./exercises/ch04/solution_c.js\" %}  \n{% validation src=\"./exercises/ch04/validation_c.js\" %}  \n{% context src=\"./exercises/support.js\" %}  \n{% endexercise %}  \n"
  },
  {
    "path": "ch05.md",
    "content": "# Chapter 05: Coding by Composing\n\n## Functional Husbandry\n\nHere's `compose`:\n\n```js\nconst compose = (...fns) => (...args) => fns.reduceRight((res, fn) => [fn.call(null, ...res)], args)[0];\n```\n\n... Don't be scared! This is the level-9000-super-Saiyan-form of _compose_. For the sake of reasoning, let's drop the variadic implementation and consider a simpler form that can compose two functions together. Once you get your head around that, you can push the abstraction further and consider it simply works for any number of functions (we could even prove that)!\nHere's a more friendly _compose_ for you my dear readers:\n\n```js\nconst compose2 = (f, g) => x => f(g(x));\n```\n\n`f` and `g` are functions and `x` is the value being \"piped\" through them.\n\nComposition feels like function husbandry. You, breeder of functions, select two with traits you'd like to combine and mash them together to spawn a brand new one. Usage is as follows:\n\n```js\nconst toUpperCase = x => x.toUpperCase();\nconst exclaim = x => `${x}!`;\nconst shout = compose(exclaim, toUpperCase);\n\nshout('send in the clowns'); // \"SEND IN THE CLOWNS!\"\n```\n\nThe composition of two functions returns a new function. This makes perfect sense: composing two units of some type (in this case function) should yield a new unit of that very type. You don't plug two legos together and get a lincoln log. There is a theory here, some underlying law that we will discover in due time.\n\nIn our definition of `compose`, the `g` will run before the `f`, creating a right to left flow of data. This is much more readable than nesting a bunch of function calls. Without compose, the above would read:\n\n```js\nconst shout = x => exclaim(toUpperCase(x));\n```\n\nInstead of inside to outside, we run right to left, which I suppose is a step in the left direction (boo!). Let's look at an example where sequence matters:\n\n```js\nconst head = x => x[0];\nconst reverse = reduce((acc, x) => [x, ...acc], []);\nconst last = compose(head, reverse);\n\nlast(['jumpkick', 'roundhouse', 'uppercut']); // 'uppercut'\n```\n\n`reverse` will turn the list around while `head` grabs the initial item. This results in an effective, albeit inefficient, `last` function. The sequence of functions in the composition should be apparent here. We could define a left to right version, however, we mirror the mathematical version much more closely as it stands. That's right, composition is straight from the math books. In fact, perhaps it's time to look at a property that holds for any composition.\n\n```js\n// associativity\ncompose(f, compose(g, h)) === compose(compose(f, g), h);\n```\n\nComposition is associative, meaning it doesn't matter how you group two of them. So, should we choose to uppercase the string, we can write:\n\n```js\ncompose(toUpperCase, compose(head, reverse));\n// or\ncompose(compose(toUpperCase, head), reverse);\n```\n\nSince it doesn't matter how we group our calls to `compose`, the result will be the same. That allows us to write a variadic compose and use it as follows:\n\n```js\n// previously we'd have to write two composes, but since it's associative, \n// we can give compose as many fn's as we like and let it decide how to group them.\nconst arg = ['jumpkick', 'roundhouse', 'uppercut'];\nconst lastUpper = compose(toUpperCase, head, reverse);\nconst loudLastUpper = compose(exclaim, toUpperCase, head, reverse);\n\nlastUpper(arg); // 'UPPERCUT'\nloudLastUpper(arg); // 'UPPERCUT!'\n```\n\nApplying the associative property gives us this flexibility and peace of mind that the result will be equivalent. The slightly more complicated variadic definition is included with the support libraries for this book and is the normal definition you'll find in libraries like [lodash][lodash-website], [underscore][underscore-website], and [ramda][ramda-website].\n\nOne pleasant benefit of associativity is that any group of functions can be extracted and bundled together in their very own composition. Let's play with refactoring our previous example:\n\n```js\nconst loudLastUpper = compose(exclaim, toUpperCase, head, reverse);\n\n// -- or ---------------------------------------------------------------\n\nconst last = compose(head, reverse);\nconst loudLastUpper = compose(exclaim, toUpperCase, last);\n\n// -- or ---------------------------------------------------------------\n\nconst last = compose(head, reverse);\nconst angry = compose(exclaim, toUpperCase);\nconst loudLastUpper = compose(angry, last);\n\n// more variations...\n```\n\nThere's no right or wrong answers - we're just plugging our legos together in whatever way we please. Usually it's best to group things in a reusable way like `last` and `angry`. If familiar with Fowler's \"[Refactoring][refactoring-book]\", one might recognize this process as \"[extract function][extract-function-refactor]\"...except without all the object state to worry about.\n\n## Pointfree\n\nPointfree style means never having to say your data. Excuse me. It means functions that never mention the data upon which they operate. First class functions, currying, and composition all play well together to create this style.\n\n> Hint: Pointfree versions of `replace` & `toLowerCase` are defined in the [Appendix C -\n> Pointfree Utilities](./appendix_c.md). Do not hesitate to have a peek!\n\n```js\n// not pointfree because we mention the data: word\nconst snakeCase = word => word.toLowerCase().replace(/\\s+/ig, '_');\n\n// pointfree\nconst snakeCase = compose(replace(/\\s+/ig, '_'), toLowerCase);\n```\n\nSee how we partially applied `replace`? What we're doing is piping our data through each function of 1 argument. Currying allows us to prepare each function to just take its data, operate on it, and pass it along. Something else to notice is how we don't need the data to construct our function in the pointfree version, whereas in the pointful one, we must have our `word` available before anything else.\n\nLet's look at another example.\n\n```js\n// not pointfree because we mention the data: name\nconst initials = name => name.split(' ').map(compose(toUpperCase, head)).join('. ');\n\n// pointfree\n// NOTE: we use 'intercalate' from the appendix instead of 'join' introduced in Chapter 09!\nconst initials = compose(intercalate('. '), map(compose(toUpperCase, head)), split(' '));\n\ninitials('hunter stockton thompson'); // 'H. S. T'\n```\n\nPointfree code can again, help us remove needless names and keep us concise and generic. Pointfree is a good litmus test for functional code as it lets us know we've got small functions that take input to output. One can't compose a while loop, for instance. Be warned, however, pointfree is a double-edged sword and can sometimes obfuscate intention. Not all functional code is pointfree and that is O.K. We'll shoot for it where we can and stick with normal functions otherwise.\n\n## Debugging\nA common mistake is to compose something like `map`, a function of two arguments, without first partially applying it.\n\n```js\n// wrong - we end up giving angry an array and we partially applied map with who knows what.\nconst latin = compose(map, angry, reverse);\n\nlatin(['frog', 'eyes']); // error\n\n// right - each function expects 1 argument.\nconst latin = compose(map(angry), reverse);\n\nlatin(['frog', 'eyes']); // ['EYES!', 'FROG!'])\n```\n\nIf you are having trouble debugging a composition, we can use this helpful, but impure trace function to see what's going on.\n\n```js\nconst trace = curry((tag, x) => {\n  console.log(tag, x);\n  return x;\n});\n\nconst dasherize = compose(\n  intercalate('-'),\n  toLower,\n  split(' '),\n  replace(/\\s{2,}/ig, ' '),\n);\n\ndasherize('The world is a vampire');\n// TypeError: Cannot read property 'apply' of undefined\n```\n\nSomething is wrong here, let's `trace`\n\n```js\nconst dasherize = compose(\n  intercalate('-'),\n  toLower,\n  trace('after split'),\n  split(' '),\n  replace(/\\s{2,}/ig, ' '),\n);\n\ndasherize('The world is a vampire');\n// after split [ 'The', 'world', 'is', 'a', 'vampire' ]\n```\n\nAh! We need to `map` this `toLower` since it's working on an array.\n\n```js\nconst dasherize = compose(\n  intercalate('-'),\n  map(toLower),\n  split(' '),\n  replace(/\\s{2,}/ig, ' '),\n);\n\ndasherize('The world is a vampire'); // 'the-world-is-a-vampire'\n```\n\nThe `trace` function allows us to view the data at a certain point for debugging purposes. Languages like Haskell and PureScript have similar functions for ease of development.\n\nComposition will be our tool for constructing programs and, as luck would have it, is backed by a powerful theory that ensures things will work out for us. Let's examine this theory.\n\n\n## Category Theory\n\nCategory theory is an abstract branch of mathematics that can formalize concepts from several different branches such as set theory, type theory, group theory, logic, and more. It primarily deals with objects, morphisms, and transformations, which mirrors programming quite closely. Here is a chart of the same concepts as viewed from each separate theory.\n\n<img src=\"images/cat_theory.png\" alt=\"category theory\" />\n\nSorry, I didn't mean to frighten you. I don't expect you to be intimately familiar with all these concepts. My point is to show you how much duplication we have so you can see why category theory aims to unify these things.\n\nIn category theory, we have something called... a category. It is defined as a collection with the following components:\n\n  * A collection of objects\n  * A collection of morphisms\n  * A notion of composition on the morphisms\n  * A distinguished morphism called identity\n\nCategory theory is abstract enough to model many things, but let's apply this to types and functions, which is what we care about at the moment.\n\n**A collection of objects**\nThe objects will be data types. For instance, ``String``, ``Boolean``, ``Number``, ``Object``, etc. We often view data types as sets of all the possible values. One could look at ``Boolean`` as the set of `[true, false]` and ``Number`` as the set of all possible numeric values. Treating types as sets is useful because we can use set theory to work with them.\n\n\n**A collection of morphisms**\nThe morphisms will be our standard every day pure functions.\n\n**A notion of composition on the morphisms**\nThis, as you may have guessed, is our brand new toy - `compose`. We've discussed that our `compose` function is associative which is no coincidence as it is a property that must hold for any composition in category theory.\n\nHere is an image demonstrating composition:\n\n<img src=\"images/cat_comp1.png\" alt=\"category composition 1\" />\n<img src=\"images/cat_comp2.png\" alt=\"category composition 2\" />\n\nHere is a concrete example in code:\n\n```js\nconst g = x => x.length;\nconst f = x => x === 4;\nconst isFourLetterWord = compose(f, g);\n```\n\n**A distinguished morphism called identity**\nLet's introduce a useful function called `id`. This function simply takes some input and spits it back at you. Take a look:\n\n```js\nconst id = x => x;\n```\n\nYou might ask yourself \"What in the bloody hell is that useful for?\". We'll make extensive use of this function in the following chapters, but for now think of it as a function that can stand in for our value - a function masquerading as every day data.\n\n`id` must play nicely with compose. Here is a property that always holds for every unary (unary: a one-argument function) function f:\n\n```js\n// identity\ncompose(id, f) === compose(f, id) === f;\n// true\n```\n\nHey, it's just like the identity property on numbers! If that's not immediately clear, take some time with it. Understand the futility. We'll be seeing `id` used all over the place soon, but for now we see it's a function that acts as a stand in for a given value. This is quite useful when writing pointfree code.\n\nSo there you have it, a category of types and functions. If this is your first introduction, I imagine you're still a little fuzzy on what a category is and why it's useful. We will build upon this knowledge throughout the book. As of right now, in this chapter, on this line, you can at least see it as providing us with some wisdom regarding composition - namely, the associativity and identity properties.\n\nWhat are some other categories, you ask? Well, we can define one for directed graphs with nodes being objects, edges being morphisms, and composition just being path concatenation. We can define with Numbers as objects and `>=` as morphisms (actually any partial or total order can be a category). There are heaps of categories, but for the purposes of this book, we'll only concern ourselves with the one defined above. We have sufficiently skimmed the surface and must move on.\n\n\n## In Summary\nComposition connects our functions together like a series of pipes. Data will flow through our application as it must - pure functions are input to output after all, so breaking this chain would disregard output, rendering our software useless.\n\nWe hold composition as a design principle above all others. This is because it keeps our app simple and reasonable. Category theory will play a big part in app architecture, modelling side effects, and ensuring correctness.\n\nWe are now at a point where it would serve us well to see some of this in practice. Let's make an example application.\n\n[Chapter 06: Example Application](ch06.md)\n\n## Exercises\n\nIn each following exercise, we'll consider Car objects with the following shape:\n\n```js\n{\n  name: 'Aston Martin One-77',\n  horsepower: 750,\n  dollar_value: 1850000,\n  in_stock: true,\n}\n```\n\n\n{% exercise %}  \nUse `compose()` to rewrite the function below.  \n  \n{% initial src=\"./exercises/ch05/exercise_a.js#L12;\" %}  \n```js  \nconst isLastInStock = (cars) => {  \n  const lastCar = last(cars);  \n  return prop('in_stock', lastCar);  \n};  \n```  \n  \n{% solution src=\"./exercises/ch05/solution_a.js\" %}  \n{% validation src=\"./exercises/ch05/validation_a.js\" %}  \n{% context src=\"./exercises/support.js\" %}  \n{% endexercise %}  \n\n\n---\n\n\nConsidering the following function:\n\n```js\nconst average = xs => reduce(add, 0, xs) / xs.length;\n```\n\n{% exercise %}  \nUse the helper function `average` to refactor `averageDollarValue` as a composition.  \n  \n{% initial src=\"./exercises/ch05/exercise_b.js#L7;\" %}  \n```js  \nconst averageDollarValue = (cars) => {  \n  const dollarValues = map(c => c.dollar_value, cars);  \n  return average(dollarValues);  \n};  \n```  \n  \n{% solution src=\"./exercises/ch05/solution_b.js\" %}  \n{% validation src=\"./exercises/ch05/validation_b.js\" %}  \n{% context src=\"./exercises/support.js\" %}  \n{% endexercise %}  \n\n\n---\n\n\n{% exercise %}  \nRefactor `fastestCar` using `compose()` and other functions in pointfree-style. Hint, the  \n`append` function may come in handy.  \n  \n{% initial src=\"./exercises/ch05/exercise_c.js#L4;\" %}  \n```js  \nconst fastestCar = (cars) => {  \n  const sorted = sortBy(car => car.horsepower, cars);  \n  const fastest = last(sorted);  \n  return concat(fastest.name, ' is the fastest');  \n};  \n```  \n  \n{% solution src=\"./exercises/ch05/solution_c.js\" %}  \n{% validation src=\"./exercises/ch05/validation_c.js\" %}  \n{% context src=\"./exercises/support.js\" %}  \n{% endexercise %}  \n\n[lodash-website]: https://lodash.com/\n[underscore-website]: https://underscorejs.org/\n[ramda-website]: https://ramdajs.com/\n[refactoring-book]: https://martinfowler.com/books/refactoring.html\n[extract-function-refactor]: https://refactoring.com/catalog/extractFunction.html\n"
  },
  {
    "path": "ch06.md",
    "content": "# Chapter 06: Example Application\n\n## Declarative Coding\n\nWe are going to switch our mindset. From here on out, we'll stop telling the computer how to do its job and instead write a specification of what we'd like as a result. I'm sure you'll find it much less stressful than trying to micromanage everything all the time.\n\nDeclarative, as opposed to imperative, means that we will write expressions, as opposed to step by step instructions.\n\nThink of SQL. There is no \"first do this, then do that\". There is one expression that specifies what we'd like from the database. We don't decide how to do the work, it does. When the database is upgraded and the SQL engine optimized, we don't have to change our query. This is because there are many ways to interpret our specification and achieve the same result.\n\nFor some folks, myself included, it's hard to grasp the concept of declarative coding at first so let's point out a few examples to get a feel for it.\n\n```js\n// imperative\nconst makes = [];\nfor (let i = 0; i < cars.length; i += 1) {\n  makes.push(cars[i].make);\n}\n\n// declarative\nconst makes = cars.map(car => car.make);\n```\n\nThe imperative loop must first instantiate the array. The interpreter must evaluate this statement before moving on. Then it directly iterates through the list of cars, manually increasing a counter and showing its bits and pieces to us in a vulgar display of explicit iteration.\n\nThe `map` version is one expression. It does not require any order of evaluation. There is much freedom here for how the map function iterates and how the returned array may be assembled. It specifies *what*, not *how*. Thus, it wears the shiny declarative sash.\n\nIn addition to being clearer and more concise, the map function may be optimized at will and our precious application code needn't change.\n\nFor those of you who are thinking \"Yes, but it's much faster to do the imperative loop\", I suggest you educate yourself on how the JIT optimizes your code. Here's a [terrific video that may shed some light](https://www.youtube.com/watch?v=g0ek4vV7nEA)\n\nHere is another example.\n\n```js\n// imperative\nconst authenticate = (form) => {\n  const user = toUser(form);\n  return logIn(user);\n};\n\n// declarative\nconst authenticate = compose(logIn, toUser);\n```\n\nThough there's nothing necessarily wrong with the imperative version, there is still an encoded step-by-step evaluation baked in. The `compose` expression simply states a fact: Authentication is the composition of `toUser` and `logIn`. Again, this leaves wiggle room for support code changes and results in our application code being a high level specification.\n\nIn the example above, the order of evaluation is specified (`toUser` must be called before `logIn`), but there are many scenarios where the order is not important, and this is easily specified with declarative coding (more on this later). \n\nBecause we don't have to encode the order of evaluation, declarative coding lends itself to parallel computing. This coupled with pure functions is why FP is a good option for the parallel future - we don't really need to do anything special to achieve parallel/concurrent systems.\n\n## A Flickr of Functional Programming\n\nWe will now build an example application in a declarative, composable way. We'll still cheat and use side effects for now, but we'll keep them minimal and separate from our pure codebase. We are going to build a browser widget that sucks in flickr images and displays them. Let's start by scaffolding the app. Here's the html:\n\n\n```html\n<!doctype html>\n<html lang=\"en\">\n  <head>\n    <meta charset=\"utf-8\">\n    <title>Flickr App</title>\n  </head>\n  <body>\n    <main id=\"js-main\" class=\"main\"></main>\n    <script src=\"https://cdnjs.cloudflare.com/ajax/libs/require.js/2.2.0/require.min.js\"></script>\n    <script src=\"main.js\"></script>\n  </body>\n</html>\n```\n\nAnd here's the main.js skeleton:\n\n```js\nconst CDN = s => `https://cdnjs.cloudflare.com/ajax/libs/${s}`;\nconst ramda = CDN('ramda/0.21.0/ramda.min');\nconst jquery = CDN('jquery/3.0.0-rc1/jquery.min');\n\nrequirejs.config({ paths: { ramda, jquery } });\nrequirejs(['jquery', 'ramda'], ($, { compose, curry, map, prop }) => {\n  // app goes here\n});\n```\n\nWe're pulling in [ramda](https://ramdajs.com) instead of lodash or some other utility library. It includes `compose`, `curry`, and more. I've used requirejs, which may seem like overkill, but we'll be using it throughout the book and consistency is key.\n\nNow that that's out of the way, on to the spec. Our app will do 4 things.\n\n1. Construct a url for our particular search term\n2. Make the flickr api call\n3. Transform the resulting json into html images\n4. Place them on the screen\n\nThere are 2 impure actions mentioned above. Do you see them? Those bits about getting data from the flickr api and placing it on the screen. Let's define those first so we can quarantine them. Also, I'll add our nice `trace` function for easy debugging.\n\n```js\nconst Impure = {\n  getJSON: curry((callback, url) => $.getJSON(url, callback)),\n  setHtml: curry((sel, html) => $(sel).html(html)),\n  trace: curry((tag, x) => { console.log(tag, x); return x; }),\n};\n```\n\nHere we've simply wrapped jQuery's methods to be curried and we've swapped the arguments to a more favorable position. I've namespaced them with `Impure` so we know these are dangerous functions. In a future example, we will make these two functions pure.\n\nNext we must construct a url to pass to our `Impure.getJSON` function.\n\n```js\nconst host = 'api.flickr.com';\nconst path = '/services/feeds/photos_public.gne';\nconst query = t => `?tags=${t}&format=json&jsoncallback=?`;\nconst url = t => `https://${host}${path}${query(t)}`;\n```\n\nThere are fancy and overly complex ways of writing `url` pointfree using monoids(we'll learn about these later) or combinators. We've chosen to stick with a readable version and assemble this string in the normal pointful fashion.\n\nLet's write an app function that makes the call and places the contents on the screen.\n\n```js\nconst app = compose(Impure.getJSON(Impure.trace('response')), url);\napp('cats');\n```\n\nThis calls our `url` function, then passes the string to our `getJSON` function, which has been partially applied with `trace`. Loading the app will show the response from the api call in the console.\n\n<img src=\"images/console_ss.png\" alt=\"console response\" />\n\nWe'd like to construct images out of this json. It looks like the `mediaUrls` are buried in `items` then each `media`'s `m` property.\n\nAnyhow, to get at these nested properties we can use a nice universal getter function from ramda called `prop`. Here's a homegrown version so you can see what's happening:\n\n```js\nconst prop = curry((property, object) => object[property]);\n```\n\nIt's quite dull actually. We just use `[]` syntax to access a property on whatever object. Let's use this to get at our `mediaUrls`.\n\n```js\nconst mediaUrl = compose(prop('m'), prop('media'));\nconst mediaUrls = compose(map(mediaUrl), prop('items'));\n```\n\nOnce we gather the `items`, we must `map` over them to extract each media url. This results in a nice array of `mediaUrls`. Let's hook this up to our app and print them on the screen.\n\n```js\nconst render = compose(Impure.setHtml('#js-main'), mediaUrls);\nconst app = compose(Impure.getJSON(render), url);\n```\n\nAll we've done is make a new composition that will call our `mediaUrls` and set the `<main>` html with them. We've replaced the `trace` call with `render` now that we have something to render besides raw json. This will crudely display our `mediaUrls` within the body.\n\nOur final step is to turn these `mediaUrls` into bonafide `images`. In a bigger application, we'd use a template/dom library like Handlebars or React. For this application though, we only need an img tag so let's stick with jQuery.\n\n```js\nconst img = src => $('<img />', { src });\n```\n\njQuery's `html` method will accept an array of tags. We only have to transform our mediaUrls into images and send them along to `setHtml`.\n\n```js\nconst images = compose(map(img), mediaUrls);\nconst render = compose(Impure.setHtml('#js-main'), images);\nconst app = compose(Impure.getJSON(render), url);\n```\n\nAnd we're done!\n\n<img src=\"images/cats_ss.png\" alt=\"cats grid\" />\n\nHere is the finished script:\n[include](./exercises/ch06/main.js)\n\nNow look at that. A beautifully declarative specification of what things are, not how they come to be. We now view each line as an equation with properties that hold. We can use these properties to reason about our application and refactor.\n\n## A Principled Refactor\n\nThere is an optimization available - we map over each item to turn it into a media url, then we map again over those mediaUrls to turn them into img tags. There is a law regarding map and composition:\n\n\n```js\n// map's composition law\ncompose(map(f), map(g)) === map(compose(f, g));\n```\n\nWe can use this property to optimize our code. Let's have a principled refactor.\n\n```js\n// original code\nconst mediaUrl = compose(prop('m'), prop('media'));\nconst mediaUrls = compose(map(mediaUrl), prop('items'));\nconst images = compose(map(img), mediaUrls);\n```\n\nLet's line up our maps. We can inline the call to `mediaUrls` in `images` thanks to equational reasoning and purity.\n\n```js\nconst mediaUrl = compose(prop('m'), prop('media'));\nconst images = compose(map(img), map(mediaUrl), prop('items'));\n```\n\nNow that we've lined up our `map`s we can apply the composition law.\n\n```js\n/*\ncompose(map(f), map(g)) === map(compose(f, g));\ncompose(map(img), map(mediaUrl)) === map(compose(img, mediaUrl));\n*/\n\nconst mediaUrl = compose(prop('m'), prop('media'));\nconst images = compose(map(compose(img, mediaUrl)), prop('items'));\n```\n\nNow the bugger will only loop once while turning each item into an img. Let's just make it a little more readable by extracting the function out.\n\n```js\nconst mediaUrl = compose(prop('m'), prop('media'));\nconst mediaToImg = compose(img, mediaUrl);\nconst images = compose(map(mediaToImg), prop('items'));\n```\n\n## In Summary\n\nWe have seen how to put our new skills into use with a small, but real world app. We've used our mathematical framework to reason about and refactor our code. But what about error handling and code branching? How can we make the whole application pure instead of merely namespacing destructive functions? How can we make our app safer and more expressive? These are the questions we will tackle in part 2.\n\n[Chapter 07: Hindley-Milner and Me](ch07.md)\n"
  },
  {
    "path": "ch07.md",
    "content": "# Chapter 07: Hindley-Milner and Me\n\n## What's Your Type?\nIf you're new to the functional world, it won't be long before you find yourself knee deep in type signatures. Types are the meta language that enables people from all different backgrounds to communicate succinctly and effectively. For the most part, they're written with a system called \"Hindley-Milner\", which we'll be examining together in this chapter.\n\nWhen working with pure functions, type signatures have an expressive power to which the English language cannot hold a candle. These signatures whisper in your ear the intimate secrets of a function. In a single, compact line, they expose behaviour and intention. We can derive \"free theorems\" from them. Types can be inferred so there's no need for explicit type annotations. They can be tuned to fine point precision or left general and abstract. They are not only useful for compile time checks, but also turn out to be the best possible documentation available. Type signatures thus play an important part in functional programming - much more than you might first expect.\n\nJavaScript is a dynamic language, but that does not mean we avoid types all together. We're still working with strings, numbers, booleans, and so on. It's just that there isn't any language level integration so we hold this information in our heads. Not to worry, since we're using signatures for documentation, we can use comments to serve our purpose.\n\nThere are type checking tools available for JavaScript such as [Flow](https://flow.org/) or the typed dialect, [TypeScript](https://www.typescriptlang.org/). The aim of this book is to equip one with the tools to write functional code so we'll stick with the standard type system used across FP languages.\n\n\n## Tales from the Cryptic\n\nFrom the dusty pages of math books, across the vast sea of white papers, amongst casual Saturday morning blog posts, down into the source code itself, we find Hindley-Milner type signatures. The system is quite simple, but warrants a quick explanation and some practice to fully absorb the little language.\n\n```js\n// capitalize :: String -> String\nconst capitalize = s => toUpperCase(head(s)) + toLowerCase(tail(s));\n\ncapitalize('smurf'); // 'Smurf'\n```\n\nHere, `capitalize` takes a `String` and returns a `String`. Never mind the implementation, it's the type signature we're interested in.\n\nIn HM, functions are written as `a -> b` where `a` and `b` are variables for any type. So the signatures for `capitalize` can be read as \"a function from `String` to `String`\". In other words, it takes a `String` as its input and returns a `String` as its output.\n\nLet's look at some more function signatures:\n\n```js\n// strLength :: String -> Number\nconst strLength = s => s.length;\n\n// join :: String -> [String] -> String\nconst join = curry((what, xs) => xs.join(what));\n\n// match :: Regex -> String -> [String]\nconst match = curry((reg, s) => s.match(reg));\n\n// replace :: Regex -> String -> String -> String\nconst replace = curry((reg, sub, s) => s.replace(reg, sub));\n```\n\n`strLength` is the same idea as before: we take a `String` and return you a `Number`.\n\nThe others might perplex you at first glance. Without fully understanding the details, you could always just view the last type as the return value. So for `match` you can interpret as: It takes a `Regex` and a `String` and returns you `[String]`. But an interesting thing is going on here that I'd like to take a moment to explain if I may.\n\nFor `match` we are free to group the signature like so:\n\n```js\n// match :: Regex -> (String -> [String])\nconst match = curry((reg, s) => s.match(reg));\n```\n\nAh yes, grouping the last part in parenthesis reveals more information. Now it is seen as a function that takes a `Regex` and returns us a function from `String` to `[String]`. Because of currying, this is indeed the case: give it a `Regex` and we get a function back waiting for its `String` argument. Of course, we don't have to think of it this way, but it is good to understand why the last type is the one returned.\n\n```js\n// match :: Regex -> (String -> [String])\n// onHoliday :: String -> [String]\nconst onHoliday = match(/holiday/ig);\n```\n\nEach argument pops one type off the front of the signature. `onHoliday` is `match` that already has a `Regex`.\n\n```js\n// replace :: Regex -> (String -> (String -> String))\nconst replace = curry((reg, sub, s) => s.replace(reg, sub));\n```\n\nAs you can see with the full parenthesis on `replace`, the extra notation can get a little noisy and redundant so we simply omit them. We can give all the arguments at once if we choose so it's easier to just think of it as: `replace` takes a `Regex`, a `String`, another `String` and returns you a `String`.\n\nA few last things here:\n\n\n```js\n// id :: a -> a\nconst id = x => x;\n\n// map :: (a -> b) -> [a] -> [b]\nconst map = curry((f, xs) => xs.map(f));\n```\n\nThe `id` function takes any old type `a` and returns something of the same type `a`. We're able to use variables in types just like in code. Variable names like `a` and `b` are convention, but they are arbitrary and can be replaced with whatever name you'd like. If they are the same variable, they have to be the same type. That's an important rule so let's reiterate: `a -> b` can be any type `a` to any type `b`, but `a -> a` means it has to be the same type. For example, `id` may be `String -> String` or `Number -> Number`, but not `String -> Bool`.\n\n`map` similarly uses type variables, but this time we introduce `b` which may or may not be the same type as `a`. We can read it as: `map` takes a function from any type `a` to the same or different type `b`, then takes an array of `a`'s and results in an array of `b`'s.\n\nHopefully, you've been overcome by the expressive beauty in this type signature. It literally tells us what the function does almost word for word. It's given a function from `a` to `b`, an array of `a`, and it delivers us an array of `b`. The only sensible thing for it to do is call the bloody function on each `a`. Anything else would be a bold face lie.\n\nBeing able to reason about types and their implications is a skill that will take you far in the functional world. Not only will papers, blogs, docs, etc, become more digestible, but the signature itself will practically lecture you on its functionality. It takes practice to become a fluent reader, but if you stick with it, heaps of information will become available to you sans RTFMing.\n\nHere's a few more just to see if you can decipher them on your own.\n\n```js\n// head :: [a] -> a\nconst head = xs => xs[0];\n\n// filter :: (a -> Bool) -> [a] -> [a]\nconst filter = curry((f, xs) => xs.filter(f));\n\n// reduce :: ((b, a) -> b) -> b -> [a] -> b\nconst reduce = curry((f, x, xs) => xs.reduce(f, x));\n```\n\n`reduce` is perhaps, the most expressive of all. It's a tricky one, however, so don't feel inadequate should you struggle with it. For the curious, I'll try to explain in English though working through the signature on your own is much more instructive.\n\nAhem, here goes nothing....looking at the signature, we see the first argument is a function that expects `b` and `a`, and produces a `b`. Where might it get these `a`s and `b`s? Well, the following arguments in the signature are a `b` and an array of `a`s so we can only assume that the `b` and each of those `a`s will be fed in. We also see that the result of the function is a `b` so the thinking here is our final incantation of the passed in function will be our output value. Knowing what reduce does, we can state that the above investigation is accurate.\n\n\n## Narrowing the Possibility\n\nOnce a type variable is introduced, there emerges a curious property called *[parametricity](https://en.wikipedia.org/wiki/Parametricity)*. This property states that a function will *act on all types in a uniform manner*. Let's investigate:\n\n```js\n// head :: [a] -> a\n```\n\nLooking at `head`, we see that it takes `[a]` to `a`. Besides the concrete type `array`, it has no other information available and, therefore, its functionality is limited to working on the array alone. What could it possibly do with the variable `a` if it knows nothing about it? In other words, `a` says it cannot be a *specific* type, which means it can be *any* type, which leaves us with a function that must work uniformly for *every* conceivable type. This is what *parametricity* is all about. Guessing at the implementation, the only reasonable assumptions are that it takes the first, last, or a random element from that array. The name `head` should tip us off.\n\nHere's another one:\n\n```js\n// reverse :: [a] -> [a]\n```\n\nFrom the type signature alone, what could `reverse` possibly be up to? Again, it cannot do anything specific to `a`. It cannot change `a` to a different type or we'd introduce a `b`. Can it sort? Well, no, it wouldn't have enough information to sort every possible type. Can it re-arrange?  Yes, I suppose it can do that, but it has to do so in exactly the same predictable way. Another possibility is that it may decide to remove or duplicate an element. In any case, the point is, the possible behaviour is massively narrowed by its polymorphic type.\n\nThis narrowing of possibility allows us to use type signature search engines like [Hoogle](https://hoogle.haskell.org/) to find a function we're after. The information packed tightly into a signature is quite powerful indeed.\n\n## Free as in Theorem\n\nBesides deducing implementation possibilities, this sort of reasoning gains us *free theorems*. What follows are a few random example theorems lifted directly from [Wadler's paper on the subject](http://ttic.uchicago.edu/~dreyer/course/papers/wadler.pdf).\n\n```js\n// head :: [a] -> a\ncompose(f, head) === compose(head, map(f));\n\n// filter :: (a -> Bool) -> [a] -> [a]\ncompose(map(f), filter(compose(p, f))) === compose(filter(p), map(f));\n```\n\n\nYou don't need any code to get these theorems, they follow directly from the types. The first one says that if we get the `head` of our array, then run some function `f` on it, that is equivalent to, and incidentally, much faster than, if we first `map(f)` over every element then take the `head` of the result.\n\nYou might think, well that's just common sense. But last I checked, computers don't have common sense. Indeed, they must have a formal way to automate these kind of code optimizations. Maths has a way of formalizing the intuitive, which is helpful amidst the rigid terrain of computer logic.\n\nThe `filter` theorem is similar. It says that if we compose `f` and `p` to check which should be filtered, then actually apply the `f` via `map` (remember `filter` will not transform the elements - its signature enforces that `a` will not be touched), it will always be equivalent to mapping our `f` then filtering the result with the `p` predicate.\n\nThese are just two examples, but you can apply this reasoning to any polymorphic type signature and it will always hold. In JavaScript, there are some tools available to declare rewrite rules. One might also do this via the `compose` function itself. The fruit is low hanging and the possibilities are endless.\n\n## Constraints\n\nOne last thing to note is that we can constrain types to an interface.\n\n```js\n// sort :: Ord a => [a] -> [a]\n```\n\nWhat we see on the left side of our fat arrow here is the statement of a fact: `a` must be an `Ord`. Or in other words, `a` must implement the `Ord` interface. What is `Ord` and where did it come from? In a typed language it would be a defined interface that says we can order the values. This not only tells us more about the `a` and what our `sort` function is up to, but also restricts the domain. We call these interface declarations *type constraints*.\n\n```js\n// assertEqual :: (Eq a, Show a) => a -> a -> Assertion\n```\n\nHere, we have two constraints: `Eq` and `Show`. Those will ensure that we can check equality of our `a`s and print the difference if they are not equal.\n\nWe'll see more examples of constraints and the idea should take more shape in later chapters.\n\n## In Summary\n\nHindley-Milner type signatures are ubiquitous in the functional world. Though they are simple to read and write, it takes time to master the technique of understanding programs through signatures alone. We will add type signatures to each line of code from here on out.\n\n[Chapter 08: Tupperware](ch08.md)\n"
  },
  {
    "path": "ch08.md",
    "content": "# Chapter 08: Tupperware\n\n## The Mighty Container\n\n<img src=\"images/jar.jpg\" alt=\"http://blog.dwinegar.com/2011/06/another-jar.html\" />\n\nWe've seen how to write programs which pipe data through a series of pure functions. They are declarative specifications of behaviour. But what about control flow, error handling, asynchronous actions, state and, dare I say, effects?! In this chapter, we will discover the foundation upon which all of these helpful abstractions are built.\n\nFirst we will create a container. This container must hold any type of value; a ziplock that holds only tapioca pudding is rarely useful. It will be an object, but we will not give it properties and methods in the OO sense. No, we will treat it like a treasure chest - a special box that cradles our valuable data.\n\n```js\nclass Container {\n  constructor(x) {\n    this.$value = x;\n  }\n  \n  static of(x) {\n    return new Container(x);\n  }\n}\n```\n\nHere is our first container. We've thoughtfully named it `Container`. We will use `Container.of` as a constructor which saves us from having to write that awful `new` keyword all over the place. There's more to the `of` function than meets the eye, but for now, think of it as the proper way to place values into our container.\n\nLet's examine our brand new box...\n\n```js\nContainer.of(3);\n// Container(3)\n\nContainer.of('hotdogs');\n// Container(\"hotdogs\")\n\nContainer.of(Container.of({ name: 'yoda' }));\n// Container(Container({ name: 'yoda' }))\n```\n\nIf you are using node, you will see `{$value: x}` even though we've got ourselves a `Container(x)`. Chrome will output the type properly, but no matter; as long as we understand what a `Container` looks like, we'll be fine. In some environments you can overwrite the `inspect` method if you'd like, but we will not be so thorough. For this book, we will write the conceptual output as if we'd overwritten `inspect` as it's much more instructive than `{$value: x}` for pedagogical as well as aesthetic reasons.\n\nLet's make a few things clear before we move on:\n\n* `Container` is an object with one property. Lots of containers just hold one thing, though they aren't limited to one. We've arbitrarily named its property `$value`.\n\n* The `$value` cannot be one specific type or our `Container` would hardly live up to the name.\n\n* Once data goes into the `Container` it stays there. We *could* get it out by using `.$value`, but that would defeat the purpose.\n\nThe reasons we're doing this will become clear as a mason jar, but for now, bear with me.\n\n## My First Functor\n\nOnce our value, whatever it may be, is in the container, we'll need a way to run functions on it.\n\n```js\n// (a -> b) -> Container a -> Container b\nContainer.prototype.map = function (f) {\n  return Container.of(f(this.$value));\n};\n```\n\nWhy, it's just like Array's famous `map`, except we have `Container a` instead of `[a]`. And it works essentially the same way:\n\n```js\nContainer.of(2).map(two => two + 2); \n// Container(4)\n\nContainer.of('flamethrowers').map(s => s.toUpperCase()); \n// Container('FLAMETHROWERS')\n\nContainer.of('bombs').map(append(' away')).map(prop('length')); \n// Container(10)\n```\n\nWe can work with our value without ever having to leave the `Container`. This is a remarkable thing. Our value in the `Container` is handed to the `map` function so we can fuss with it and afterward, returned to its `Container` for safe keeping. As a result of never leaving the `Container`, we can continue to `map` away, running functions as we please. We can even change the type as we go along as demonstrated in the latter of the three examples.\n\nWait a minute, if we keep calling `map`, it appears to be some sort of composition! What mathematical magic is at work here? Well chaps, we've just discovered *Functors*.\n\n> A Functor is a type that implements `map` and obeys some laws\n\nYes, *Functor* is simply an interface with a contract. We could have just as easily named it *Mappable*, but now, where's the *fun* in that? Functors come from category theory and we'll look at the maths in detail toward the end of the chapter, but for now, let's work on intuition and practical uses for this bizarrely named interface.\n\nWhat reason could we possibly have for bottling up a value and using `map` to get at it? The answer reveals itself if we choose a better question: What do we gain from asking our container to apply functions for us? Well, abstraction of function application. When we `map` a function, we ask the container type to run it for us. This is a very powerful concept, indeed.\n\n## Schrödinger's Maybe\n\n<img src=\"images/cat.png\" alt=\"cool cat, need reference\" />\n\n`Container` is fairly boring. In fact, it is usually called `Identity` and has about the same impact as our `id` function (again there is a mathematical connection we'll look at when the time is right). However, there are other functors, that is, container-like types that have a proper `map` function, which can provide useful behaviour whilst mapping. Let's define one now.\n\n> A complete implementation is given in the [Appendix B](./appendix_b.md#Maybe)\n\n```js\nclass Maybe {\n  static of(x) {\n    return new Maybe(x);\n  }\n\n  get isNothing() {\n    return this.$value === null || this.$value === undefined;\n  }\n\n  constructor(x) {\n    this.$value = x;\n  }\n\n  map(fn) {\n    return this.isNothing ? this : Maybe.of(fn(this.$value));\n  }\n\n  inspect() {\n    return this.isNothing ? 'Nothing' : `Just(${inspect(this.$value)})`;\n  }\n}\n```\n\nNow, `Maybe` looks a lot like `Container` with one minor change: it will first check to see if it has a value before calling the supplied function. This has the effect of side stepping those pesky nulls as we `map`(Note that this implementation is simplified for teaching).\n\n```js\nMaybe.of('Malkovich Malkovich').map(match(/a/ig));\n// Just(True)\n\nMaybe.of(null).map(match(/a/ig));\n// Nothing\n\nMaybe.of({ name: 'Boris' }).map(prop('age')).map(add(10));\n// Nothing\n\nMaybe.of({ name: 'Dinah', age: 14 }).map(prop('age')).map(add(10));\n// Just(24)\n```\n\nNotice our app doesn't explode with errors as we map functions over our null values. This is because `Maybe` will take care to check for a value each and every time it applies a function.\n\nThis dot syntax is perfectly fine and functional, but for reasons mentioned in Part 1, we'd like to maintain our pointfree style. As it happens, `map` is fully equipped to delegate to whatever functor it receives:\n\n```js\n// map :: Functor f => (a -> b) -> f a -> f b\nconst map = curry((f, anyFunctor) => anyFunctor.map(f));\n```\n\nThis is delightful as we can carry on with composition per usual and `map` will work as expected. This is the case with ramda's `map` as well. We'll use dot notation when it's instructive and the pointfree version when it's convenient. Did you notice that? I've sneakily introduced extra notation into our type signature. The `Functor f =>` tells us that `f` must be a Functor. Not that difficult, but I felt I should mention it.\n\n## Use Cases\n\nIn the wild, we'll typically see `Maybe` used in functions which might fail to return a result.\n\n```js\n// safeHead :: [a] -> Maybe(a)\nconst safeHead = xs => Maybe.of(xs[0]);\n\n// streetName :: Object -> Maybe String\nconst streetName = compose(map(prop('street')), safeHead, prop('addresses'));\n\nstreetName({ addresses: [] });\n// Nothing\n\nstreetName({ addresses: [{ street: 'Shady Ln.', number: 4201 }] });\n// Just('Shady Ln.')\n```\n\n`safeHead` is like our normal `head`, but with added type safety. A curious thing happens when `Maybe` is introduced into our code; we are forced to deal with those sneaky `null` values. The `safeHead` function is honest and up front about its possible failure - there's really nothing to be ashamed of - and so it returns a `Maybe` to inform us of this matter. We are more than merely *informed*, however, because we are forced to `map` to get at the value we want since it is tucked away inside the `Maybe` object. Essentially, this is a `null` check enforced by the `safeHead` function itself. We can now sleep better at night knowing a `null` value won't rear its ugly, decapitated head when we least expect it. APIs like this will upgrade a flimsy application from paper and tacks to wood and nails. They will guarantee safer software.\n\n\nSometimes a function might return a `Nothing` explicitly to signal failure. For instance:\n\n```js\n// withdraw :: Number -> Account -> Maybe(Account)\nconst withdraw = curry((amount, { balance }) =>\n  Maybe.of(balance >= amount ? { balance: balance - amount } : null));\n\n// This function is hypothetical, not implemented here... nor anywhere else.\n// updateLedger :: Account -> Account \nconst updateLedger = account => account;\n\n// remainingBalance :: Account -> String\nconst remainingBalance = ({ balance }) => `Your balance is $${balance}`;\n\n// finishTransaction :: Account -> String\nconst finishTransaction = compose(remainingBalance, updateLedger);\n\n\n// getTwenty :: Account -> Maybe(String)\nconst getTwenty = compose(map(finishTransaction), withdraw(20));\n\ngetTwenty({ balance: 200.00 }); \n// Just('Your balance is $180')\n\ngetTwenty({ balance: 10.00 });\n// Nothing\n```\n\n`withdraw` will tip its nose at us and return `Nothing` if we're short on cash. This function also communicates its fickleness and leaves us no choice, but to `map` everything afterwards. The difference is that the `null` was intentional here. Instead of a `Just('..')`, we get the `Nothing` back to signal failure and our application effectively halts in its tracks. This is important to note: if the `withdraw` fails, then `map` will sever the rest of our computation since it doesn't ever run the mapped functions, namely `finishTransaction`. This is precisely the intended behaviour as we'd prefer not to update our ledger or show a new balance if we hadn't successfully withdrawn funds.\n\n## Releasing the Value\n\nOne thing people often miss is that there will always be an end of the line; some effecting function that sends JSON along, or prints to the screen, or alters our filesystem, or what have you. We cannot deliver the output with `return`, we must run some function or another to send it out into the world. We can phrase it like a Zen Buddhist koan: \"If a program has no observable effect, does it even run?\". Does it run correctly for its own satisfaction? I suspect it merely burns some cycles and goes back to sleep...\n\nOur application's job is to retrieve, transform, and carry that data along until it's time to say goodbye and the function which does so may be mapped, thus the value needn't leave the warm womb of its container. Indeed, a common error is to try to remove the value from our `Maybe` one way or another as if the possible value inside will suddenly materialize and all will be forgiven. We must understand it may be a branch of code where our value is not around to live up to its destiny.  Our code, much like Schrödinger's cat, is in two states at once and should maintain that fact until the final function. This gives our code a linear flow despite the logical branching.\n\nThere is, however, an escape hatch. If we would rather return a custom value and continue on, we can use a little helper called `maybe`.\n\n```js\n// maybe :: b -> (a -> b) -> Maybe a -> b\nconst maybe = curry((v, f, m) => {\n  if (m.isNothing) {\n    return v;\n  }\n\n  return f(m.$value);\n});\n\n// getTwenty :: Account -> String\nconst getTwenty = compose(maybe('You\\'re broke!', finishTransaction), withdraw(20));\n\ngetTwenty({ balance: 200.00 }); \n// 'Your balance is $180.00'\n\ngetTwenty({ balance: 10.00 }); \n// 'You\\'re broke!'\n```\n\nWe will now either return a static value (of the same type that `finishTransaction` returns) or continue on merrily finishing up the transaction sans `Maybe`. With `maybe`, we are witnessing the equivalent of an `if/else` statement whereas with `map`, the imperative analog would be: `if (x !== null) { return f(x) }`.\n\nThe introduction of `Maybe` can cause some initial discomfort. Users of Swift and Scala will know what I mean as it's baked right into the core libraries under the guise of `Option(al)`. When pushed to deal with `null` checks all the time (and there are times we know with absolute certainty the value exists), most people can't help but feel it's a tad laborious. However, with time, it will become second nature and you'll likely appreciate the safety. After all, most of the time it will prevent cut corners and save our hides.\n\nWriting unsafe software is like taking care to paint each egg with pastels before hurling it into traffic; like building a retirement home with materials warned against by three little pigs. It will do us well to put some safety into our functions and `Maybe` helps us do just that.\n\nI'd be remiss if I didn't mention that the \"real\" implementation will split `Maybe` into two types: one for something and the other for nothing. This allows us to obey parametricity in `map` so values like `null` and `undefined` can still be mapped over and the universal qualification of the value in a functor will be respected. You'll often see types like `Some(x) / None` or `Just(x) / Nothing` instead of a `Maybe` that does a `null` check on its value.\n\n## Pure Error Handling\n\n<img src=\"images/fists.jpg\" alt=\"pick a hand... need a reference\" />\n\nIt may come as a shock, but `throw/catch` is not very pure. When an error is thrown, instead of returning an output value, we sound the alarms! The function attacks, spewing thousands of 0s and 1s like shields and spears in an electric battle against our intruding input. With our new friend `Either`, we can do better than to declare war on input, we can respond with a polite message. Let's take a look:\n\n> A complete implementation is given in the [Appendix B](./appendix_b.md#Either)\n\n```js\nclass Either {\n  static of(x) {\n    return new Right(x);\n  }\n\n  constructor(x) {\n    this.$value = x;\n  }\n}\n\nclass Left extends Either {\n  map(f) {\n    return this;\n  }\n\n  inspect() {\n    return `Left(${inspect(this.$value)})`;\n  }\n}\n\nclass Right extends Either {\n  map(f) {\n    return Either.of(f(this.$value));\n  }\n\n  inspect() {\n    return `Right(${inspect(this.$value)})`;\n  }\n}\n\nconst left = x => new Left(x);\n```\n\n`Left` and `Right` are two subclasses of an abstract type we call `Either`. I've skipped the ceremony of creating the `Either` superclass as we won't ever use it, but it's good to be aware. Now then, there's nothing new here besides the two types. Let's see how they act:\n\n```js\nEither.of('rain').map(str => `b${str}`); \n// Right('brain')\n\nleft('rain').map(str => `It's gonna ${str}, better bring your umbrella!`); \n// Left('rain')\n\nEither.of({ host: 'localhost', port: 80 }).map(prop('host'));\n// Right('localhost')\n\nleft('rolls eyes...').map(prop('host'));\n// Left('rolls eyes...')\n```\n\n`Left` is the teenagery sort and ignores our request to `map` over it. `Right` will work just like `Container` (a.k.a Identity). The power comes from the ability to embed an error message within the `Left`.\n\nSuppose we have a function that might not succeed. How about we calculate an age from a birth date. We could use `Nothing` to signal failure and branch our program, however, that doesn't tell us much. Perhaps, we'd like to know why it failed. Let's write this using `Either`.\n\n```js\nconst moment = require('moment');\n\n// getAge :: Date -> User -> Either(String, Number)\nconst getAge = curry((now, user) => {\n  const birthDate = moment(user.birthDate, 'YYYY-MM-DD');\n\n  return birthDate.isValid()\n    ? Either.of(now.diff(birthDate, 'years'))\n    : left('Birth date could not be parsed');\n});\n\ngetAge(moment(), { birthDate: '2005-12-12' });\n// Right(9)\n\ngetAge(moment(), { birthDate: 'July 4, 2001' });\n// Left('Birth date could not be parsed')\n```\n\nNow, just like `Nothing`, we are short-circuiting our app when we return a `Left`. The difference, is now we have a clue as to why our program has derailed. Something to notice is that we return `Either(String, Number)`, which holds a `String` as its left value and a `Number` as its `Right`. This type signature is a bit informal as we haven't taken the time to define an actual `Either` superclass, however, we learn a lot from the type. It informs us that we're either getting an error message or the age back.\n\n```js\n// fortune :: Number -> String\nconst fortune = compose(concat('If you survive, you will be '), toString, add(1));\n\n// zoltar :: User -> Either(String, _)\nconst zoltar = compose(map(console.log), map(fortune), getAge(moment()));\n\nzoltar({ birthDate: '2005-12-12' });\n// 'If you survive, you will be 10'\n// Right(undefined)\n\nzoltar({ birthDate: 'balloons!' });\n// Left('Birth date could not be parsed')\n```\n\nWhen the `birthDate` is valid, the program outputs its mystical fortune to the screen for us to behold. Otherwise, we are handed a `Left` with the error message plain as day though still tucked away in its container. That acts just as if we'd thrown an error, but in a calm, mild manner fashion as opposed to losing its temper and screaming like a child when something goes wrong.\n\nIn this example, we are logically branching our control flow depending on the validity of the birth date, yet it reads as one linear motion from right to left rather than climbing through the curly braces of a conditional statement. Usually, we'd move the `console.log` out of our `zoltar` function and `map` it at the time of calling, but it's helpful to see how the `Right` branch differs. We use `_` in the right branch's type signature to indicate it's a value that should be ignored (In some browsers you have to use `console.log.bind(console)` to use it first class).\n\nI'd like to take this opportunity to point out something you may have missed: `fortune`, despite its use with `Either` in this example, is completely ignorant of any functors milling about. This was also the case with `finishTransaction` in the previous example. At the time of calling, a function can be surrounded by `map`, which transforms it from a non-functory function to a functory one, in informal terms. We call this process *lifting*. Functions tend to be better off working with normal data types rather than container types, then *lifted* into the right container as deemed necessary. This leads to simpler, more reusable functions that can be altered to work with any functor on demand.\n\n`Either` is great for casual errors like validation as well as more serious, stop the show errors like missing files or broken sockets. Try replacing some of the `Maybe` examples with `Either` to give better feedback.\n\nNow, I can't help but feel I've done `Either` a disservice by introducing it as merely a container for error messages. It captures logical disjunction (a.k.a `||`) in a type. It also encodes the idea of a *Coproduct* from category theory, which won't be touched on in this book, but is well worth reading up on as there's properties to be exploited. It is the canonical sum type (or disjoint union of sets) because its amount of possible inhabitants is the sum of the two contained types (I know that's a bit hand wavy so here's a [great article](https://www.schoolofhaskell.com/school/to-infinity-and-beyond/pick-of-the-week/sum-types)). There are many things `Either` can be, but as a functor, it is used for its error handling.\n\nJust like with `Maybe`, we have little `either`, which behaves similarly, but takes two functions instead of one and a static value. Each function should return the same type:\n\n```js\n// either :: (a -> c) -> (b -> c) -> Either a b -> c\nconst either = curry((f, g, e) => {\n  let result;\n\n  switch (e.constructor) {\n    case Left:\n      result = f(e.$value);\n      break;\n\n    case Right:\n      result = g(e.$value);\n      break;\n\n    // No Default\n  }\n\n  return result;\n});\n\n// zoltar :: User -> _\nconst zoltar = compose(console.log, either(id, fortune), getAge(moment()));\n\nzoltar({ birthDate: '2005-12-12' });\n// 'If you survive, you will be 10'\n// undefined\n\nzoltar({ birthDate: 'balloons!' });\n// 'Birth date could not be parsed'\n// undefined\n```\n\nFinally, a use for that mysterious `id` function. It simply parrots back the value in the `Left` to pass the error message to `console.log`. We've made our fortune-telling app more robust by enforcing error handling from within `getAge`. We either slap the user with a hard truth like a high five from a palm reader or we carry on with our process. And with that, we're ready to move on to an entirely different type of functor.\n\n## Old McDonald Had Effects...\n\n<img src=\"images/dominoes.jpg\" alt=\"dominoes.. need a reference\" />\n\nIn our chapter about purity we saw a peculiar example of a pure function. This function contained a side-effect, but we dubbed it pure by wrapping its action in another function. Here's another example of this:\n\n```js\n// getFromStorage :: String -> (_ -> String)\nconst getFromStorage = key => () => localStorage[key];\n```\n\nHad we not surrounded its guts in another function, `getFromStorage` would vary its output depending on external circumstance. With the sturdy wrapper in place, we will always get the same output per input: a function that, when called, will retrieve a particular item from `localStorage`. And just like that (maybe throw in a few Hail Mary's) we've cleared our conscience and all is forgiven.\n\nExcept, this isn't particularly useful now is it. Like a collectible action figure in its original packaging, we can't actually play with it. If only there were a way to reach inside of the container and get at its contents... Enter `IO`.\n\n```js\nclass IO {\n  static of(x) {\n    return new IO(() => x);\n  }\n\n  constructor(fn) {\n    this.$value = fn;\n  }\n\n  map(fn) {\n    return new IO(compose(fn, this.$value));\n  }\n\n  inspect() {\n    return `IO(${inspect(this.$value)})`;\n  }\n}\n```\n\n`IO` differs from the previous functors in that the `$value` is always a function. We don't\nthink of its `$value` as a function, however - that is an implementation detail and we best\nignore it. What is happening is exactly what we saw with the `getFromStorage` example: `IO`\ndelays the impure action by capturing it in a function wrapper. As such, we think of `IO` as\ncontaining the return value of the wrapped action and not the wrapper itself. This is apparent\nin the `of` function: we have an `IO(x)`, the `IO(() => x)` is just necessary to\navoid evaluation. Note that, to simplify reading, we'll show the hypothetical value contained\nin the `IO` as result; however in practice, you can't tell what this value is until you've\nactually unleashed the effects!\n\nLet's see it in use:\n\n```js\n// ioWindow :: IO Window\nconst ioWindow = new IO(() => window);\n\nioWindow.map(win => win.innerWidth);\n// IO(1430)\n\nioWindow\n  .map(prop('location'))\n  .map(prop('href'))\n  .map(split('/'));\n// IO(['http:', '', 'localhost:8000', 'blog', 'posts'])\n\n\n// $ :: String -> IO [DOM]\nconst $ = selector => new IO(() => document.querySelectorAll(selector));\n\n$('#myDiv').map(head).map(div => div.innerHTML);\n// IO('I am some inner html')\n```\n\nHere, `ioWindow` is an actual `IO` that we can `map` over straight away, whereas `$` is a function that returns an `IO` after it's called. I've written out the *conceptual* return values to better express the `IO`, though, in reality, it will always be `{ $value: [Function] }`. When we `map` over our `IO`, we stick that function at the end of a composition which, in turn, becomes the new `$value` and so on. Our mapped functions do not run, they get tacked on the end of a computation we're building up, function by function, like carefully placing dominoes that we don't dare tip over. The result is reminiscent of Gang of Four's command pattern or a queue.\n\nTake a moment to channel your functor intuition. If we see past the implementation details, we should feel right at home mapping over any container no matter its quirks or idiosyncrasies. We have the functor laws, which we will explore toward the end of the chapter, to thank for this pseudo-psychic power. At any rate, we can finally play with impure values without sacrificing our precious purity.\n\nNow, we've caged the beast, but we'll still have to set it free at some point. Mapping over our `IO` has built up a mighty impure computation and running it is surely going to disturb the peace. So where and when can we pull the trigger? Is it even possible to run our `IO` and still wear white at our wedding? The answer is yes, if we put the onus on the calling code. Our pure code, despite the nefarious plotting and scheming, maintains its innocence and it's the caller who gets burdened with the responsibility of actually running the effects. Let's see an example to make this concrete.\n\n```js\n// url :: IO String\nconst url = new IO(() => window.location.href);\n\n// toPairs :: String -> [[String]]\nconst toPairs = compose(map(split('=')), split('&'));\n\n// params :: String -> [[String]]\nconst params = compose(toPairs, last, split('?'));\n\n// findParam :: String -> IO Maybe [String]\nconst findParam = key => map(compose(Maybe.of, find(compose(eq(key), head)), params), url);\n\n// -- Impure calling code ----------------------------------------------\n\n// run it by calling $value()!\nfindParam('searchTerm').$value();\n// Just(['searchTerm', 'wafflehouse'])\n```\n\nOur library keeps its hands clean by wrapping `url` in an `IO` and passing the buck to the caller. You might have also noticed that we have stacked our containers; it's perfectly reasonable to have a `IO(Maybe([x]))`, which is three functors deep (`Array` is most definitely a mappable container type) and exceptionally expressive.\n\nThere's something that's been bothering me and we should rectify it immediately: `IO`'s `$value` isn't really its contained value, nor is it a private property. It is the pin in the grenade and it is meant to be pulled by a caller in the most public of ways. Let's rename this property to `unsafePerformIO` to remind our users of its volatility.\n\n```js\nclass IO {\n  constructor(io) {\n    this.unsafePerformIO = io;\n  }\n\n  map(fn) {\n    return new IO(compose(fn, this.unsafePerformIO));\n  }\n}\n```\n\nThere, much better. Now our calling code becomes `findParam('searchTerm').unsafePerformIO()`, which is clear as day to users (and readers) of the application.\n\n`IO` will be a loyal companion, helping us tame those feral impure actions. Next, we'll see a type similar in spirit, but having a drastically different use case.\n\n\n## Asynchronous Tasks\n\nCallbacks are the narrowing spiral staircase to hell. They are control flow as designed by M.C. Escher. With each nested callback squeezed in between the jungle gym of curly braces and parenthesis, they feel like limbo in an oubliette (how low can we go?!). I'm getting claustrophobic chills just thinking about them. Not to worry, we have a much better way of dealing with asynchronous code and it starts with an \"F\".\n\nThe internals are a bit too complicated to spill out all over the page here so we will use `Data.Task` (previously `Data.Future`) from Quildreen Motta's fantastic [Folktale](https://folktale.origamitower.com/). Behold some example usage:\n\n```js\n// -- Node readFile example ------------------------------------------\n\nconst fs = require('fs');\n\n// readFile :: String -> Task Error String\nconst readFile = filename => new Task((reject, result) => {\n  fs.readFile(filename, (err, data) => (err ? reject(err) : result(data)));\n});\n\nreadFile('metamorphosis').map(split('\\n')).map(head);\n// Task('One morning, as Gregor Samsa was waking up from anxious dreams, he discovered that\n// in bed he had been changed into a monstrous verminous bug.')\n\n\n// -- jQuery getJSON example -----------------------------------------\n\n// getJSON :: String -> {} -> Task Error JSON\nconst getJSON = curry((url, params) => new Task((reject, result) => {\n  $.getJSON(url, params, result).fail(reject);\n}));\n\ngetJSON('/video', { id: 10 }).map(prop('title'));\n// Task('Family Matters ep 15')\n\n\n// -- Default Minimal Context ----------------------------------------\n\n// We can put normal, non futuristic values inside as well\nTask.of(3).map(three => three + 1);\n// Task(4)\n```\n\nThe functions I'm calling `reject` and `result` are our error and success callbacks, respectively. As you can see, we simply `map` over the `Task` to work on the future value as if it was right there in our grasp. By now `map` should be old hat.\n\nIf you're familiar with promises, you might recognize the function `map` as `then` with `Task` playing the role of our promise. Don't fret if you aren't familiar with promises, we won't be using them anyhow because they are not pure, but the analogy holds nonetheless.\n\nLike `IO`, `Task` will patiently wait for us to give it the green light before running. In fact, because it waits for our command, `IO` is effectively subsumed by `Task` for all things asynchronous; `readFile` and `getJSON` don't require an extra `IO` container to be pure. What's more, `Task` works in a similar fashion when we `map` over it: we're placing instructions for the future like a chore chart in a time capsule - an act of sophisticated technological procrastination.\n\nTo run our `Task`, we must call the method `fork`. This works like `unsafePerformIO`, but as the name suggests, it will fork our process and evaluation continues on without blocking our thread. This can be implemented in numerous ways with threads and such, but here it acts as a normal async call would and the big wheel of the event loop keeps on turning. Let's look at `fork`:\n\n```js\n// -- Pure application -------------------------------------------------\n// blogPage :: Posts -> HTML\nconst blogPage = Handlebars.compile(blogTemplate);\n\n// renderPage :: Posts -> HTML\nconst renderPage = compose(blogPage, sortBy(prop('date')));\n\n// blog :: Params -> Task Error HTML\nconst blog = compose(map(renderPage), getJSON('/posts'));\n\n\n// -- Impure calling code ----------------------------------------------\nblog({}).fork(\n  error => $('#error').html(error.message),\n  page => $('#main').html(page),\n);\n\n$('#spinner').show();\n```\n\nUpon calling `fork`, the `Task` hurries off to find some posts and render the page. Meanwhile, we show a spinner since `fork` does not wait for a response. Finally, we will either display an error or render the page onto the screen depending if the `getJSON` call succeeded or not.\n\nTake a moment to consider how linear the control flow is here. We just read bottom to top, right to left even though the program will actually jump around a bit during execution. This makes reading and reasoning about our application simpler than having to bounce between callbacks and error handling blocks.\n\nGoodness, would you look at that, `Task` has also swallowed up `Either`! It must do so in order to handle futuristic failures since our normal control flow does not apply in the async world. This is all well and good as it provides sufficient and pure error handling out of the box.\n\nEven with `Task`, our `IO` and `Either` functors are not out of a job. Bear with me on a quick example that leans toward the more complex and hypothetical side, but is useful for illustrative purposes.\n\n```js\n// Postgres.connect :: Url -> IO DbConnection\n// runQuery :: DbConnection -> ResultSet\n// readFile :: String -> Task Error String\n\n// -- Pure application -------------------------------------------------\n\n// dbUrl :: Config -> Either Error Url\nconst dbUrl = ({ uname, pass, host, db }) => {\n  if (uname && pass && host && db) {\n    return Either.of(`db:pg://${uname}:${pass}@${host}5432/${db}`);\n  }\n\n  return left(Error('Invalid config!'));\n};\n\n// connectDb :: Config -> Either Error (IO DbConnection)\nconst connectDb = compose(map(Postgres.connect), dbUrl);\n\n// getConfig :: Filename -> Task Error (Either Error (IO DbConnection))\nconst getConfig = compose(map(compose(connectDb, JSON.parse)), readFile);\n\n\n// -- Impure calling code ----------------------------------------------\n\ngetConfig('db.json').fork(\n  logErr('couldn\\'t read file'),\n  either(console.log, map(runQuery)),\n);\n```\n\nIn this example, we still make use of `Either` and `IO` from within the success branch of `readFile`. `Task` takes care of the impurities of reading a file asynchronously, but we still deal with validating the config with `Either` and wrangling the db connection with `IO`. So you see, we're still in business for all things synchronous.\n\nI could go on, but that's all there is to it. Simple as `map`.\n\nIn practice, you'll likely have multiple asynchronous tasks in one workflow and we haven't yet acquired the full container apis to tackle this scenario. Not to worry, we'll look at monads and such soon, but first, we must examine the maths that make this all possible.\n\n\n## A Spot of Theory\n\nAs mentioned before, functors come from category theory and satisfy a few laws. Let's first explore these useful properties.\n\n```js\n// identity\nmap(id) === id;\n\n// composition\ncompose(map(f), map(g)) === map(compose(f, g));\n```\n\nThe *identity* law is simple, but important. These laws are runnable bits of code so we can try them on our own functors to validate their legitimacy.\n\n```js\nconst idLaw1 = map(id);\nconst idLaw2 = id;\n\nidLaw1(Container.of(2)); // Container(2)\nidLaw2(Container.of(2)); // Container(2)\n```\n\nYou see, they are equal. Next let's look at composition.\n\n```js\nconst compLaw1 = compose(map(append(' world')), map(append(' cruel')));\nconst compLaw2 = map(compose(append(' world'), append(' cruel')));\n\ncompLaw1(Container.of('Goodbye')); // Container('Goodbye cruel world')\ncompLaw2(Container.of('Goodbye')); // Container('Goodbye cruel world')\n```\n\nIn category theory, functors take the objects and morphisms of a category and map them to a different category. By definition, this new category must have an identity and the ability to compose morphisms, but we needn't check because the aforementioned laws ensure these are preserved.\n\nPerhaps our definition of a category is still a bit fuzzy. You can think of a category as a network of objects with morphisms that connect them. So a functor would map the one category to the other without breaking the network. If an object `a` is in our source category `C`, when we map it to category `D` with functor `F`, we refer to that object as `F a` (If you put it together what does that spell?!). Perhaps, it's better to look at a diagram:\n\n<img src=\"images/catmap.png\" alt=\"Categories mapped\" />\n\nFor instance, `Maybe` maps our category of types and functions to a category where each object may not exist and each morphism has a `null` check. We accomplish this in code by surrounding each function with `map` and each type with our functor. We know that each of our normal types and functions will continue to compose in this new world. Technically, each functor in our code maps to a sub category of types and functions which makes all functors a particular brand called endofunctors, but for our purposes, we'll think of it as a different category.\n\nWe can also visualize the mapping of a morphism and its corresponding objects with this diagram:\n\n<img src=\"images/functormap.png\" alt=\"functor diagram\" />\n\nIn addition to visualizing the mapped morphism from one category to another under the functor `F`, we see that the diagram commutes, which is to say, if you follow the arrows each route produces the same result. The different routes mean different behavior, but we always end at the same type. This formalism gives us principled ways to reason about our code - we can boldly apply formulas without having to parse and examine each individual scenario. Let's take a concrete example.\n\n```js\n// topRoute :: String -> Maybe String\nconst topRoute = compose(Maybe.of, reverse);\n\n// bottomRoute :: String -> Maybe String\nconst bottomRoute = compose(map(reverse), Maybe.of);\n\ntopRoute('hi'); // Just('ih')\nbottomRoute('hi'); // Just('ih')\n```\n\nOr visually:\n\n<img src=\"images/functormapmaybe.png\" alt=\"functor diagram 2\" />\n\nWe can instantly see and refactor code based on properties held by all functors.\n\nFunctors can stack:\n\n```js\nconst nested = Task.of([Either.of('pillows'), left('no sleep for you')]);\n\nmap(map(map(toUpperCase)), nested);\n// Task([Right('PILLOWS'), Left('no sleep for you')])\n```\n\nWhat we have here with `nested` is a future array of elements that might be errors. We `map` to peel back each layer and run our function on the elements. We see no callbacks, if/else's, or for loops; just an explicit context. We do, however, have to `map(map(map(f)))`. We can instead compose functors. You heard me correctly:\n\n```js\nclass Compose {\n  constructor(fgx) {\n    this.getCompose = fgx;\n  }\n\n  static of(fgx) {\n    return new Compose(fgx);\n  }\n\n  map(fn) {\n    return new Compose(map(map(fn), this.getCompose));\n  }\n}\n\nconst tmd = Task.of(Maybe.of('Rock over London'));\n\nconst ctmd = Compose.of(tmd);\n\nconst ctmd2 = map(append(', rock on, Chicago'), ctmd);\n// Compose(Task(Just('Rock over London, rock on, Chicago')))\n\nctmd2.getCompose;\n// Task(Just('Rock over London, rock on, Chicago'))\n```\n\nThere, one `map`. Functor composition is associative and earlier, we defined `Container`, which is actually called the `Identity` functor. If we have identity and associative composition we have a category. This particular category has categories as objects and functors as morphisms, which is enough to make one's brain perspire. We won't delve too far into this, but it's nice to appreciate the architectural implications or even just the simple abstract beauty in the pattern.\n\n\n## In Summary\n\nWe've seen a few different functors, but there are infinitely many. Some notable omissions are iterable data structures like trees, lists, maps, pairs, you name it. Event streams and observables are both functors. Others can be for encapsulation or even just type modelling. Functors are all around us and we'll use them extensively throughout the book.\n\nWhat about calling a function with multiple functor arguments? How about working with an order sequence of impure or async actions? We haven't yet acquired the full tool set for working in this boxed up world. Next, we'll cut right to the chase and look at monads.\n\n[Chapter 09: Monadic Onions](ch09.md)\n\n## Exercises\n\n{% exercise %}  \nUse `add` and `map` to make a function that increments a value inside a functor.  \n  \n{% initial src=\"./exercises/ch08/exercise_a.js#L3;\" %}  \n```js  \n// incrF :: Functor f => f Int -> f Int  \nconst incrF = undefined;  \n```  \n  \n{% solution src=\"./exercises/ch08/solution_a.js\" %}  \n{% validation src=\"./exercises/ch08/validation_a.js\" %}  \n{% context src=\"./exercises/support.js\" %}  \n{% endexercise %}  \n\n\n---\n\n  \nGiven the following User object:  \n  \n```js  \nconst user = { id: 2, name: 'Albert', active: true };  \n```  \n  \n{% exercise %}  \nUse `safeProp` and `head` to find the first initial of the user.  \n  \n{% initial src=\"./exercises/ch08/exercise_b.js#L7;\" %}  \n```js  \n// initial :: User -> Maybe String  \nconst initial = undefined;  \n```  \n  \n{% solution src=\"./exercises/ch08/solution_b.js\" %}  \n{% validation src=\"./exercises/ch08/validation_b.js\" %}  \n{% context src=\"./exercises/support.js\" %}  \n{% endexercise %}  \n\n\n---\n\n\nGiven the following helper functions:\n\n```js\n// showWelcome :: User -> String\nconst showWelcome = compose(concat('Welcome '), prop('name'));\n\n// checkActive :: User -> Either String User\nconst checkActive = function checkActive(user) {\n  return user.active\n    ? Either.of(user)\n    : left('Your account is not active');\n};\n```\n\n{% exercise %}  \nWrite a function that uses `checkActive` and `showWelcome` to grant access or return the error.\n\n{% initial src=\"./exercises/ch08/exercise_c.js#L15;\" %}  \n```js\n// eitherWelcome :: User -> Either String String\nconst eitherWelcome = undefined;\n```\n\n\n{% solution src=\"./exercises/ch08/solution_c.js\" %}  \n{% validation src=\"./exercises/ch08/validation_c.js\" %}  \n{% context src=\"./exercises/support.js\" %}  \n{% endexercise %}  \n\n\n---\n\n\nWe now consider the following functions:\n\n```js\n// validateUser :: (User -> Either String ()) -> User -> Either String User\nconst validateUser = curry((validate, user) => validate(user).map(_ => user));\n\n// save :: User -> IO User\nconst save = user => new IO(() => ({ ...user, saved: true }));\n```\n\n{% exercise %}  \nWrite a function `validateName` which checks whether a user has a name longer than 3 characters\nor return an error message. Then use `either`, `showWelcome` and `save` to write a `register`\nfunction to signup and welcome a user when the validation is ok.\n\nRemember either's two arguments must return the same type.\n\n{% initial src=\"./exercises/ch08/exercise_d.js#L15;\" %}  \n```js\n// validateName :: User -> Either String ()\nconst validateName = undefined;\n\n// register :: User -> IO String\nconst register = compose(undefined, validateUser(validateName));\n```\n\n\n{% solution src=\"./exercises/ch08/solution_d.js\" %}  \n{% validation src=\"./exercises/ch08/validation_d.js\" %}  \n{% context src=\"./exercises/support.js\" %}  \n{% endexercise %}  \n"
  },
  {
    "path": "ch09.md",
    "content": "# Chapter 09: Monadic Onions\n\n## Pointy Functor Factory\n\nBefore we go any further, I have a confession to make: I haven't been fully honest about that `of` method we've placed on each of our types. Turns out, it is not there to avoid the `new` keyword, but rather to place values in what's called a *default minimal context*. Yes, `of` does not actually take the place of a constructor - it is part of an important interface we call *Pointed*.\n\n> A *pointed functor* is a functor with an `of` method\n\nWhat's important here is the ability to drop any value in our type and start mapping away.\n\n```js\nIO.of('tetris').map(concat(' master'));\n// IO('tetris master')\n\nMaybe.of(1336).map(add(1));\n// Maybe(1337)\n\nTask.of([{ id: 2 }, { id: 3 }]).map(map(prop('id')));\n// Task([2,3])\n\nEither.of('The past, present and future walk into a bar...').map(concat('it was tense.'));\n// Right('The past, present and future walk into a bar...it was tense.')\n```\n\nIf you recall, `IO` and `Task`'s constructors expect a function as their argument, but `Maybe` and `Either` do not. The motivation for this interface is a common, consistent way to place a value into our functor without the complexities and specific demands of constructors. The term \"default minimal context\" lacks precision, yet captures the idea well: we'd like to lift any value in our type and `map` away per usual with the expected behaviour of whichever functor.\n\nOne important correction I must make at this point, pun intended, is that `Left.of` doesn't make any sense. Each functor must have one way to place a value inside it and with `Either`, that's `new Right(x)`. We define `of` using `Right` because if our type *can* `map`, it *should* `map`. Looking at the examples above, we should have an intuition about how `of` will usually work and `Left` breaks that mold.\n\nYou may have heard of functions such as `pure`, `point`, `unit`, and `return`. These are various monikers for our `of` method, international function of mystery. `of` will become important when we start using monads because, as we will see, it's our responsibility to place values back into the type manually.\n\nTo avoid the `new` keyword, there are several standard JavaScript tricks or libraries so let's use them and use `of` like a responsible adult from here on out. I recommend using functor instances from `folktale`, `ramda` or `fantasy-land` as they provide the correct `of` method as well as nice constructors that don't rely on `new`.\n\n\n## Mixing Metaphors\n\n<img src=\"images/onion.png\" alt=\"onion\" />\n\nYou see, in addition to space burritos (if you've heard the rumors), monads are like onions. Allow me to demonstrate with a common situation:\n\n```js\nconst fs = require('fs');\n\n// readFile :: String -> IO String\nconst readFile = filename => new IO(() => fs.readFileSync(filename, 'utf-8'));\n\n// print :: String -> IO String\nconst print = x => new IO(() => {\n  console.log(x);\n  return x;\n});\n\n// cat :: String -> IO (IO String)\nconst cat = compose(map(print), readFile);\n\ncat('.git/config');\n// IO(IO('[core]\\nrepositoryformatversion = 0\\n'))\n```\n\nWhat we've got here is an `IO` trapped inside another `IO` because `print` introduced a second `IO` during our `map`. To continue working with our string, we must `map(map(f))` and to observe the effect, we must `unsafePerformIO().unsafePerformIO()`.\n\n```js\n// cat :: String -> IO (IO String)\nconst cat = compose(map(print), readFile);\n\n// catFirstChar :: String -> IO (IO String)\nconst catFirstChar = compose(map(map(head)), cat);\n\ncatFirstChar('.git/config');\n// IO(IO('['))\n```\n\nWhile it is nice to see that we have two effects packaged up and ready to go in our application, it feels a bit like working in two hazmat suits and we end up with an uncomfortably awkward API. Let's look at another situation:\n\n```js\n// safeProp :: Key -> {Key: a} -> Maybe a\nconst safeProp = curry((x, obj) => Maybe.of(obj[x]));\n\n// safeHead :: [a] -> Maybe a\nconst safeHead = safeProp(0);\n\n// firstAddressStreet :: User -> Maybe (Maybe (Maybe Street))\nconst firstAddressStreet = compose(\n  map(map(safeProp('street'))),\n  map(safeHead),\n  safeProp('addresses'),\n);\n\nfirstAddressStreet({\n  addresses: [{ street: { name: 'Mulburry', number: 8402 }, postcode: 'WC2N' }],\n});\n// Maybe(Maybe(Maybe({name: 'Mulburry', number: 8402})))\n```\n\nAgain, we see this nested functor situation where it's neat to see there are three possible failures in our function, but it's a little presumptuous to expect a caller to `map` three times to get at the value - we'd only just met. This pattern will arise time and time again and it is the primary situation where we'll need to shine the mighty monad symbol into the night sky.\n\nI said monads are like onions because tears well up as we peel back each layer of the nested functor with `map` to get at the inner value. We can dry our eyes, take a deep breath, and use a method called `join`.\n\n```js\nconst mmo = Maybe.of(Maybe.of('nunchucks'));\n// Maybe(Maybe('nunchucks'))\n\nmmo.join();\n// Maybe('nunchucks')\n\nconst ioio = IO.of(IO.of('pizza'));\n// IO(IO('pizza'))\n\nioio.join();\n// IO('pizza')\n\nconst ttt = Task.of(Task.of(Task.of('sewers')));\n// Task(Task(Task('sewers')));\n\nttt.join();\n// Task(Task('sewers'))\n```\n\nIf we have two layers of the same type, we can smash them together with `join`. This ability to join together, this functor matrimony, is what makes a monad a monad. Let's inch toward the full definition with something a little more accurate:\n\n> Monads are pointed functors that can flatten\n\nAny functor which defines a `join` method, has an `of` method, and obeys a few laws is a monad. Defining `join` is not too difficult so let's do so for `Maybe`:\n\n```js\nMaybe.prototype.join = function join() {\n  return this.isNothing() ? Maybe.of(null) : this.$value;\n};\n```\n\nThere, simple as consuming one's twin in the womb. If we have a `Maybe(Maybe(x))` then `.$value` will just remove the unnecessary extra layer and we can safely `map` from there. Otherwise, we'll just have the one `Maybe` as nothing would have been mapped in the first place.\n\nNow that we have a `join` method, let's sprinkle some magic monad dust over the `firstAddressStreet` example and see it in action:\n\n```js\n// join :: Monad m => m (m a) -> m a\nconst join = mma => mma.join();\n\n// firstAddressStreet :: User -> Maybe Street\nconst firstAddressStreet = compose(\n  join,\n  map(safeProp('street')),\n  join,\n  map(safeHead), safeProp('addresses'),\n);\n\nfirstAddressStreet({\n  addresses: [{ street: { name: 'Mulburry', number: 8402 }, postcode: 'WC2N' }],\n});\n// Maybe({name: 'Mulburry', number: 8402})\n```\n\nWe added `join` wherever we encountered the nested `Maybe`'s to keep them from getting out of hand. Let's do the same with `IO` to give us a feel for that.\n\n```js\nIO.prototype.join = function() {\n  const $ = this;\n  return new IO(() => $.unsafePerformIO().unsafePerformIO());\n};\n```\n\nWe simply bundle running the two layers of IO sequentially: outer then inner. Mind you, we have not thrown out purity, but merely repackaged the excessive two layers of shrink wrap into one easier-to-open package.\n\n```js\n// log :: a -> IO a\nconst log = x => new IO(() => {\n  console.log(x);\n  return x;\n});\n\n// setStyle :: Selector -> CSSProps -> IO DOM\nconst setStyle =\n  curry((sel, props) => new IO(() => jQuery(sel).css(props)));\n\n// getItem :: String -> IO String\nconst getItem = key => new IO(() => localStorage.getItem(key));\n\n// applyPreferences :: String -> IO DOM\nconst applyPreferences = compose(\n  join,\n  map(setStyle('#main')),\n  join,\n  map(log),\n  map(JSON.parse),\n  getItem,\n);\n\napplyPreferences('preferences').unsafePerformIO();\n// Object {backgroundColor: \"green\"}\n// <div style=\"background-color: 'green'\"/>\n```\n\n`getItem` returns an `IO String` so we `map` to parse it. Both `log` and `setStyle` return `IO`'s themselves so we must `join` to keep our nesting under control.\n\n## My Chain Hits My Chest\n\n<img src=\"images/chain.jpg\" alt=\"chain\" />\n\nYou might have noticed a pattern. We often end up calling `join` right after a `map`. Let's abstract this into a function called `chain`.\n\n```js\n// chain :: Monad m => (a -> m b) -> m a -> m b\nconst chain = curry((f, m) => m.map(f).join());\n\n// or\n\n// chain :: Monad m => (a -> m b) -> m a -> m b\nconst chain = f => compose(join, map(f));\n```\n\nWe'll just bundle up this map/join combo into a single function. If you've read about monads previously, you might have seen `chain` called `>>=` (pronounced bind) or `flatMap` which are all aliases for the same concept. I personally think `flatMap` is the most accurate name, but we'll stick with `chain` as it's the widely accepted name in JS. Let's refactor the two examples above with `chain`:\n\n```js\n// map/join\nconst firstAddressStreet = compose(\n  join,\n  map(safeProp('street')),\n  join,\n  map(safeHead),\n  safeProp('addresses'),\n);\n\n// chain\nconst firstAddressStreet = compose(\n  chain(safeProp('street')),\n  chain(safeHead),\n  safeProp('addresses'),\n);\n\n// map/join\nconst applyPreferences = compose(\n  join,\n  map(setStyle('#main')),\n  join,\n  map(log),\n  map(JSON.parse),\n  getItem,\n);\n\n// chain\nconst applyPreferences = compose(\n  chain(setStyle('#main')),\n  chain(log),\n  map(JSON.parse),\n  getItem,\n);\n```\n\nI swapped out any `map/join` with our new `chain` function to tidy things up a bit. Cleanliness is nice and all, but there's more to `chain` than meets the eye - it's more of a tornado than a vacuum. Because `chain` effortlessly nests effects, we can capture both *sequence* and *variable assignment* in a purely functional way.\n\n```js\n// getJSON :: Url -> Params -> Task JSON\ngetJSON('/authenticate', { username: 'stale', password: 'crackers' })\n  .chain(user => getJSON('/friends', { user_id: user.id }));\n// Task([{name: 'Seimith', id: 14}, {name: 'Ric', id: 39}]);\n\n// querySelector :: Selector -> IO DOM\nquerySelector('input.username')\n  .chain(({ value: uname }) =>\n    querySelector('input.email')\n      .chain(({ value: email }) => IO.of(`Welcome ${uname} prepare for spam at ${email}`))\n  );\n// IO('Welcome Olivia prepare for spam at olivia@tremorcontrol.net');\n\nMaybe.of(3)\n  .chain(three => Maybe.of(2).map(add(three)));\n// Maybe(5);\n\nMaybe.of(null)\n  .chain(safeProp('address'))\n  .chain(safeProp('street'));\n// Maybe(null);\n```\n\nWe could have written these examples with `compose`, but we'd need a few helper functions and this style lends itself to explicit variable assignment via closure anyhow. Instead we're using the infix version of `chain` which, incidentally, can be derived from `map` and `join` for any type automatically: `t.prototype.chain = function(f) { return this.map(f).join(); }`. We can also define `chain` manually if we'd like a false sense of performance, though we must take care to maintain the correct functionality - that is, it must equal `map` followed by `join`. An interesting fact is that we can derive `map` for free if we've created `chain` simply by bottling the value back up when we're finished with `of`. With `chain`, we can also define `join` as `chain(id)`. It may feel like playing Texas Hold em' with a rhinestone magician in that I'm just pulling things out of my behind, but, as with most mathematics, all of these principled constructs are interrelated. Lots of these derivations are mentioned in the [fantasyland](https://github.com/fantasyland/fantasy-land) repo, which is the official specification for algebraic data types in JavaScript.\n\nAnyways, let's get to the examples above. In the first example, we see two `Task`'s chained in a sequence of asynchronous actions - first it retrieves the `user`, then it finds the friends with that user's id. We use `chain` to avoid a `Task(Task([Friend]))` situation.\n\nNext, we use `querySelector` to find a few different inputs and create a welcoming message. Notice how we have access to both `uname` and `email` at the innermost function - this is functional variable assignment at its finest. Since `IO` is graciously lending us its value, we are in charge of putting it back how we found it - we wouldn't want to break its trust (and our program). `IO.of` is the perfect tool for the job and it's why Pointed is an important prerequisite to the Monad interface. However, we could choose to `map` as that would also return the correct type:\n\n```js\nquerySelector('input.username').chain(({ value: uname }) =>\n  querySelector('input.email').map(({ value: email }) =>\n    `Welcome ${uname} prepare for spam at ${email}`));\n// IO('Welcome Olivia prepare for spam at olivia@tremorcontrol.net');\n```\n\nFinally, we have two examples using `Maybe`. Since `chain` is mapping under the hood, if any value is `null`, we stop the computation dead in its tracks.\n\nDon't worry if these examples are hard to grasp at first. Play with them. Poke them with a stick. Smash them to bits and reassemble. Remember to `map` when returning a \"normal\" value and `chain` when we're returning another functor. In the next chapter, we'll approach `Applicatives` and see nice tricks to make this kind of expressions nicer and highly readable.\n\nAs a reminder, this does not work with two different nested types. Functor composition and later, monad transformers, can help us in that situation.\n\n## Power Trip\n\nContainer style programming can be confusing at times. We sometimes find ourselves struggling to understand how many containers deep a value is or if we need `map` or `chain` (soon we'll see more container methods). We can greatly improve debugging with tricks like implementing `inspect` and we'll learn how to create a \"stack\" that can handle whatever effects we throw at it, but there are times when we question if it's worth the hassle.\n\nI'd like to swing the fiery monadic sword for a moment to exhibit the power of programming this way.\n\nLet's read a file, then upload it directly afterward:\n\n```js\n// readFile :: Filename -> Either String (Task Error String)\n// httpPost :: String -> String -> Task Error JSON\n// upload :: Filename -> Either String (Task Error JSON)\nconst upload = compose(map(chain(httpPost('/uploads'))), readFile);\n```\n\nHere, we are branching our code several times. Looking at the type signatures I can see that we protect against 3 errors - `readFile` uses `Either` to validate the input (perhaps ensuring the filename is present), `readFile` may error when accessing the file as expressed in the first type parameter of `Task`, and the upload may fail for whatever reason which is expressed by the `Error` in `httpPost`. We casually pull off two nested, sequential asynchronous actions with `chain`.\n\nAll of this is achieved in one linear left to right flow. This is all pure and declarative. It holds equational reasoning and reliable properties. We aren't forced to add needless and confusing variable names. Our `upload` function is written against generic interfaces and not specific one-off apis. It's one bloody line for goodness sake.\n\nFor contrast, let's look at the standard imperative way to pull this off:\n\n```js\n// upload :: Filename -> (String -> a) -> Void\nconst upload = (filename, callback) => {\n  if (!filename) {\n    throw new Error('You need a filename!');\n  } else {\n    readFile(filename, (errF, contents) => {\n      if (errF) throw errF;\n      httpPost('/uploads', contents, (errH, json) => {\n        if (errH) throw errH;\n        callback(json);\n      });\n    });\n  }\n};\n```\n\nWell isn't that the devil's arithmetic. We're pinballed through a volatile maze of madness. Imagine if it were a typical app that also mutated variables along the way! We'd be in the tar pit indeed.\n\n## Theory\n\nThe first law we'll look at is associativity, but perhaps not in the way you're used to it.\n\n```js\n// associativity\ncompose(join, map(join)) === compose(join, join);\n```\n\nThese laws get at the nested nature of monads so associativity focuses on joining the inner or outer types first to achieve the same result. A picture might be more instructive:\n\n<img src=\"images/monad_associativity.png\" alt=\"monad associativity law\" />\n\nStarting with the top left moving downward, we can `join` the outer two `M`'s of `M(M(M a))` first then cruise over to our desired `M a` with another `join`. Alternatively, we can pop the hood and flatten the inner two `M`'s with `map(join)`. We end up with the same `M a` regardless of if we join the inner or outer `M`'s first and that's what associativity is all about. It's worth noting that `map(join) != join`. The intermediate steps can vary in value, but the end result of the last `join` will be the same.\n\nThe second law is similar:\n\n```js\n// identity for all (M a)\ncompose(join, of) === compose(join, map(of)) === id;\n```\n\nIt states that, for any monad `M`, `of` and `join` amounts to `id`. We can also `map(of)` and attack it from the inside out. We call this \"triangle identity\" because it makes such a shape when visualized:\n\n<img src=\"images/triangle_identity.png\" alt=\"monad identity law\" />\n\nIf we start at the top left heading right, we can see that `of` does indeed drop our `M a` in another `M` container. Then if we move downward and `join` it, we get the same as if we just called `id` in the first place. Moving right to left, we see that if we sneak under the covers with `map` and call `of` of the plain `a`, we'll still end up with `M (M a)` and `join`ing will bring us back to square one.\n\nI should mention that I've just written `of`, however, it must be the specific `M.of` for whatever monad we're using.\n\nNow, I've seen these laws, identity and associativity, somewhere before... Hold on, I'm thinking...Yes of course! They are the laws for a category. But that would mean we need a composition function to complete the definition. Behold:\n\n```js\nconst mcompose = (f, g) => compose(chain(f), g);\n\n// left identity\nmcompose(M, f) === f;\n\n// right identity\nmcompose(f, M) === f;\n\n// associativity\nmcompose(mcompose(f, g), h) === mcompose(f, mcompose(g, h));\n```\n\nThey are the category laws after all. Monads form a category called the \"Kleisli category\" where all objects are monads and morphisms are chained functions. I don't mean to taunt you with bits and bobs of category theory without much explanation of how the jigsaw fits together. The intention is to scratch the surface enough to show the relevance and spark some interest while focusing on the practical properties we can use each day.\n\n\n## In Summary\n\nMonads let us drill downward into nested computations. We can assign variables, run sequential effects, perform asynchronous tasks, all without laying one brick in a pyramid of doom. They come to the rescue when a value finds itself jailed in multiple layers of the same type. With the help of the trusty sidekick \"pointed\", monads are able to lend us an unboxed value and know we'll be able to place it back in when we're done.\n\nYes, monads are very powerful, yet we still find ourselves needing some extra container functions. For instance, what if we wanted to run a list of api calls at once, then gather the results? We can accomplish this task with monads, but we'd have to wait for each one to finish before calling the next. What about combining several validations? We'd like to continue validating to gather the list of errors, but monads would stop the show after the first `Left` entered the picture.\n\nIn the next chapter, we'll see how applicative functors fit into the container world and why we prefer them to monads in many cases.\n\n[Chapter 10: Applicative Functors](ch10.md)\n\n\n## Exercises\n\n\nConsidering a User object as follow:\n\n```js\nconst user = {\n  id: 1,\n  name: 'Albert',\n  address: {\n    street: {\n      number: 22,\n      name: 'Walnut St',\n    },\n  },\n};\n```\n\n{% exercise %}\nUse `safeProp` and `map/join` or `chain` to safely get the street name when given a user\n\n{% initial src=\"./exercises/ch09/exercise_a.js#L16;\" %}\n```js\n// getStreetName :: User -> Maybe String\nconst getStreetName = undefined;\n```\n\n\n{% solution src=\"./exercises/ch09/solution_a.js\" %}\n{% validation src=\"./exercises/ch09/validation_a.js\" %}\n{% context src=\"./exercises/support.js\" %}\n{% endexercise %}\n\n\n---\n\n\nWe now consider the following items:\n\n```js\n// getFile :: IO String\nconst getFile = IO.of('/home/mostly-adequate/ch09.md');\n\n// pureLog :: String -> IO ()\nconst pureLog = str => new IO(() => console.log(str));\n```\n\n{% exercise %}\nUse getFile to get the filepath, remove the directory and keep only the basename,\nthen purely log it. Hint: you may want to use `split` and `last` to obtain the\nbasename from a filepath.\n\n{% initial src=\"./exercises/ch09/exercise_b.js#L13;\" %}\n```js\n// logFilename :: IO ()\nconst logFilename = undefined;\n\n```\n\n\n{% solution src=\"./exercises/ch09/solution_b.js\" %}\n{% validation src=\"./exercises/ch09/validation_b.js\" %}\n{% context src=\"./exercises/support.js\" %}\n{% endexercise %}\n\n\n---\n\nFor this exercise, we consider helpers with the following signatures:\n\n```js\n// validateEmail :: Email -> Either String Email\n// addToMailingList :: Email -> IO([Email])\n// emailBlast :: [Email] -> IO ()\n```\n\n{% exercise %}\nUse `validateEmail`, `addToMailingList` and `emailBlast` to create a function\nwhich adds a new email to the mailing list if valid, and then notify the whole\nlist.\n\n{% initial src=\"./exercises/ch09/exercise_c.js#L11;\" %}\n```js\n// joinMailingList :: Email -> Either String (IO ())\nconst joinMailingList = undefined;\n```\n\n\n{% solution src=\"./exercises/ch09/solution_c.js\" %}\n{% validation src=\"./exercises/ch09/validation_c.js\" %}\n{% context src=\"./exercises/support.js\" %}\n{% endexercise %}\n"
  },
  {
    "path": "ch10.md",
    "content": "# Chapter 10: Applicative Functors\n\n## Applying Applicatives\n\nThe name **applicative functor** is pleasantly descriptive given its functional origins. Functional programmers are notorious for coming up with names like `mappend` or `liftA4`, which seem perfectly natural when viewed in the math lab, but hold the clarity of an indecisive Darth Vader at the drive thru in any other context.\n\nAnyhow, the name should spill the beans on what this interface gives us: *the ability to apply functors to each other*.\n\nNow, why would a normal, rational person such as yourself want such a thing? What does it even *mean* to apply one functor to another?\n\nTo answer these questions, we'll start with a situation you may have already encountered in your functional travels. Let's say, hypothetically, that we have two functors (of the same type) and we'd like to call a function with both of their values as arguments. Something simple like adding the values of two `Container`s.\n\n```js\n// We can't do this because the numbers are bottled up.\nadd(Container.of(2), Container.of(3));\n// NaN\n\n// Let's use our trusty map\nconst containerOfAdd2 = map(add, Container.of(2));\n// Container(add(2))\n```\n\nWe have ourselves a `Container` with a partially applied function inside. More specifically, we have a `Container(add(2))` and we'd like to apply its `add(2)` to the `3` in `Container(3)` to complete the call. In other words, we'd like to apply one functor to another.\n\nNow, it just so happens that we already have the tools to accomplish this task. We can `chain` and then `map` the partially applied `add(2)` like so:\n\n```js\nContainer.of(2).chain(two => Container.of(3).map(add(two)));\n```\n\nThe issue here is that we are stuck in the sequential world of monads wherein nothing may be evaluated until the previous monad has finished its business. We have ourselves two strong, independent values and I should think it unnecessary to delay the creation of `Container(3)` merely to satisfy the monad's sequential demands.\n\nIn fact, it would be lovely if we could succinctly apply one functor's contents to another's value without these needless functions and variables should we find ourselves in this pickle jar.\n\n\n## Ships in Bottles\n\n<img src=\"images/ship_in_a_bottle.jpg\" alt=\"https://www.deviantart.com/hollycarden\" />\n\n`ap` is a function that can apply the function contents of one functor to the value contents of another. Say that five times fast.\n\n```js\nContainer.of(add(2)).ap(Container.of(3));\n// Container(5)\n\n// all together now\n\nContainer.of(2).map(add).ap(Container.of(3));\n// Container(5)\n```\n\nThere we are, nice and neat. Good news for `Container(3)` as it's been set free from the jail of the nested monadic function. It's worth mentioning again that `add`, in this case, gets partially applied during the first `map` so this only works when `add` is curried.\n\nWe can define `ap` like so:\n\n```js\nContainer.prototype.ap = function (otherContainer) {\n  return otherContainer.map(this.$value);\n};\n```\n\nRemember, `this.$value` will be a function and we'll be accepting another functor so we need only `map` it. And with that we have our interface definition:\n\n\n> An *applicative functor* is a pointed functor with an `ap` method\n\nNote the dependence on **pointed**. The pointed interface is crucial here as we'll see throughout the following examples.\n\nNow, I sense your skepticism (or perhaps confusion and horror), but keep an open mind; this `ap` character will prove useful. Before we get into it, let's explore a nice property.\n\n```js\nF.of(x).map(f) === F.of(f).ap(F.of(x));\n```\n\nIn proper English, mapping `f` is equivalent to `ap`ing a functor of `f`. Or in properer English, we can place `x` into our container and `map(f)` OR we can lift both `f` and `x` into our container and `ap` them. This allows us to write in a left-to-right fashion:\n\n```js\nMaybe.of(add).ap(Maybe.of(2)).ap(Maybe.of(3));\n// Maybe(5)\n\nTask.of(add).ap(Task.of(2)).ap(Task.of(3));\n// Task(5)\n```\n\nOne might even recognise the vague shape of a normal function call if viewed mid squint. We'll look at the pointfree version later in the chapter, but for now, this is the preferred way to write such code. Using `of`, each value gets transported to the magical land of containers, this parallel universe where each application can be async or null or what have you and `ap` will apply functions within this fantastical place. It's like building a ship in a bottle.\n\nDid you see there? We used `Task` in our example. This is a prime situation where applicative functors pull their weight. Let's look at a more in-depth example.\n\n## Coordination Motivation\n\nSay we're building a travel site and we'd like to retrieve both a list of tourist destinations and local events. Each of these are separate, stand-alone api calls.\n\n```js\n// Http.get :: String -> Task Error HTML\n\nconst renderPage = curry((destinations, events) => { /* render page */ });\n\nTask.of(renderPage).ap(Http.get('/destinations')).ap(Http.get('/events'));\n// Task(\"<div>some page with dest and events</div>\")\n```\n\nBoth `Http` calls will happen instantly and `renderPage` will be called when both are resolved. Contrast this with the monadic version where one `Task` must finish before the next fires off. Since we don't need the destinations to retrieve events, we are free from sequential evaluation.\n\nAgain, because we're using partial application to achieve this result, we must ensure `renderPage` is curried or it will not wait for both `Tasks` to finish. Incidentally, if you've ever had to do such a thing manually, you'll appreciate the astonishing simplicity of this interface. This is the kind of beautiful code that takes us one step closer to the singularity.\n\nLet's look at another example.\n\n```js\n// $ :: String -> IO DOM\nconst $ = selector => new IO(() => document.querySelector(selector));\n\n// getVal :: String -> IO String\nconst getVal = compose(map(prop('value')), $);\n\n// signIn :: String -> String -> Bool -> User\nconst signIn = curry((username, password, rememberMe) => { /* signing in */ });\n\nIO.of(signIn).ap(getVal('#email')).ap(getVal('#password')).ap(IO.of(false));\n// IO({ id: 3, email: 'gg@allin.com' })\n```\n\n`signIn` is a curried function of 3 arguments so we have to `ap` accordingly. With each `ap`, `signIn` receives one more argument until it is complete and runs. We can continue this pattern with as many arguments as necessary. Another thing to note is that two arguments end up naturally in `IO` whereas the last one needs a little help from `of` to lift it into `IO` since `ap` expects the function and all its arguments to be in the same type.\n\n## Bro, Do You Even Lift?\n\nLet's examine a pointfree way to write these applicative calls. Since we know `map` is equal to `of/ap`, we can write generic functions that will `ap` as many times as we specify:\n\n```js\nconst liftA2 = curry((g, f1, f2) => f1.map(g).ap(f2));\n\nconst liftA3 = curry((g, f1, f2, f3) => f1.map(g).ap(f2).ap(f3));\n\n// liftA4, etc\n```\n\n`liftA2` is a strange name. It sounds like one of the finicky freight elevators in a rundown factory or a vanity plate for a cheap limo company. Once enlightened, however, it's self explanatory: lift these pieces into the applicative functor world.\n\nWhen I first saw this 2-3-4 nonsense it struck me as ugly and unnecessary. After all, we can check the arity of functions in JavaScript and build this up dynamically. However, it is often useful to partially apply `liftA(N)` itself, so it cannot vary in argument length.\n\nLet's see this in use:\n\n```js\n// checkEmail :: User -> Either String Email\n// checkName :: User -> Either String String\n\nconst user = {\n  name: 'John Doe',\n  email: 'blurp_blurp',\n};\n\n//  createUser :: Email -> String -> IO User\nconst createUser = curry((email, name) => { /* creating... */ });\n\nEither.of(createUser).ap(checkEmail(user)).ap(checkName(user));\n// Left('invalid email')\n\nliftA2(createUser, checkEmail(user), checkName(user));\n// Left('invalid email')\n```\n\nSince `createUser` takes two arguments, we use the corresponding `liftA2`. The two statements are equivalent, but the `liftA2` version has no mention of `Either`. This makes it more generic and flexible since we are no longer married to a specific type.\n\n\nLet's see the previous examples written this way:\n\n```js\nliftA2(add, Maybe.of(2), Maybe.of(3));\n// Maybe(5)\n\nliftA2(renderPage, Http.get('/destinations'), Http.get('/events'));\n// Task('<div>some page with dest and events</div>')\n\nliftA3(signIn, getVal('#email'), getVal('#password'), IO.of(false));\n// IO({ id: 3, email: 'gg@allin.com' })\n```\n\n\n## Operators\n\nIn languages like Haskell, Scala, PureScript, and Swift, where it is possible to create your own infix operators you may see syntax like this:\n\n```hs\n-- Haskell / PureScript\nadd <$> Right 2 <*> Right 3\n```\n\n```js\n// JavaScript\nmap(add, Right(2)).ap(Right(3));\n```\n\nIt's helpful to know that `<$>` is `map` (aka `fmap`) and `<*>` is just `ap`. This allows for a more natural function application style and can help remove some parenthesis.\n\n## Free Can Openers\n<img src=\"images/canopener.jpg\" alt=\"http://www.breannabeckmeyer.com/\" />\n\nWe haven't spoken much about derived functions. Seeing as all of these interfaces are built off of each other and obey a set of laws, we can define some weaker interfaces in terms of the stronger ones.\n\nFor instance, we know that an applicative is first a functor, so if we have an applicative instance, surely we can define a functor for our type.\n\nThis kind of perfect computational harmony is possible because we're working within a mathematical framework. Mozart couldn't have done better even if he had torrented Ableton as a child.\n\nI mentioned earlier that `of/ap` is equivalent to `map`. We can use this knowledge to define `map` for free:\n\n```js\n// map derived from of/ap\nX.prototype.map = function map(f) {\n  return this.constructor.of(f).ap(this);\n};\n```\n\nMonads are at the top of the food chain, so to speak, so if we have `chain`, we get functor and applicative for free:\n\n```js\n// map derived from chain\nX.prototype.map = function map(f) {\n  return this.chain(a => this.constructor.of(f(a)));\n};\n\n// ap derived from chain/map\nX.prototype.ap = function ap(other) {\n  return this.chain(f => other.map(f));\n};\n```\n\nIf we can define a monad, we can define both the applicative and functor interfaces. This is quite remarkable as we get all of these can openers for free. We can even examine a type and automate this process.\n\nIt should be pointed out that part of `ap`'s appeal is the ability to run things concurrently so defining it via `chain` is missing out on that optimization. Despite that, it's good to have an immediate working interface while one works out the best possible implementation.\n\nWhy not just use monads and be done with it, you ask? It's good practice to work with the level of power you need, no more, no less. This keeps cognitive load to a minimum by ruling out possible functionality. For this reason, it's good to favor applicatives over monads.\n\nMonads have the unique ability to sequence computation, assign variables, and halt further execution all thanks to the downward nesting structure. When one sees applicatives in use, they needn't concern themselves with any of that business.\n\nNow, on to the legalities ...\n\n## Laws\n\nLike the other mathematical constructs we've explored, applicative functors hold some useful properties for us to rely on in our daily code. First off, you should know that applicatives are \"closed under composition\", meaning `ap` will never change container types on us (yet another reason to favor over monads). That's not to say we cannot have multiple different effects - we can stack our types knowing that they will remain the same during the entirety of our application.\n\nTo demonstrate:\n\n```js\nconst tOfM = compose(Task.of, Maybe.of);\n\nliftA2(liftA2(concat), tOfM('Rainy Days and Mondays'), tOfM(' always get me down'));\n// Task(Maybe(Rainy Days and Mondays always get me down))\n```\n\nSee, no need to worry about different types getting in the mix.\n\nTime to look at our favorite categorical law: *identity*:\n\n### Identity\n\n```js\n// identity\nA.of(id).ap(v) === v;\n```\n\nRight, so applying `id` all from within a functor shouldn't alter the value in `v`. For example:\n\n```js\nconst v = Identity.of('Pillow Pets');\nIdentity.of(id).ap(v) === v;\n```\n\n`Identity.of(id)` makes me chuckle at its futility. Anyway, what's interesting is that, as we've already established, `of/ap` is the same as `map` so this law follows directly from functor identity: `map(id) == id`.\n\nThe beauty in using these laws is that, like a militant kindergarten gym coach, they force all of our interfaces to play well together.\n\n### Homomorphism\n\n```js\n// homomorphism\nA.of(f).ap(A.of(x)) === A.of(f(x));\n```\n\nA *homomorphism* is just a structure preserving map. In fact, a functor is just a *homomorphism* between categories as it preserves the original category's structure under the mapping.\n\n\nWe're really just stuffing our normal functions and values into a container and running the computation in there so it should come as no surprise that we will end up with the same result if we apply the whole thing inside the container (left side of the equation) or apply it outside, then place it in there (right side).\n\nA quick example:\n\n```js\nEither.of(toUpperCase).ap(Either.of('oreos')) === Either.of(toUpperCase('oreos'));\n```\n\n### Interchange\n\nThe *interchange* law states that it doesn't matter if we choose to lift our function into the left or right side of `ap`.\n\n```js\n// interchange\nv.ap(A.of(x)) === A.of(f => f(x)).ap(v);\n```\n\nHere is an example:\n\n```js\nconst v = Task.of(reverse);\nconst x = 'Sparklehorse';\n\nv.ap(Task.of(x)) === Task.of(f => f(x)).ap(v);\n```\n\n### Composition\n\nAnd finally composition which is just a way to check that our standard function composition holds when applying inside of containers.\n\n```js\n// composition\nA.of(compose).ap(u).ap(v).ap(w) === u.ap(v.ap(w));\n```\n\n```js\nconst u = IO.of(toUpperCase);\nconst v = IO.of(concat('& beyond'));\nconst w = IO.of('blood bath ');\n\nIO.of(compose).ap(u).ap(v).ap(w) === u.ap(v.ap(w));\n```\n\n## In Summary\n\nA good use case for applicatives is when one has multiple functor arguments. They give us the ability to apply functions to arguments all within the functor world. Though we could already do so with monads, we should prefer applicative functors when we aren't in need of monadic specific functionality.\n\nWe're almost finished with container apis. We've learned how to `map`, `chain`, and now `ap` functions. In the next chapter, we'll learn how to work better with multiple functors and disassemble them in a principled way.\n\n[Chapter 11: Transformation Again, Naturally](ch11.md)\n\n\n## Exercises\n\n{% exercise %}  \nWrite a function that adds two possibly null numbers together using `Maybe` and `ap`.  \n  \n{% initial src=\"./exercises/ch10/exercise_a.js#L3;\" %}  \n```js  \n// safeAdd :: Maybe Number -> Maybe Number -> Maybe Number  \nconst safeAdd = undefined;  \n```  \n  \n  \n{% solution src=\"./exercises/ch10/solution_a.js\" %}  \n{% validation src=\"./exercises/ch10/validation_a.js\" %}  \n{% context src=\"./exercises/support.js\" %}  \n{% endexercise %}  \n  \n  \n---  \n  \n  \n{% exercise %}  \nRewrite `safeAdd` from exercise_b to use `liftA2` instead of `ap`.  \n  \n{% initial src=\"./exercises/ch10/exercise_b.js#L3;\" %}  \n```js  \n// safeAdd :: Maybe Number -> Maybe Number -> Maybe Number  \nconst safeAdd = undefined;  \n```  \n  \n  \n{% solution src=\"./exercises/ch10/solution_b.js\" %}  \n{% validation src=\"./exercises/ch10/validation_b.js\" %}  \n{% context src=\"./exercises/support.js\" %}  \n{% endexercise %}  \n  \n  \n---  \n  \nFor the next exercise, we consider the following helpers:  \n  \n```js  \nconst localStorage = {  \n  player1: { id:1, name: 'Albert' },  \n  player2: { id:2, name: 'Theresa' },  \n};  \n  \n// getFromCache :: String -> IO User  \nconst getFromCache = x => new IO(() => localStorage[x]);  \n  \n// game :: User -> User -> String  \nconst game = curry((p1, p2) => `${p1.name} vs ${p2.name}`);  \n```  \n  \n{% exercise %}  \nWrite an IO that gets both player1 and player2 from the cache and starts the game.  \n  \n  \n{% initial src=\"./exercises/ch10/exercise_c.js#L16;\" %}  \n```js  \n// startGame :: IO String  \nconst startGame = undefined;  \n```  \n  \n  \n{% solution src=\"./exercises/ch10/solution_c.js\" %}  \n{% validation src=\"./exercises/ch10/validation_c.js\" %}  \n{% context src=\"./exercises/support.js\" %}  \n{% endexercise %}  \n"
  },
  {
    "path": "ch11.md",
    "content": "# Chapter 11: Transform Again, Naturally\n\nWe are about to discuss *natural transformations* in the context of practical utility in every day code. It just so happens they are a pillar of category theory and absolutely indispensable when applying mathematics to reason about and refactor our code. As such, I believe it is my duty to inform you about the lamentable injustice you are about to witness undoubtedly due to my limited scope. Let's begin.\n\n## Curse This Nest\n\nI'd like to address the issue of nesting. Not the instinctive urge felt by soon to be parents wherein they tidy and rearrange with obsessive compulsion, but the...well actually, come to think of it, that isn't far from the mark as we'll see in the coming chapters... In any case, what I mean by *nesting* is to have two or more different types all huddled together around a value, cradling it like a newborn, as it were.\n\n```js\nRight(Maybe('b'));\n\nIO(Task(IO(1000)));\n\n[Identity('bee thousand')];\n```\n\nUntil now, we've managed to evade this common scenario with carefully crafted examples, but in practice, as one codes, types tend to tangle themselves up like earbuds in an exorcism. If we don't meticulously keep our types organized as we go along, our code will read hairier than a beatnik in a cat café.\n\n## A Situational Comedy\n\n```js\n// getValue :: Selector -> Task Error (Maybe String)\n// postComment :: String -> Task Error Comment\n// validate :: String -> Either ValidationError String\n\n// saveComment :: () -> Task Error (Maybe (Either ValidationError (Task Error Comment)))\nconst saveComment = compose(\n  map(map(map(postComment))),\n  map(map(validate)),\n  getValue('#comment'),\n);\n```\n\nThe gang is all here, much to our type signature's dismay. Allow me to briefly explain the code. We start by getting the user input with `getValue('#comment')` which is an action which retrieves text on an element. Now, it might error finding the element or the value string may not exist so it returns `Task Error (Maybe String)`. After that, we must `map` over both the `Task` and the `Maybe` to pass our text to `validate`, which in turn, gives us back `Either` a `ValidationError` or our `String`. Then onto mapping for days to send the `String` in our current `Task Error (Maybe (Either ValidationError String))` into `postComment` which returns our resulting `Task`.\n\nWhat a frightful mess. A collage of abstract types, amateur type expressionism, polymorphic Pollock, monolithic Mondrian. There are many solutions to this common issue. We can compose the types into one monstrous container, sort and `join` a few, homogenize them, deconstruct them, and so on. In this chapter, we'll focus on homogenizing them via *natural transformations*.\n\n## All Natural\n\nA *Natural Transformation* is a \"morphism between functors\", that is, a function which operates on the containers themselves. Typewise, it is a function `(Functor f, Functor g) => f a -> g a`. What makes it special is that we cannot, for any reason, peek at the contents of our functor. Think of it as an exchange of highly classified information - the two parties oblivious to what's in the sealed manila envelope stamped \"top secret\". This is a structural operation. A functorial costume change. Formally, a *natural transformation* is any function for which the following holds:\n\n<img width=600 src=\"images/natural_transformation.png\" alt=\"natural transformation diagram\" />\n\nor in code:\n\n```js\n// nt :: (Functor f, Functor g) => f a -> g a\ncompose(map(f), nt) === compose(nt, map(f));\n```\n\nBoth the diagram and the code say the same thing: We can run our natural transformation then `map` or `map` then run our natural transformation and get the same result. Incidentally, that follows from a [free theorem](ch07.md#free-as-in-theorem) though natural transformations (and functors) are not limited to functions on types.\n\n## Principled Type Conversions\n\nAs programmers we are familiar with type conversions. We transform types like `Strings` into `Booleans` and `Integers` into `Floats` (though JavaScript only has `Numbers`). The difference here is simply that we're working with algebraic containers and we have some theory at our disposal.\n\nLet's look at some of these as examples:\n\n```js\n// idToMaybe :: Identity a -> Maybe a\nconst idToMaybe = x => Maybe.of(x.$value);\n\n// idToIO :: Identity a -> IO a\nconst idToIO = x => IO.of(x.$value);\n\n// eitherToTask :: Either a b -> Task a b\nconst eitherToTask = either(Task.rejected, Task.of);\n\n// ioToTask :: IO a -> Task () a\nconst ioToTask = x => new Task((reject, resolve) => resolve(x.unsafePerform()));\n\n// maybeToTask :: Maybe a -> Task () a\nconst maybeToTask = x => (x.isNothing ? Task.rejected() : Task.of(x.$value));\n\n// arrayToMaybe :: [a] -> Maybe a\nconst arrayToMaybe = x => Maybe.of(x[0]);\n```\n\nSee the idea? We're just changing one functor to another. We are permitted to lose information along the way so long as the value we'll `map` doesn't get lost in the shape shift shuffle. That is the whole point: `map` must carry on, according to our definition, even after the transformation.\n\nOne way to look at it is that we are transforming our effects. In that light, we can view `ioToTask` as converting synchronous to asynchronous or `arrayToMaybe` from nondeterminism to possible failure. Note that we cannot convert asynchronous to synchronous in JavaScript so we cannot write `taskToIO` - that would be a supernatural transformation.\n\n## Feature Envy\n\nSuppose we'd like to use some features from another type like `sortBy` on a `List`. *Natural transformations* provide a nice way to convert to the target type knowing our `map` will be sound.\n\n```js\n// arrayToList :: [a] -> List a\nconst arrayToList = List.of;\n\nconst doListyThings = compose(sortBy(h), filter(g), arrayToList, map(f));\nconst doListyThings_ = compose(sortBy(h), filter(g), map(f), arrayToList); // law applied\n```\n\nA wiggle of our nose, three taps of our wand, drop in `arrayToList`, and voilà! Our `[a]` is a `List a` and we can `sortBy` if we please.\n\nAlso, it becomes easier to optimize / fuse operations by moving `map(f)` to the left of *natural transformation* as shown in `doListyThings_`.\n\n## Isomorphic JavaScript\n\nWhen we can completely go back and forth without losing any information, that is considered an *isomorphism*. That's just a fancy word for \"holds the same data\". We say that two types are *isomorphic* if we can provide the \"to\" and \"from\" *natural transformations* as proof:\n\n```js\n// promiseToTask :: Promise a b -> Task a b\nconst promiseToTask = x => new Task((reject, resolve) => x.then(resolve).catch(reject));\n\n// taskToPromise :: Task a b -> Promise a b\nconst taskToPromise = x => new Promise((resolve, reject) => x.fork(reject, resolve));\n\nconst x = Promise.resolve('ring');\ntaskToPromise(promiseToTask(x)) === x;\n\nconst y = Task.of('rabbit');\npromiseToTask(taskToPromise(y)) === y;\n```\n\nQ.E.D. `Promise` and `Task` are *isomorphic*. We can also write a `listToArray` to complement our `arrayToList` and show that they are too. As a counter example, `arrayToMaybe` is not an *isomorphism* since it loses information:\n\n```js\n// maybeToArray :: Maybe a -> [a]\nconst maybeToArray = x => (x.isNothing ? [] : [x.$value]);\n\n// arrayToMaybe :: [a] -> Maybe a\nconst arrayToMaybe = x => Maybe.of(x[0]);\n\nconst x = ['elvis costello', 'the attractions'];\n\n// not isomorphic\nmaybeToArray(arrayToMaybe(x)); // ['elvis costello']\n\n// but is a natural transformation\ncompose(arrayToMaybe, map(replace('elvis', 'lou')))(x); // Just('lou costello')\n// ==\ncompose(map(replace('elvis', 'lou')), arrayToMaybe)(x); // Just('lou costello')\n```\n\nThey are indeed *natural transformations*, however, since `map` on either side yields the same result. I mention *isomorphisms* here, mid-chapter while we're on the subject, but don't let that fool you, they are an enormously powerful and pervasive concept. Anyways, let's move on.\n\n## A Broader Definition\n\nThese structural functions aren't limited to type conversions by any means.\n\nHere are a few different ones:\n\n```hs\nreverse :: [a] -> [a]\n\njoin :: (Monad m) => m (m a) -> m a\n\nhead :: [a] -> a\n\nof :: a -> f a\n```\n\nThe natural transformation laws hold for these functions too. One thing that might trip you up is that `head :: [a] -> a` can be viewed as `head :: [a] -> Identity a`. We are free to insert `Identity` wherever we please whilst proving laws since we can, in turn, prove that `a` is isomorphic to `Identity a` (see, I told you *isomorphisms* were pervasive).\n\n## One Nesting Solution\n\nBack to our comedic type signature. We can sprinkle in some *natural transformations* throughout the calling code to coerce each varying type so they are uniform and, therefore, `join`able.\n\n```js\n// getValue :: Selector -> Task Error (Maybe String)\n// postComment :: String -> Task Error Comment\n// validate :: String -> Either ValidationError String\n\n// saveComment :: () -> Task Error Comment\nconst saveComment = compose(\n  chain(postComment),\n  chain(eitherToTask),\n  map(validate),\n  chain(maybeToTask),\n  getValue('#comment'),\n);\n```\n\nSo what do we have here? We've simply added `chain(maybeToTask)` and `chain(eitherToTask)`. Both have the same effect; they naturally transform the functor our `Task` is holding into another `Task` then `join` the two. Like pigeon spikes on a window ledge, we avoid nesting right at the source. As they say in the city of light, \"Mieux vaut prévenir que guérir\" - an ounce of prevention is worth a pound of cure.\n\n## In Summary\n\n*Natural transformations* are functions on our functors themselves. They are an extremely important concept in category theory and will start to appear everywhere once more abstractions are adopted, but for now, we've scoped them to a few concrete applications. As we saw, we can achieve different effects by converting types with the guarantee that our composition will hold. They can also help us with nested types, although they have the general effect of homogenizing our functors to the lowest common denominator, which in practice, is the functor with the most volatile effects (`Task` in most cases).\n\nThis continual and tedious sorting of types is the price we pay for having materialized them - summoned them from the ether. Of course, implicit effects are much more insidious and so here we are fighting the good fight. We'll need a few more tools in our tackle before we can reel in the larger type amalgamations. Next up, we'll look at reordering our types with *Traversable*.\n\n[Chapter 12: Traversing the Stone](ch12.md)\n\n\n## Exercises\n\n{% exercise %}  \nWrite a natural transformation that converts `Either b a` to `Maybe a`\n  \n{% initial src=\"./exercises/ch11/exercise_a.js#L3;\" %}  \n```js  \n// eitherToMaybe :: Either b a -> Maybe a  \nconst eitherToMaybe = undefined;  \n```  \n  \n  \n{% solution src=\"./exercises/ch11/solution_a.js\" %}  \n{% validation src=\"./exercises/ch11/validation_a.js\" %}  \n{% context src=\"./exercises/support.js\" %}  \n{% endexercise %}  \n  \n  \n---  \n\n\n```js\n// eitherToTask :: Either a b -> Task a b\nconst eitherToTask = either(Task.rejected, Task.of);\n```\n\n{% exercise %}  \nUsing `eitherToTask`, simplify `findNameById` to remove the nested `Either`.\n  \n{% initial src=\"./exercises/ch11/exercise_b.js#L6;\" %}  \n```js  \n// findNameById :: Number -> Task Error (Either Error User)  \nconst findNameById = compose(map(map(prop('name'))), findUserById);  \n```  \n  \n  \n{% solution src=\"./exercises/ch11/solution_b.js\" %}  \n{% validation src=\"./exercises/ch11/validation_b.js\" %}  \n{% context src=\"./exercises/support.js\" %}  \n{% endexercise %}  \n  \n  \n---  \n\n\nAs a reminder, the following functions are available in the exercise's context:\n\n```hs\nsplit :: String -> String -> [String]\nintercalate :: String -> [String] -> String\n```\n\n{% exercise %}  \nWrite the isomorphisms between String and [Char].\n  \n{% initial src=\"./exercises/ch11/exercise_c.js#L8;\" %}  \n```js  \n// strToList :: String -> [Char]  \nconst strToList = undefined;  \n  \n// listToStr :: [Char] -> String  \nconst listToStr = undefined;  \n```  \n  \n  \n{% solution src=\"./exercises/ch11/solution_c.js\" %}  \n{% validation src=\"./exercises/ch11/validation_c.js\" %}  \n{% context src=\"./exercises/support.js\" %}  \n{% endexercise %}  \n"
  },
  {
    "path": "ch12.md",
    "content": "# Chapter 12: Traversing the Stone\n\nSo far, in our cirque du conteneur, you've seen us tame the ferocious [functor](ch08.md#my-first-functor), bending it to our will to perform any operation that strikes our fancy. You've been dazzled by the juggling of many dangerous effects at once using function [application](ch10.md) to collect the results. Sat there in amazement as containers vanished in thin air by [joining](ch09.md) them together. At the side effect sideshow, we've seen them [composed](ch08.md#a-spot-of-theory) into one. And most recently, we've ventured beyond what's natural and [transformed](ch11.md) one type into another before your very eyes.\n\nAnd now for our next trick, we'll look at traversals. We'll watch types soar over one another as if they were trapeze artists holding our value intact. We'll reorder effects like the trolleys in a tilt-a-whirl. When our containers get intertwined like the limbs of a contortionist, we can use this interface to straighten things out. We'll witness different effects with different orderings. Fetch me my pantaloons and slide whistle, let's get started.\n\n## Types n' Types\n\nLet's get weird:\n\n```js\n// readFile :: FileName -> Task Error String\n\n// firstWords :: String -> String\nconst firstWords = compose(intercalate(' '), take(3), split(' '));\n\n// tldr :: FileName -> Task Error String\nconst tldr = compose(map(firstWords), readFile);\n\nmap(tldr, ['file1', 'file2']);\n// [Task('hail the monarchy'), Task('smash the patriarchy')]\n```\n\nHere we read a bunch of files and end up with a useless array of tasks. How might we fork each one of these? It would be most agreeable if we could switch the types around to have `Task Error [String]` instead of `[Task Error String]`. That way, we'd have one future value holding all the results, which is much more amenable to our async needs than several future values arriving at their leisure.\n\nHere's one last example of a sticky situation:\n\n```js\n// getAttribute :: String -> Node -> Maybe String\n// $ :: Selector -> IO Node\n\n// getControlNode :: Selector -> IO (Maybe (IO Node))\nconst getControlNode = compose(map(map($)), map(getAttribute('aria-controls')), $);\n```\n\nLook at those `IO`s longing to be together. It'd be just lovely to `join` them, let them dance cheek to cheek, but alas a `Maybe` stands between them like a chaperone at prom. Our best move here would be to shift their positions next to one another, that way each type can be together at last and our signature can be simplified to `IO (Maybe Node)`.\n\n## Type Feng Shui\n\nThe *Traversable* interface consists of two glorious functions: `sequence` and `traverse`.\n\nLet's rearrange our types using `sequence`:\n\n```js\nsequence(List.of, Maybe.of(['the facts'])); // [Just('the facts')]\nsequence(Task.of, new Map({ a: Task.of(1), b: Task.of(2) })); // Task(Map({ a: 1, b: 2 }))\nsequence(IO.of, Either.of(IO.of('buckle my shoe'))); // IO(Right('buckle my shoe'))\nsequence(Either.of, [Either.of('wing')]); // Right(['wing'])\nsequence(Task.of, left('wing')); // Task(Left('wing'))\n```\n\nSee what has happened here? Our nested type gets turned inside out like a pair of leather trousers on a humid summer night. The inner functor is shifted to the outside and vice versa. It should be known that `sequence` is bit particular about its arguments. It looks like this:\n\n```js\n// sequence :: (Traversable t, Applicative f) => (a -> f a) -> t (f a) -> f (t a)\nconst sequence = curry((of, x) => x.sequence(of));\n```\n\nLet's start with the second argument. It must be a *Traversable* holding an *Applicative*, which sounds quite restrictive, but just so happens to be the case more often than not. It is the `t (f a)` which gets turned into a `f (t a)`. Isn't that expressive? It's clear as day the two types do-si-do around each other. That first argument there is merely a crutch and only necessary in an untyped language. It is a type constructor (our *of*) provided so that we can invert map-reluctant types like `Left` - more on that in a minute.\n\nUsing `sequence`, we can shift types around with the precision of a sidewalk thimblerigger. But how does it work? Let's look at how a type, say `Either`, would implement it:\n\n```js\nclass Right extends Either {\n  // ...\n  sequence(of) {\n    return this.$value.map(Either.of);\n  }\n}\n```\n\nAh yes, if our `$value` is a functor (it must be an applicative, in fact), we can simply `map` our constructor to leap frog the type.\n\nYou may have noticed that we've ignored the `of` entirely. It is passed in for the occasion where mapping is futile, as is the case with `Left`:\n\n```js\nclass Left extends Either {\n  // ...\n  sequence(of) {\n    return of(this);\n  }\n}\n```\n\nWe'd like the types to always end up in the same arrangement, therefore it is necessary for types like `Left` who don't actually hold our inner applicative to get a little help in doing so. The *Applicative* interface requires that we first have a *Pointed Functor* so we'll always have a `of` to pass in. In a language with a type system, the outer type can be inferred from the signature and does not need to be explicitly given.\n\n## Effect Assortment\n\nDifferent orders have different outcomes where our containers are concerned. If I have `[Maybe a]`, that's a collection of possible values whereas if I have a `Maybe [a]`, that's a possible collection of values. The former indicates we'll be forgiving and keep \"the good ones\", while the latter means it's an \"all or nothing\" type of situation. Likewise, `Either Error (Task Error a)` could represent a client side validation and `Task Error (Either Error a)` could be a server side one. Types can be swapped to give us different effects.\n\n```js\n// fromPredicate :: (a -> Bool) -> a -> Either e a\n\n// partition :: (a -> Bool) -> [a] -> [Either e a]\nconst partition = f => map(fromPredicate(f));\n\n// validate :: (a -> Bool) -> [a] -> Either e [a]\nconst validate = f => traverse(Either.of, fromPredicate(f));\n```\n\nHere we have two different functions based on if we `map` or `traverse`.  The first, `partition` will give us an array of `Left`s and `Right`s according to the predicate function. This is useful to keep precious data around for future use rather than filtering it out with the bathwater. `validate` instead will give us the first item that fails the predicate in `Left`, or all the items in `Right` if everything is hunky dory. By choosing a different type order, we get different behavior.\n\nLet's look at the `traverse` function of `List`, to see how the `validate` method is made. \n\n```js\ntraverse(of, fn) {\n    return this.$value.reduce(\n      (f, a) => fn(a).map(b => bs => bs.concat(b)).ap(f),\n      of(new List([])),\n    );\n  }\n```\n\nThis just runs a `reduce` on the list. The reduce function is `(f, a) => fn(a).map(b => bs => bs.concat(b)).ap(f)`, which looks a bit scary, so let's step through it.\n\n1. `reduce(..., ...)`\n\n   Remember the signature of `reduce :: [a] -> (f -> a -> f) -> f -> f`. The first argument is actually provided by the dot-notation on `$value`, so it's a list of things. \n   Then we need a function from a `f` (the accumulator) and a `a` (the iteree) to return us a new accumulator. \n\n2. `of(new List([]))`\n\n   The seed value is `of(new List([]))`, which in our case is `Right([]) :: Either e [a]`. Notice that `Either e [a]` will also be our final resulting type!\n\n3. `fn :: Applicative f => a -> f a`\n\n   If we apply it to our example above, `fn` is actually `fromPredicate(f) :: a -> Either e a`.  \n   > fn(a) :: Either e a\n\n4. `.map(b => bs => bs.concat(b))`\n\n   When `Right`, `Either.map` passes the right value to the function and returns a new `Right` with the result. In this case the function has one parameter (`b`), and returns another function (`bs => bs.concat(b)`, where `b` is in scope due to the closure). When `Left`, the left value is returned.  \n   > fn(a).map(b => bs => bs.concat(b)) :: Either e ([a] -> [a])\n\n5. .`ap(f)`\n\n   Remember that `f` is an Applicative here, so we can apply the function `bs => bs.concat(b)` to whatever value `bs :: [a]` is in `f`. Fortunately for us, `f` comes from our initial seed and has the following type: `f :: Either e [a]` which is by the way, preserved when we apply `bs => bs.concat(b)`. \n   When `f` is `Right`, this calls `bs => bs.concat(b)`, which returns a `Right` with the item added to the list. When `Left`, the left value (from the previous step or previous iteration respectively) is returned. \n   > fn(a).map(b => bs => bs.concat(b)).ap(f) :: Either e [a]\n\nThis apparently miraculous transformation is achieved with just 6 measly lines of code in `List.traverse`, and is accomplished with `of`, `map` and `ap`, so will work for any Applicative Functor. This is a great example \nof how those abstraction can help to write highly generic code with only a few assumptions (that can, incidentally, be declared and checked at the type level!).\n\n## Waltz of the Types\n\nTime to revisit and clean our initial examples.\n\n```js\n// readFile :: FileName -> Task Error String\n\n// firstWords :: String -> String\nconst firstWords = compose(intercalate(' '), take(3), split(' '));\n\n// tldr :: FileName -> Task Error String\nconst tldr = compose(map(firstWords), readFile);\n\ntraverse(Task.of, tldr, ['file1', 'file2']);\n// Task(['hail the monarchy', 'smash the patriarchy']);\n```\n\nUsing `traverse` instead of `map`, we've successfully herded those unruly `Task`s into a nice coordinated array of results. This is like `Promise.all()`, if you're familiar, except it isn't just a one-off, custom function, no, this works for any *traversable* type. These mathematical apis tend to capture most things we'd like to do in an interoperable, reusable way, rather than each library reinventing these functions for a single type.\n\nLet's clean up the last example for closure (no, not that kind):\n\n```js\n// getAttribute :: String -> Node -> Maybe String\n// $ :: Selector -> IO Node\n\n// getControlNode :: Selector -> IO (Maybe Node)\nconst getControlNode = compose(chain(traverse(IO.of, $)), map(getAttribute('aria-controls')), $);\n```\n\nInstead of `map(map($))` we have `chain(traverse(IO.of, $))` which inverts our types as it maps then flattens the two `IO`s via `chain`.\n\n## No Law and Order\n\nWell now, before you get all judgemental and bang the backspace button like a gavel to retreat from the chapter, take a moment to recognize that these laws are useful code guarantees. 'Tis my conjecture that the goal of most program architecture is an attempt to place useful restrictions on our code to narrow the possibilities, to guide us into the answers as designers and readers.\n\nAn interface without laws is merely indirection. Like any other mathematical structure, we must expose properties for our own sanity. This has a similar effect as encapsulation since it protects the data, enabling us to swap out the interface with another law abiding citizen.\n\nCome along now, we've got some laws to suss out.\n\n### Identity\n\n```js\nconst identity1 = compose(sequence(Identity.of), map(Identity.of));\nconst identity2 = Identity.of;\n\n// test it out with Right\nidentity1(Either.of('stuff'));\n// Identity(Right('stuff'))\n\nidentity2(Either.of('stuff'));\n// Identity(Right('stuff'))\n```\n\nThis should be straightforward. If we place an `Identity` in our functor, then turn it inside out with `sequence` that's the same as just placing it on the outside to begin with. We chose `Right` as our guinea pig as it is easy to try the law and inspect. An arbitrary functor there is normal, however, the use of a concrete functor here, namely `Identity` in the law itself might raise some eyebrows. Remember a [category](ch05.md#category-theory) is defined by morphisms between its objects that have associative composition and identity. When dealing with the category of functors, natural transformations are the morphisms and `Identity` is, well identity. The `Identity` functor is as fundamental in demonstrating laws as our `compose` function. In fact, we should give up the ghost and follow suit with our [Compose](ch08.md#a-spot-of-theory) type:\n\n### Composition\n\n```js\nconst comp1 = compose(sequence(Compose.of), map(Compose.of));\nconst comp2 = (Fof, Gof) => compose(Compose.of, map(sequence(Gof)), sequence(Fof));\n\n\n// Test it out with some types we have lying around\ncomp1(Identity(Right([true])));\n// Compose(Right([Identity(true)]))\n\ncomp2(Either.of, Array)(Identity(Right([true])));\n// Compose(Right([Identity(true)]))\n```\n\nThis law preserves composition as one would expect: if we swap compositions of functors, we shouldn't see any surprises since the composition is a functor itself. We arbitrarily chose `true`, `Right`, `Identity`, and `Array` to test it out. Libraries like [quickcheck](https://hackage.haskell.org/package/QuickCheck) or [jsverify](http://jsverify.github.io/) can help us test the law by fuzz testing the inputs.\n\nAs a natural consequence of the above law, we get the ability to [fuse traversals](https://www.cs.ox.ac.uk/jeremy.gibbons/publications/iterator.pdf), which is nice from a performance standpoint.\n\n### Naturality\n\n```js\nconst natLaw1 = (of, nt) => compose(nt, sequence(of));\nconst natLaw2 = (of, nt) => compose(sequence(of), map(nt));\n\n// test with a random natural transformation and our friendly Identity/Right functors.\n\n// maybeToEither :: Maybe a -> Either () a\nconst maybeToEither = x => (x.$value ? new Right(x.$value) : new Left());\n\nnatLaw1(Maybe.of, maybeToEither)(Identity.of(Maybe.of('barlow one')));\n// Right(Identity('barlow one'))\n\nnatLaw2(Either.of, maybeToEither)(Identity.of(Maybe.of('barlow one')));\n// Right(Identity('barlow one'))\n```\n\nThis is similar to our identity law. If we first swing the types around then run a natural transformation on the outside, that should equal mapping a natural transformation, then flipping the types.\n\nA natural consequence of this law is:\n\n```js\ntraverse(A.of, A.of) === A.of;\n```\n\nWhich, again, is nice from a performance standpoint.\n\n\n## In Summary\n\n*Traversable* is a powerful interface that gives us the ability to rearrange our types with the ease of a telekinetic interior decorator. We can achieve different effects with different orders as well as iron out those nasty type wrinkles that keep us from `join`ing them down. Next, we'll take a bit of a detour to see one of the most powerful interfaces of functional programming and perhaps even algebra itself: [Monoids bring it all together](ch13.md)\n\n## Exercises\n\nConsidering the following elements:\n\n```js\n// httpGet :: Route -> Task Error JSON\n\n// routes :: Map Route Route\nconst routes = new Map({ '/': '/', '/about': '/about' });\n```\n\n\n{% exercise %}  \nUse the traversable interface to change the type signature of `getJsons` to\nMap Route Route → Task Error (Map Route JSON)\n\n  \n{% initial src=\"./exercises/ch12/exercise_a.js#L11;\" %}  \n```js  \n// getJsons :: Map Route Route -> Map Route (Task Error JSON)\nconst getJsons = map(httpGet);\n```  \n  \n  \n{% solution src=\"./exercises/ch12/solution_a.js\" %}  \n{% validation src=\"./exercises/ch12/validation_a.js\" %}  \n{% context src=\"./exercises/support.js\" %}  \n{% endexercise %}  \n  \n  \n---  \n\n\nWe now define the following validation function:\n\n```js\n// validate :: Player -> Either String Player\nconst validate = player => (player.name ? Either.of(player) : left('must have name'));\n```\n\n\n{% exercise %}  \nUsing traversable, and the `validate` function, update `startGame` (and its signature)\nto only start the game if all players are valid\n\n  \n{% initial src=\"./exercises/ch12/exercise_b.js#L7;\" %}  \n```js  \n// startGame :: [Player] -> [Either Error String]\nconst startGame = compose(map(map(always('game started!'))), map(validate));\n```  \n  \n  \n{% solution src=\"./exercises/ch12/solution_b.js\" %}  \n{% validation src=\"./exercises/ch12/validation_b.js\" %}  \n{% context src=\"./exercises/support.js\" %}  \n{% endexercise %}  \n  \n  \n---  \n\n\nFinally, we consider some file-system helpers:\n\n```js\n// readfile :: String -> String -> Task Error String\n// readdir :: String -> Task Error [String]\n```\n\n{% exercise %}  \nUse traversable to rearrange and flatten the nested Tasks & Maybe\n\n  \n{% initial src=\"./exercises/ch12/exercise_c.js#L8;\" %}  \n```js  \n// readFirst :: String -> Task Error (Maybe (Task Error String))\nconst readFirst = compose(map(map(readfile('utf-8'))), map(safeHead), readdir);\n```  \n  \n  \n{% solution src=\"./exercises/ch12/solution_c.js\" %}  \n{% validation src=\"./exercises/ch12/validation_c.js\" %}  \n{% context src=\"./exercises/support.js\" %}  \n{% endexercise %}  \n"
  },
  {
    "path": "ch13.md",
    "content": "# Chapter 13: Monoids bring it all together\n\n## Wild combination\n\nIn this chapter, we will examine *monoids* by way of *semigroup*. *Monoids* are the bubblegum in the hair of mathematical abstraction. They capture an idea that spans multiple disciplines, figuratively and literally bringing them all together. They are the ominous force that connects all that calculates. The oxygen in our code base, the ground on which it runs, quantum entanglement encoded.\n\n*Monoids* are about combination. But what is combination? It can mean so many things from accumulation to concatenation to multiplication to choice, composition, ordering, even evaluation! We'll see many examples here, but we'll only tip-toe on the foothills of monoid mountain. The instances are plentiful and applications vast. The aim of this chapter is to provide a good intuition so you can make some *monoids* of your own.\n\n## Abstracting addition\n\nAddition has some interesting qualities I'd like to discuss. Let's have a look at it through our abstraction goggles.\n\nFor starters, it's a binary operation, that is, an operation which takes two values and returns a value, all within the same set.\n\n```js\n// a binary operation\n1 + 1 = 2\n```\n\nSee? Two values in the domain, one value in the codomain, all the same set - numbers, as it were. Some might say numbers are \"closed under addition\", meaning the type won't ever change no matter which ones get tossed into the mix. That means we can chain the operation since the result is always another number:\n\n```js\n// we can run this on any amount of numbers\n1 + 7 + 5 + 4 + ...\n```\n\nIn addition to that (what a calculated pun...), we have associativity which buys us the ability to group operations however we please. Incidentally, an associative, binary operation is a recipe for parallel computation because we can chunk and distribute work.\n\n```js\n// associativity\n(1 + 2) + 3 = 6\n1 + (2 + 3) = 6\n```\n\nNow, don't go confusing this with commutativity which allows us to rearrange the order. While that holds for addition, we're not particularly interested in that property at the moment - too specific for our abstraction needs.\n\nCome to think of it, what properties should be in our abstract superclass anyways? What traits are specific to addition and what ones can be generalized? Are there other abstractions amidst this hierarchy or is it all one chunk? It's this kind of thinking that our mathematical forefathers applied when conceiving the interfaces in abstract algebra.\n\nAs it happens, those old school abstractionists landed on the concept of a *group* when abstracting addition. A *group* has all the bells and whistles including the concept of negative numbers. Here, we're only interested in that associative binary operator so we'll choose the less specific interface *Semigroup*. A *Semigroup* is a type with a `concat` method which acts as our associative binary operator.\n\nLet's implement it for addition and call it `Sum`:\n\n```js\nconst Sum = x => ({\n  x,\n  concat: other => Sum(x + other.x)\n})\n```\n\nNote we `concat` with some other `Sum` and always return a `Sum`.\n\nI've used an object factory here instead of our typical prototype ceremony, primarily because `Sum` is not *pointed* and we don't want to have to type `new`. Anyways, here it is in action:\n\n```js\nSum(1).concat(Sum(3)) // Sum(4)\nSum(4).concat(Sum(37)) // Sum(41)\n```\n\nJust like that, we can program to an interface, not an implementation. Since this interface comes from group theory it has centuries of literature backing it up. Free docs!\n\nNow, as mentioned, `Sum` is not *pointed*, nor a *functor*. As an exercise, go back and check the laws to see why. Okay, I'll just tell you: it can only hold a number, so `map` does not make sense here as we cannot transform the underlying value to another type. That would be a very limited `map` indeed!\n\nSo why is this useful? Well, as with any interface, we can swap out our instance to achieve different results:\n\n```js\nconst Product = x => ({ x, concat: other => Product(x * other.x) })\n\nconst Min = x => ({ x, concat: other => Min(x < other.x ? x : other.x) })\n\nconst Max = x => ({ x, concat: other => Max(x > other.x ? x : other.x) })\n```\n\nThis isn't limited to numbers, though. Let's see some other types:\n\n```js\nconst Any = x => ({ x, concat: other => Any(x || other.x) })\nconst All = x => ({ x, concat: other => All(x && other.x) })\n\nAny(false).concat(Any(true)) // Any(true)\nAny(false).concat(Any(false)) // Any(false)\n\nAll(false).concat(All(true)) // All(false)\nAll(true).concat(All(true)) // All(true)\n\n[1,2].concat([3,4]) // [1,2,3,4]\n\n\"miracle grow\".concat(\"n\") // miracle grown\"\n\nMap({day: 'night'}).concat(Map({white: 'nikes'})) // Map({day: 'night', white: 'nikes'})\n```\n\nIf you stare at these long enough the pattern will pop out at you like a magic eye poster. It's everywhere. We're merging data structures, combining logic, building strings...it seems one can bludgeon almost any task into this combination based interface.\n\nI've used `Map` a few times now. Pardon me if you two weren't properly introduced. `Map` simply wraps `Object` so we can embellish it with some extra methods without altering the fabric of the universe.\n\n\n## All my favourite functors are semigroups.\n\nThe types we've seen so far which implement the functor interface all implement semigroup one as well. Let's look at `Identity` (the artist previously known as Container):\n\n```js\nIdentity.prototype.concat = function(other) {\n  return new Identity(this.__value.concat(other.__value))\n}\n\nIdentity.of(Sum(4)).concat(Identity.of(Sum(1))) // Identity(Sum(5))\nIdentity.of(4).concat(Identity.of(1)) // TypeError: this.__value.concat is not a function\n```\n\nIt is a *semigroup* if and only if its `__value` is a *semigroup*. Like a butterfingered hang glider, it is one whilst it holds one.\n\nOther types have similar behavior:\n\n```js\n// combine with error handling\nRight(Sum(2)).concat(Right(Sum(3))) // Right(Sum(5))\nRight(Sum(2)).concat(Left('some error')) // Left('some error')\n\n\n// combine async\nTask.of([1,2]).concat(Task.of([3,4])) // Task([1,2,3,4])\n```\n\nThis gets particularly useful when we stack these semigroups into a cascading combination:\n\n```js\n// formValues :: Selector -> IO (Map String String)\n// validate :: Map String String -> Either Error (Map String String)\n\nformValues('#signup').map(validate).concat(formValues('#terms').map(validate)) // IO(Right(Map({username: 'andre3000', accepted: true})))\nformValues('#signup').map(validate).concat(formValues('#terms').map(validate)) // IO(Left('one must accept our totalitarian agreement'))\n\nserverA.get('/friends').concat(serverB.get('/friends')) // Task([friend1, friend2])\n\n// loadSetting :: String -> Task Error (Maybe (Map String Boolean))\nloadSetting('email').concat(loadSetting('general')) // Task(Maybe(Map({backgroundColor: true, autoSave: false})))\n```\n\nIn the top example, we've combined an `IO` holding an `Either` holding a `Map` to validate and merge form values. Next, we've hit a couple of different servers and combined their results in an async way using `Task` and `Array`. Lastly, we've stacked `Task`, `Maybe`, and `Map` to load, parse, and merge multiple settings.\n\nThese can be `chain`ed or `ap`'d, but *semigroups* capture what we'd like to do much more concisely.\n\nThis extends beyond functors. In fact, it turns out that anything made up entirely of semigroups, is itself, a semigroup: if we can concat the kit, then we can concat the caboodle.\n\n```js\nconst Analytics = (clicks, path, idleTime) => ({\n  clicks,\n  path,\n  idleTime,\n  concat: other =>\n    Analytics(clicks.concat(other.clicks), path.concat(other.path), idleTime.concat(other.idleTime))\n})\n\nAnalytics(Sum(2), ['/home', '/about'], Right(Max(2000))).concat(Analytics(Sum(1), ['/contact'], Right(Max(1000))))\n// Analytics(Sum(3), ['/home', '/about', '/contact'], Right(Max(2000)))\n```\n\nSee, everything knows how to combine itself nicely. Turns out, we could do the same thing for free just by using the `Map` type:\n\n```js\nMap({clicks: Sum(2), path: ['/home', '/about'], idleTime: Right(Max(2000))}).concat(Map({clicks: Sum(1), path: ['/contact'], idleTime: Right(Max(1000))}))\n// Map({clicks: Sum(3), path: ['/home', '/about', '/contact'], idleTime: Right(Max(2000))})\n```\n\nWe can stack and combine as many of these as we'd like. It's simply a matter of adding another tree to the forest, or another flame to the forest fire depending on your codebase.\n\nThe default, intuitive behavior is to combine what a type is holding, however, there are cases where we ignore what's inside and combine the containers themselves. Consider a type like `Stream`:\n\n```js\nconst submitStream = Stream.fromEvent('click', $('#submit'))\nconst enterStream = filter(x => x.key === 'Enter', Stream.fromEvent('keydown', $('#myForm')))\n\nsubmitStream.concat(enterStream).map(submitForm) // Stream()\n```\n\nWe can combine event streams by capturing events from both as one new stream. Alternatively, we could have combined them by insisting they hold a semigroup. In fact, there are many possible instances for each type. Consider `Task`, we can combine them by choosing the earlier or later of the two. We can always chose the first `Right` instead of short circuiting on `Left` which has the effect of ignoring errors. There is an interface called *Alternative* which implements some of these, well, alternative instances, typically focused on choice rather than cascading combination. It is worth looking into if you are in need of such functionality.\n\n## Monoids for nothing\n\nWe were abstracting addition, but like the Babylonians, we lacked the concept of zero (there were zero mentions of it).\n\nZero acts as *identity* meaning any element added to `0`, will return back that very same element. Abstraction-wise, it's helpful to think of `0` as a kind of neutral or *empty* element. It's important that it act the same way on the left and right side of our binary operation:\n\n```js\n// identity\n1 + 0 = 1\n0 + 1 = 1\n```\n\nLet's call this concept `empty` and create a new interface with it. Like so many startups, we'll choose a heinously uninformative, yet conveniently googleable name: *Monoid*. The recipe for *Monoid* is to take any *semigroup* and add a special *identity* element. We'll implement that with an `empty` function on the type itself:\n\n```js\nArray.empty = () => []\nString.empty = () => \"\"\nSum.empty = () => Sum(0)\nProduct.empty = () => Product(1)\nMin.empty = () => Min(Infinity)\nMax.empty = () => Max(-Infinity)\nAll.empty = () => All(true)\nAny.empty = () => Any(false)\n```\n\nWhen might an empty, identity value prove useful? That's like asking why zero is useful. Like not asking anything at all...\n\nWhen we have nothing else, who can we count on? Zero. How many bugs do we want? Zero. It's our tolerance for unsafe code. A fresh start. The ultimate price tag. It can annihilate everything in its path or save us in a pinch. A golden life saver and a pit of despair.\n\nCodewise, they correspond to sensible defaults:\n\n```js\nconst settings = (prefix=\"\", overrides=[], total=0) => ...\n\nconst settings = (prefix=String.empty(), overrides=Array.empty(), total=Sum.empty()) => ...\n```\n\nOr to return a useful value when we have nothing else:\n\n```js\nsum([]) // 0\n```\n\nThey are also the perfect initial value for an accumulator...\n\n## Folding down the house\n\nIt just so happens that `concat` and `empty` fit perfectly in the first two slots of `reduce`. We can actually `reduce` an array of *semigroup*'s down by ignoring the *empty* value, but as you can see, that leads to a precarious situation:\n\n```js\n// concat :: Semigroup s => s -> s -> s\nconst concat = x => y => x.concat(y)\n\n[Sum(1), Sum(2)].reduce(concat) // Sum(3)\n\n[].reduce(concat) // TypeError: Reduce of empty array with no initial value\n```\n\nBoom goes the dynamite. Like a twisted ankle in a marathon, we have ourselves a runtime exception. JavaScript is more than happy to let us strap pistols to our sneakers before running - it is a conservative sort of language, I suppose, but it stops us dead in our tracks when the array is barren. What could it return anyhow? `NaN`, `false`, `-1`? If we were to continue on in our program, we'd like a result of the right type. It could return a `Maybe` to indicate the possibility of failure, but we can do one better.\n\nLet's use our curried `reduce` function and make a safe version where the `empty` value is not optional. It shall henceforth be known as `fold`:\n\n```js\n// fold :: Monoid m => m -> [m] -> m\nconst fold = reduce(concat)\n```\n\nThe initial `m` is our `empty` value - our neutral, starting point, then we take an array of `m`'s and crush them down to one beautiful diamond like value.\n\n```js\nfold(Sum.empty(), [Sum(1), Sum(2)]) // Sum(3)\nfold(Sum.empty(), []) // Sum(0)\n\nfold(Any.empty(), [Any(false), Any(true)]) // Any(true)\nfold(Any.empty(), []) // Any(false)\n\n\nfold(Either.of(Max.empty()), [Right(Max(3)), Right(Max(21)), Right(Max(11))]) // Right(Max(21))\nfold(Either.of(Max.empty()), [Right(Max(3)), Left('error retrieving value'), Right(Max(11))]) // Left('error retrieving value')\n\nfold(IO.of([]), ['.link', 'a'].map($)) // IO([<a>, <button class=\"link\"/>, <a>])\n```\n\nWe've provided a manual `empty` value for those last two since we can't define one on the type itself. That's totally fine. Typed languages can figure that out by themselves, but we have to pass it in here.\n\n## Not quite a monoid\n\nThere are some *semigroups* that cannot become *monoids*, that is provide an initial value. Look at `First`:\n\n```js\nconst First = x => ({ x, concat: other => First(x) })\n\nMap({id: First(123), isPaid: Any(true), points: Sum(13)}).concat(Map({id: First(2242), isPaid: Any(false), points: Sum(1)}))\n// Map({id: First(123), isPaid: Any(true), points: Sum(14)})\n```\n\nWe'll merge a couple of accounts and keep the `First` id. There is no way to define an `empty` value for it. Doesn't mean it's not useful.\n\n\n## Grand unifying theory\n\n## Group theory or Category theory?\n\nThe notion of a binary operation is everywhere in abstract algebra. It is, in fact, the primary operation for a *category*. We cannot, however, model our operation in category theory without an *identity*. This is the reason we start with a semi-group from group theory, then jump to a monoid in category theory once we have *empty*.\n\nMonoids form a single object category where the morphism is `concat`, `empty` is the identity, and composition is guaranteed.\n\n### Composition as a monoid\n\nFunctions of type `a -> a`, where the domain is in the same set as the codomain, are called *endomorphisms*. We can make a *monoid* called `Endo` which captures this idea:\n\n```js\nconst Endo = run => ({\n  run,\n  concat: other =>\n    Endo(compose(run, other.run))\n})\n\nEndo.empty = () => Endo(identity)\n\n\n// in action\n\n// thingDownFlipAndReverse :: Endo [String] -> [String]\nconst thingDownFlipAndReverse = fold(Endo(() => []), [Endo(reverse), Endo(sort), Endo(append('thing down')])\n\nthingDownFlipAndReverse.run(['let me work it', 'is it worth it?'])\n// ['thing down', 'let me work it', 'is it worth it?']\n```\n\nSince they are all the same type, we can `concat` via `compose` and the types always line up.\n\n### Monad as a monoid\n\nYou may have noticed that `join` is an operation which takes two (nested) monads and squashes them down to one in an associative fashion. It is also a natural transformation or \"functor function\". As previously stated, we can make a category of functors as objects with natural transformations as morphisms. Now, if we specialize it to *Endofunctors*, that is functors of the same type, then `join` provides us with a monoid in the category of Endofunctors also known as a Monad. To show the exact formulation in code takes a little finagling which I encourage you to google, but that's the general idea.\n\n### Applicative as a monoid\n\nEven applicative functors have a monoidal formulation known in the category theory as a *lax monoidal functor*. We can implement the interface as a monoid and recover `ap` from it:\n\n```js\n// concat :: f a -> f b -> f [a, b]\n// empty :: () -> f ()\n\n// ap :: Functor f => f (a -> b) -> f a -> f b\nconst ap = compose(map(([f, x]) => f(x)), concat)\n```\n\n\n## In summary\n\nSo you see, everything is connected, or can be. This profound realization makes *Monoids* a powerful modelling tool for broad swaths of app architecture to the tiniest pieces of datum. I encourage you to think of *monoids* whenever direct accumulation or combination is part of your application, then once you've got that down, start to stretch the definition to more applications (you'd be surprised how much one can model with a *monoid*).\n\n## Exercises\n\n"
  },
  {
    "path": "exercises/.eslintrc.js",
    "content": "const globals = Object\n  .keys(require('./support'))\n  .reduce((o, k) => ({ ...o, [k]: true }), { requirejs: true, assert: true });\n\nmodule.exports = {\n  extends: 'airbnb',\n  env: {\n    browser: true,\n    amd: true,\n  },\n  globals,\n  rules: {\n    'import/no-amd': 0,\n    'import/no-dynamic-require': 0,\n    'no-unused-vars': 0,\n    'object-curly-newline': [2, {\n      multiline: true,\n      consistent: true,\n      minProperties: 5,\n    }],\n  },\n};\n"
  },
  {
    "path": "exercises/README.md",
    "content": "# Mostly Adequate Exercises\n\n## Overview\n\nAll exercises from the book can be completed either:\n\n- in browser (using the version of the book published on [gitbook.io](https://mostly-adequate.gitbooks.io/mostly-adequate-guide/))\n- in your editor & terminal, using `npm`\n\nIn every folder named `ch**` from this `exercises/` folder, you'll find three types of files:\n\n- exercises\n- solutions\n- validations\n\nExercises are structured with a statement in comment, followed by an incomplete\nor incorrect function. For example, `exercise_a` from `ch04` looks like this:\n\n\n```js\n// Refactor to remove all arguments by partially applying the function.\n\n// words :: String -> [String]\nconst words = str => split(' ', str);\n```\n\nFollowing the statement, your goal is to refactor the given function `words`. Once done, \nyour proposal can be verified by running:\n\n```\nnpm run ch04\n```\n\nRemember to first install node dependencies being at the recommended node version of the project. More on this on [the main README of the project](../README.md#about-the-nodejs-version).\n\nAlternatively, you can also have a peak at the corresponding solution file: in this case\n`solution_a.js`. \n\n> The files `validation_*.js` aren't really part of the exercises but are used\n> internally to verify your proposal and, offer hints when adequate. The curious \n> reader may have a look at them :).\n\nNow go and learn some functional programming λ!\n\n## About the Appendixes\n\nImportant notice: the exercise runner takes care of bringing all\ndata-structures and functions from the appendixes into scope. Therefore, you\nmay assume that any function present in the appendix is just available for you\nto use! Amazing, isn't it? \n"
  },
  {
    "path": "exercises/ch04/exercise_a.js",
    "content": "// Refactor to remove all arguments by partially applying the function.\n\n// words :: String -> [String]\nconst words = str => split(' ', str);\n"
  },
  {
    "path": "exercises/ch04/exercise_b.js",
    "content": "// Refactor to remove all arguments by partially applying the functions.\n\n// filterQs :: [String] -> [String]\nconst filterQs = xs => filter(x => x.match(/q/i), xs);\n"
  },
  {
    "path": "exercises/ch04/exercise_c.js",
    "content": "// Considering the following function:\n//\n//   const keepHighest = (x, y) => (x >= y ? x : y);\n//\n// Refactor `max` to not reference any arguments using the helper function `keepHighest`.\n\n// max :: [Number] -> Number\nconst max = xs => reduce((acc, x) => (x >= acc ? x : acc), -Infinity, xs);\n"
  },
  {
    "path": "exercises/ch04/solution_a.js",
    "content": "const words = split(' ');\n"
  },
  {
    "path": "exercises/ch04/solution_b.js",
    "content": "const filterQs = filter(match(/q/i));\n"
  },
  {
    "path": "exercises/ch04/solution_c.js",
    "content": "const max = reduce(keepHighest, -Infinity);\n"
  },
  {
    "path": "exercises/ch04/validation_a.js",
    "content": "/* globals words */\n\nassert.arrayEqual(\n  words('Jingle bells Batman smells'),\n  ['Jingle', 'bells', 'Batman', 'smells'],\n  'The function gives incorrect results.',\n);\n\nassert(\n  split.partially,\n  'The answer is incorrect; hint: split is currified!',\n);\n"
  },
  {
    "path": "exercises/ch04/validation_b.js",
    "content": "/* globals filterQs */\n\nfilter.calledPartial = false;\nmatch.calledPartial = false;\n\nassert.arrayEqual(\n  filterQs(['quick', 'camels', 'quarry', 'over', 'quails']),\n  ['quick', 'quarry', 'quails'],\n  'The function gives incorrect results.',\n);\n\nassert(\n  filter.partially,\n  'The answer is incorrect; hint: look at the arguments for `filter`.',\n);\n\nassert(\n  match.partially,\n  'The answer is incorrect; hint: look at the arguments for `match`.',\n);\n"
  },
  {
    "path": "exercises/ch04/validation_c.js",
    "content": "/* globals max */\n\nassert(\n  max([323, 523, 554, 123, 5234]) === 5234,\n  'The function gives incorrect results.',\n);\n\nassert(\n  reduce.partially,\n  'The answer is incorrect; hint: look at the arguments for `reduce`!',\n);\n\nassert(\n  keepHighest.calledBy && keepHighest.calledBy.name === '$reduceIterator',\n  'The answer is incorrect; hint: look closely to `reduce\\'s` iterator and `keepHighest`!',\n);\n"
  },
  {
    "path": "exercises/ch05/exercise_a.js",
    "content": "// We consider Car objects of the following shape:\n//\n//   {\n//     name: 'Aston Martin One-77',\n//     horsepower: 750,\n//     dollar_value: 1850000,\n//     in_stock: true,\n//   }\n//\n// Use `compose()` to rewrite the function below.\n\n\n// isLastInStock :: [Car] -> Boolean\nconst isLastInStock = (cars) => {\n  const lastCar = last(cars);\n  return prop('in_stock', lastCar);\n};\n"
  },
  {
    "path": "exercises/ch05/exercise_b.js",
    "content": "// Considering the following function:\n//\n//   const average = xs => reduce(add, 0, xs) / xs.length;\n//\n// Use the helper function `average` to refactor `averageDollarValue` as a composition.\n\n// averageDollarValue :: [Car] -> Int\nconst averageDollarValue = (cars) => {\n  const dollarValues = map(c => c.dollar_value, cars);\n  return average(dollarValues);\n};\n"
  },
  {
    "path": "exercises/ch05/exercise_c.js",
    "content": "// Refactor `fastestCar` using `compose()` and other functions in pointfree-style.\n\n// fastestCar :: [Car] -> String\nconst fastestCar = (cars) => {\n  const sorted = sortBy(car => car.horsepower, cars);\n  const fastest = last(sorted);\n  return concat(fastest.name, ' is the fastest');\n};\n"
  },
  {
    "path": "exercises/ch05/solution_a.js",
    "content": "const isLastInStock = compose(prop('in_stock'), last);\n"
  },
  {
    "path": "exercises/ch05/solution_b.js",
    "content": "const averageDollarValue = compose(average, map(prop('dollar_value')));\n"
  },
  {
    "path": "exercises/ch05/solution_c.js",
    "content": "const fastestCar = compose(\n  append(' is the fastest'),\n  prop('name'),\n  last,\n  sortBy(prop('horsepower')),\n);\n"
  },
  {
    "path": "exercises/ch05/validation_a.js",
    "content": "/* globals isLastInStock */\n\nconst fixture01 = cars.slice(0, 3);\nconst fixture02 = cars.slice(3);\n\ntry {\n  assert(\n    isLastInStock(fixture01),\n    'The function gives incorrect results.',\n  );\n\n  assert(\n    !isLastInStock(fixture02),\n    'The function gives incorrect results.',\n  );\n} catch (err) {\n  const callees = isLastInStock.callees || [];\n\n  if (callees[0] === 'prop' && callees[1] === 'last') {\n    throw new Error('The answer is incorrect; hint: functions are composed from right to left!');\n  }\n\n  throw err;\n}\n\nassert.arrayEqual(\n  isLastInStock.callees || [],\n  ['last', 'prop'],\n  'The answer is incorrect; hint: prop is currified!',\n);\n"
  },
  {
    "path": "exercises/ch05/validation_b.js",
    "content": "/* globals averageDollarValue */\n\ntry {\n  assert(\n    averageDollarValue(cars) === 790700,\n    'The function gives incorrect results.',\n  );\n} catch (err) {\n  const callees = averageDollarValue.callees || [];\n\n  if (callees[0] === 'average' && callees[1] === 'map') {\n    throw new Error('The answer is incorrect; hint: functions are composed from right to left!');\n  }\n\n  throw err;\n}\n\nassert.arrayEqual(\n  averageDollarValue.callees || [],\n  ['map', 'average'],\n  'The answer is incorrect; hint: map is currified!',\n);\n\nassert(\n  prop.partially,\n  'The answer is almost correct; hint: you can use prop to access objects\\' properties!',\n);\n"
  },
  {
    "path": "exercises/ch05/validation_c.js",
    "content": "/* globals fastestCar */\n\ntry {\n  assert(\n    fastestCar(cars) === 'Aston Martin One-77 is the fastest',\n    'The function gives incorrect results.',\n  );\n} catch (err) {\n  const callees = fastestCar.callees || [];\n\n  if (callees.length > 0 && callees[0] !== 'sortBy') {\n    throw new Error('The answer is incorrect; hint: functions are composed from right to left!');\n  }\n\n  throw err;\n}\n\nconst callees = fastestCar.callees || [];\n\nassert.arrayEqual(\n  callees.slice(0, 3),\n  ['sortBy', 'last', 'prop'],\n  'The answer is incorrect; hint: Hindley-Milner signatures help a lot to reason about composition!',\n);\n"
  },
  {
    "path": "exercises/ch06/index.html",
    "content": "<!doctype html>\n<html lang=\"en\">\n  <head>\n    <meta charset=\"utf-8\">\n    <title>Flickr App</title>\n    <style>\n      body {\n        margin: 0;\n      }\n\n      .main {\n        display: flex;\n        flex-flow: row wrap;\n      }\n\n      .main > img {\n        flex: 1 1 25vw;\n        object-fit: cover;\n        height: 25vh;\n      }\n    </style>\n  </head>\n  <body>\n    <main id=\"js-main\" class=\"main\"></main>\n    <script src=\"https://cdnjs.cloudflare.com/ajax/libs/require.js/2.2.0/require.min.js\"></script>\n    <script src=\"main.js\"></script>\n  </body>\n</html>\n"
  },
  {
    "path": "exercises/ch06/main.js",
    "content": "const CDN = s => `https://cdnjs.cloudflare.com/ajax/libs/${s}`;\nconst ramda = CDN('ramda/0.21.0/ramda.min');\nconst jquery = CDN('jquery/3.0.0-rc1/jquery.min');\n\nrequirejs.config({ paths: { ramda, jquery } });\nrequire(['jquery', 'ramda'], ($, { compose, curry, map, prop }) => {\n  // -- Utils ----------------------------------------------------------\n  const Impure = {\n    trace: curry((tag, x) => { console.log(tag, x); return x; }), // eslint-disable-line no-console\n    getJSON: curry((callback, url) => $.getJSON(url, callback)),\n    setHtml: curry((sel, html) => $(sel).html(html)),\n  };\n\n  // -- Pure -----------------------------------------------------------\n  const host = 'api.flickr.com';\n  const path = '/services/feeds/photos_public.gne';\n  const query = t => `?tags=${t}&format=json&jsoncallback=?`;\n  const url = t => `https://${host}${path}${query(t)}`;\n\n  const img = src => $('<img />', { src });\n  const mediaUrl = compose(prop('m'), prop('media'));\n  const mediaUrls = compose(map(mediaUrl), prop('items'));\n  const images = compose(map(img), mediaUrls);\n\n  // -- Impure ---------------------------------------------------------\n  const render = compose(Impure.setHtml('#js-main'), images);\n  const app = compose(Impure.getJSON(render), url);\n\n  app('cats');\n});\n"
  },
  {
    "path": "exercises/ch08/exercise_a.js",
    "content": "// Use `add` and `map` to make a function that increments a value inside a functor.\n\n// incrF :: Functor f => f Int -> f Int\nconst incrF = undefined;\n"
  },
  {
    "path": "exercises/ch08/exercise_b.js",
    "content": "// Given the following User object:\n//\n//   const user = { id: 2, name: 'Albert', active: true };\n//\n// Use `safeProp` and `head` to find the first initial of the user.\n\n// initial :: User -> Maybe String\nconst initial = undefined;\n"
  },
  {
    "path": "exercises/ch08/exercise_c.js",
    "content": "// Given the following helper functions:\n//\n//   // showWelcome :: User -> String\n//   const showWelcome = compose(concat('Welcome '), prop('name'));\n//\n//   // checkActive :: User -> Either String User\n//   const checkActive = function checkActive(user) {\n//     return user.active\n//       ? Either.of(user)\n//       : left('Your account is not active');\n//   };\n//\n// Write a function that uses `checkActive` and `showWelcome` to grant access or return the error.\n\n// eitherWelcome :: User -> Either String String\nconst eitherWelcome = undefined;\n"
  },
  {
    "path": "exercises/ch08/exercise_d.js",
    "content": "// We now consider the following functions:\n//\n//   // validateUser :: (User -> Either String ()) -> User -> Either String User\n//   const validateUser = curry((validate, user) => validate(user).map(_ => user));\n//\n//   // save :: User -> IO User\n//   const save = user => new IO(() => ({ ...user, saved: true }));\n//\n// Write a function `validateName` which checks whether a user has a name longer than 3 characters\n// or return an error message. Then use `either`, `showWelcome` and `save` to write a `register`\n// function to signup and welcome a user when the validation is ok.\n//\n// Remember either's two arguments must return the same type.\n\n// validateName :: User -> Either String ()\nconst validateName = undefined;\n\n// register :: User -> IO String\nconst register = compose(undefined, validateUser(validateName));\n"
  },
  {
    "path": "exercises/ch08/solution_a.js",
    "content": "const incrF = map(add(1));\n"
  },
  {
    "path": "exercises/ch08/solution_b.js",
    "content": "const initial = compose(map(head), safeProp('name'));\n"
  },
  {
    "path": "exercises/ch08/solution_c.js",
    "content": "const eitherWelcome = compose(map(showWelcome), checkActive);\n"
  },
  {
    "path": "exercises/ch08/solution_d.js",
    "content": "const validateName = ({ name }) => (name.length > 3\n  ? Either.of(null)\n  : left('Your name need to be > 3')\n);\n\nconst saveAndWelcome = compose(map(showWelcome), save);\n\nconst register = compose(\n  either(IO.of, saveAndWelcome),\n  validateUser(validateName),\n);\n"
  },
  {
    "path": "exercises/ch08/validation_a.js",
    "content": "/* globals incrF */\n\nassert(\n  incrF(Identity.of(2)).$value === 3,\n  'The function gives incorrect results.',\n);\n\nassert(\n  add.partially,\n  'The answer is incorrect; hint: add is currified!',\n);\n\nassert(\n  map.partially,\n  'The answer is incorrect; hint: map is currified!',\n);\n"
  },
  {
    "path": "exercises/ch08/validation_b.js",
    "content": "/* globals initial */\n\nif (!(initial(albert) instanceof Maybe) && initial.callees && initial.callees[0] === 'safeProp' && initial.callees[1] === 'head') {\n  throw new Error('The function gives incorrect results; hint: look carefully at the signatures of `safeProp` and `head`!');\n}\n\nassert(\n  initial(albert).$value === 'A',\n  'The function gives incorrect results.',\n);\n\nassert.arrayEqual(\n  initial.callees || [],\n  ['safeProp', 'map'],\n  'The answer is incorrect; hint: you can compose `safeProp` with `head` in a declarative way',\n);\n"
  },
  {
    "path": "exercises/ch08/validation_c.js",
    "content": "/* globals eitherWelcome */\n\nif (!(eitherWelcome(gary) instanceof Either) && eitherWelcome.callees && eitherWelcome.callees[0] === 'checkActive' && eitherWelcome.callees[1] === 'showWelcome') {\n  throw new Error('The function gives incorrect results; hint: look carefully at the signatures of `checkActive` and `showWelcome`!');\n}\n\nassert(\n  eitherWelcome(gary).$value === 'Your account is not active',\n  'The function gives incorrect results.',\n);\n\nassert(\n  eitherWelcome(theresa).$value === 'Welcome Theresa',\n  'The function gives incorrect results.',\n);\n\nassert.arrayEqual(\n  eitherWelcome.callees || [],\n  ['checkActive', 'map'],\n  'The answer is incorrect; hint: you can compose `checkActive` with `showWelcome` in a declarative way!',\n);\n"
  },
  {
    "path": "exercises/ch08/validation_d.js",
    "content": "/* globals validateName, register */\n\nconst validateGary = validateName(gary);\nassert(\n  validateGary instanceof Either && validateGary.isRight,\n  'The function `validateName` gives incorrect results.',\n);\n\nconst validateYi = validateName(yi);\nassert(\n  validateYi instanceof Either && validateYi.isLeft && typeof validateYi.$value === 'string',\n  'The function `validateName` gives incorrect results!',\n);\n\nconst registerAlbert = register(albert);\nassert(\n  registerAlbert instanceof IO,\n  'The right outcome to `register` is incorrect; hint: `save` returns an `IO` and you\\'ll need `map` to manipulate the inner value!',\n);\n\nconst msgAlbert = registerAlbert.unsafePerformIO();\nassert(\n  typeof msgAlbert === 'string',\n  'The right outcome to `register` is incorrect; hint: look carefully at your signatures, `register` should return an `IO(String)` in every scenarios!',\n);\n\nconst callees = register.callees || [];\n\nassert(\n  callees[callees.length - 1] === 'either',\n  'The function `register` seems incorrect; hint: you can use `either` to branch an `Either` to different outcomes!',\n);\n\nassert(\n  msgAlbert === showWelcome(albert),\n  'The function `register` returns a correct type, but the inner value is incorrect! Did you use `showWelcome`?',\n);\n\nconst registerYi = register(yi);\nassert(\n  registerYi instanceof IO,\n  'The left outcome to `register` is incorrect; hint: look carefully at your signatures, `register` should return an `IO` in every scenarios!',\n);\n\nconst msgYi = registerYi.unsafePerformIO();\nassert(\n  typeof msgYi === 'string',\n  'The left outcome to `register` is incorrect; hint: look carefully at your signatures, `register` should return an `IO(String)` in every scenarios!',\n);\n"
  },
  {
    "path": "exercises/ch09/exercise_a.js",
    "content": "// Considering a User object as follow:\n//\n//   const user = {\n//     id: 1,\n//     name: 'Albert',\n//     address: {\n//       street: {\n//         number: 22,\n//         name: 'Walnut St',\n//       },\n//     },\n//   };\n//\n// Use `safeProp` and `map/join` or `chain` to safely get the street name when given a user\n\n// getStreetName :: User -> Maybe String\nconst getStreetName = undefined;\n"
  },
  {
    "path": "exercises/ch09/exercise_b.js",
    "content": "// We now consider the following items:\n//\n//   // getFile :: IO String\n//   const getFile = IO.of('/home/mostly-adequate/ch09.md');\n//\n//   // pureLog :: String -> IO ()\n//   const pureLog = str => new IO(() => console.log(str));\n//\n// Use getFile to get the filepath, remove the directory and keep only the basename,\n// then purely log it. Hint: you may want to use `split` and `last` to obtain the\n// basename from a filepath.\n\n// logFilename :: IO ()\nconst logFilename = undefined;\n"
  },
  {
    "path": "exercises/ch09/exercise_c.js",
    "content": "// For this exercise, we consider helpers with the following signatures:\n//\n//   validateEmail :: Email -> Either String Email\n//   addToMailingList :: Email -> IO([Email])\n//   emailBlast :: [Email] -> IO ()\n//\n// Use `validateEmail`, `addToMailingList` and `emailBlast` to create a function\n// which adds a new email to the mailing list if valid, and then notify the whole\n// list.\n\n// joinMailingList :: Email -> Either String (IO ())\nconst joinMailingList = undefined;\n"
  },
  {
    "path": "exercises/ch09/solution_a.js",
    "content": "const getStreetName = compose(\n  chain(safeProp('name')),\n  chain(safeProp('street')),\n  safeProp('address'),\n);\n"
  },
  {
    "path": "exercises/ch09/solution_b.js",
    "content": "const basename = compose(last, split('/'));\n\nconst logFilename = compose(chain(pureLog), map(basename))(getFile);\n"
  },
  {
    "path": "exercises/ch09/solution_c.js",
    "content": "const joinMailingList = compose(\n  map(compose(chain(emailBlast), addToMailingList)),\n  validateEmail,\n);\n"
  },
  {
    "path": "exercises/ch09/validation_a.js",
    "content": "/* globals getStreetName */\n\nconst res = getStreetName(albert);\n\nif ((!(res instanceof Maybe) || typeof res.$value !== 'string' || res.isNothing) && getStreetName.callees) {\n  [1, 2, 3].forEach((i) => {\n    if (getStreetName.callees[i] === 'map' && getStreetName.callees[i + 1] !== 'join') {\n      throw new Error('The function gives incorrect results; hint: you can use `join` to flatten two monads!');\n    }\n  });\n\n  [1, 2].forEach((i) => {\n    if (!['map', 'chain'].includes(getStreetName.callees[i])) {\n      throw new Error('The function gives incorrect results; hint: look carefully at the signature of `safeProp` and `chain`!');\n    }\n  });\n}\n\nassert(\n  getStreetName(albert).$value === 'Walnut St',\n  'The function gives incorrect results.',\n);\n\nassert(\n  getStreetName(gary).isNothing,\n  'The function gives incorrect results.',\n);\n\nassert(\n  getStreetName(theresa).isNothing,\n  'The function gives incorrect results.',\n);\n"
  },
  {
    "path": "exercises/ch09/validation_b.js",
    "content": "/* globals logFilename */\n\nassert(\n  logFilename instanceof IO,\n  'The function gives incorrect results; hint: `logFilename` should be an IO()',\n);\n\nif (logFilename.unsafePerformIO() instanceof IO) {\n  throw new Error('The function gives incorrect results; hint: make sure to `chain` effects as you go');\n}\n\nassert(\n  logFilename.unsafePerformIO() === 'ch09.md',\n  'The function gives incorrect results; hint: did you retrieve the file\\'s basename ?',\n);\n"
  },
  {
    "path": "exercises/ch09/validation_c.js",
    "content": "/* globals joinMailingList */\n\nconst res = joinMailingList('email@email.com');\n\nassert(\n  res instanceof Either,\n  'The function has an invalid type; hint: `joinMailingList` should return an Either String (IO ())',\n);\n\nif (res.$value.unsafePerformIO() instanceof IO) {\n  throw new Error('The function gives incorrect results; hint: make sure to `chain` effects as you go');\n}\n\nconst getResult = either(identity, unsafePerformIO);\n\nassert(\n  getResult(joinMailingList('sleepy@grandpa.net')) === 'sleepy@grandpa.net',\n  'The function gives incorrect results.',\n);\n\nassert(\n  getResult(joinMailingList('notanemail')) === 'invalid email',\n  'The function gives incorrect results.',\n);\n"
  },
  {
    "path": "exercises/ch10/exercise_a.js",
    "content": "// Write a function that adds two possibly null numbers together using `Maybe` and `ap`.\n\n// safeAdd :: Maybe Number -> Maybe Number -> Maybe Number\nconst safeAdd = undefined;\n"
  },
  {
    "path": "exercises/ch10/exercise_b.js",
    "content": "// Rewrite `safeAdd` from exercise_a to use `liftA2` instead of `ap`.\n\n// safeAdd :: Maybe Number -> Maybe Number -> Maybe Number\nconst safeAdd = undefined;\n"
  },
  {
    "path": "exercises/ch10/exercise_c.js",
    "content": "// For this exercise, we consider the following helpers:\n//\n//   const localStorage = {\n//     player1: { id:1, name: 'Albert' },\n//     player2: { id:2, name: 'Theresa' },\n//   };\n//\n//   // getFromCache :: String -> IO User\n//   const getFromCache = x => new IO(() => localStorage[x]);\n//\n//   // game :: User -> User -> String\n//   const game = curry((p1, p2) => `${p1.name} vs ${p2.name}`);\n//\n// Write an IO that gets both player1 and player2 from the cache and starts the game.\n\n// startGame :: IO String\nconst startGame = undefined;\n"
  },
  {
    "path": "exercises/ch10/solution_a.js",
    "content": "const safeAdd = curry((a, b) => Maybe.of(add).ap(a).ap(b));\n"
  },
  {
    "path": "exercises/ch10/solution_b.js",
    "content": "const safeAdd = liftA2(add);\n"
  },
  {
    "path": "exercises/ch10/solution_c.js",
    "content": "const startGame = IO.of(game)\n  .ap(getFromCache('player1'))\n  .ap(getFromCache('player2'));\n"
  },
  {
    "path": "exercises/ch10/validation_a.js",
    "content": "/* globals safeAdd */\n\nconst res = safeAdd(Maybe.of(2), Maybe.of(3));\nassert(\n  res instanceof Maybe && typeof res.$value === 'number',\n  'The function has a wrong type; make sure to wrap your numbers inside `Maybe.of`',\n);\n\nassert(\n  safeAdd(Maybe.of(2), Maybe.of(3)).$value === 5,\n  'The function gives incorrect results; did you use `add` ?',\n);\n\nassert(\n  safeAdd(Maybe.of(null), Maybe.of(3)).isNothing,\n  'The function gives incorrect results; `Nothing` should be returned when at least one value is `null`',\n);\n\nassert(\n  safeAdd(Maybe.of(2), Maybe.of(null)).isNothing,\n  'The function gives incorrect results; `Nothing` should be returned when at least one value is `null`',\n);\n\nassert(\n  withSpyOn('ap', Maybe.prototype, () => safeAdd(Maybe.of(2), Maybe.of(3))),\n  'The function seems incorrect; did you use `ap` ?',\n);\n"
  },
  {
    "path": "exercises/ch10/validation_b.js",
    "content": "/* globals safeAdd */\n\nconst res = safeAdd(Maybe.of(2), Maybe.of(3));\nassert(\n  res instanceof Maybe && typeof res.$value === 'number',\n  'The function has a wrong type; make sure to wrap your numbers inside `Maybe.of`',\n);\n\nassert(\n  safeAdd(Maybe.of(2), Maybe.of(3)).$value === 5,\n  'The function gives incorrect results; did you use `add` ?',\n);\n\nassert(\n  safeAdd(Maybe.of(null), Maybe.of(3)).isNothing,\n  'The function gives incorrect results; `Nothing` should be returned when at least one value is `null`',\n);\n\nassert(\n  safeAdd(Maybe.of(2), Maybe.of(null)).isNothing,\n  'The function gives incorrect results; `Nothing` should be returned when at least one value is `null`',\n);\n\nassert(\n  liftA2.partially && safeAdd.name === 'liftA2',\n  'The function seems incorrect; did you use `liftA2`? Remember that `liftA2` is currified!',\n);\n"
  },
  {
    "path": "exercises/ch10/validation_c.js",
    "content": "/* globals startGame */\n\nassert(\n  startGame instanceof IO && typeof startGame.unsafePerformIO() === 'string',\n  'The answer has a wrong type; `startGame` should be an `IO String`',\n);\n\nassert(\n  startGame.unsafePerformIO() === `${albert.name} vs ${theresa.name}`,\n  'The answer gives incorrect results',\n);\n"
  },
  {
    "path": "exercises/ch11/exercise_a.js",
    "content": "// Write a natural transformation that converts `Either b a` to `Maybe a`\n\n// eitherToMaybe :: Either b a -> Maybe a\nconst eitherToMaybe = undefined;\n"
  },
  {
    "path": "exercises/ch11/exercise_b.js",
    "content": "// Using `eitherToTask`, simplify `findNameById` to remove the nested `Either`.\n//\n//   // eitherToTask :: Either a b -> Task a b\n//   const eitherToTask = either(Task.rejected, Task.of);\n\n// findNameById :: Number -> Task Error (Either Error User)\nconst findNameById = compose(map(map(prop('name'))), findUserById);\n"
  },
  {
    "path": "exercises/ch11/exercise_c.js",
    "content": "// Write the isomorphisms between String and [Char].\n//\n// As a reminder, the following functions are available in the exercise's context:\n//\n//   split :: String -> String -> [String]\n//   intercalate :: String -> [String] -> String\n\n// strToList :: String -> [Char]\nconst strToList = undefined;\n\n// listToStr :: [Char] -> String\nconst listToStr = undefined;\n"
  },
  {
    "path": "exercises/ch11/solution_a.js",
    "content": "const eitherToMaybe = either(always(nothing), Maybe.of);\n"
  },
  {
    "path": "exercises/ch11/solution_b.js",
    "content": "const findNameById = compose(map(prop('name')), chain(eitherToTask), findUserById);\n"
  },
  {
    "path": "exercises/ch11/solution_c.js",
    "content": "const strToList = split('');\n\nconst listToStr = intercalate('');\n"
  },
  {
    "path": "exercises/ch11/validation_a.js",
    "content": "/* globals eitherToMaybe */\n\nconst just = eitherToMaybe(Either.of('one eyed willy'));\nconst noth = eitherToMaybe(left('some error'));\n\nassert(\n  just instanceof Maybe && just.isJust && just.$value === 'one eyed willy',\n  'The function maps the `Right()` side incorrectly; hint: `Right(14)` should be mapped to `Just(14)`',\n);\n\nassert(\n  noth instanceof Maybe && noth.isNothing,\n  'The function maps the `Left()` side incorrectly; hint: `Left(\\'error\\')` should be mapped to `Nothing`',\n);\n"
  },
  {
    "path": "exercises/ch11/validation_b.js",
    "content": "/* globals findNameById */\n\nconst throwUnexpected = () => {\n  throw new Error('The function gives incorrect results; a Task has resolved unexpectedly!');\n};\n\nconst res = findNameById(1);\n\nassert(\n  res instanceof Task,\n  'The function has an incorrect type; hint: `findNameById` must return a `Task String User`!',\n);\n\nres.fork(throwUnexpected, (val) => {\n  assert(\n    !(val instanceof Task),\n    'The function has an incorrect type; hint: `findNameById` must return a `Task String User`, make sure to flatten any nested Functor!',\n  );\n\n  assert(\n    !(val instanceof Either),\n    'The function has an incorrect type; hint: did you use `eitherToTask` ?',\n  );\n\n  assert(\n    val === 'Albert',\n    'The function gives incorrect results for the `Right` side of `Either`.',\n  );\n});\n\n\nconst rej = findNameById(999);\n\nassert(\n  rej instanceof Task,\n  'The function has an incorrect type; hint: `findNameById` must return a `Task String User`!',\n);\n\nrej.fork((val) => {\n  assert(\n    !(val instanceof Task),\n    'The function has an incorrect type; hint: `findNameById` must return a `Task String User`, make sure to flatten any nested Functor!',\n  );\n\n  assert(\n    val === 'not found',\n    'The function gives incorrect results for the `Left` side of `Either`.',\n  );\n}, throwUnexpected);\n"
  },
  {
    "path": "exercises/ch11/validation_c.js",
    "content": "/* globals strToList, listToStr */\n\nconst sortLetters = compose(listToStr, sortBy(identity), strToList);\n\nassert(\n  sortLetters('sortme') === 'emorst',\n  'The function gives incorrect results',\n);\n"
  },
  {
    "path": "exercises/ch12/exercise_a.js",
    "content": "// Considering the following elements:\n//\n//   // httpGet :: Route -> Task Error JSON\n//   // routes :: Map Route Route\n//   const routes = new Map({ '/': '/', '/about': '/about' });\n//\n// Use the traversable interface to change the type signature of `getJsons`.\n//\n//   getJsons :: Map Route Route -> Task Error (Map Route JSON)\n\n// getJsons :: Map Route Route -> Map Route (Task Error JSON)\nconst getJsons = map(httpGet);\n"
  },
  {
    "path": "exercises/ch12/exercise_b.js",
    "content": "// Using traversable, and the `validate` function, update `startGame` (and its signature)\n// to only start the game if all players are valid\n//\n//   // validate :: Player -> Either String Player\n//   validate = player => (player.name ? Either.of(player) : left('must have name'));\n\n// startGame :: [Player] -> [Either Error String]\nconst startGame = compose(map(map(always('game started!'))), map(validate));\n"
  },
  {
    "path": "exercises/ch12/exercise_c.js",
    "content": "// Considering the following functions:\n//\n//   readfile :: String -> String -> Task Error String\n//   readdir :: String -> Task Error [String]\n//\n// Use traversable to rearrange and flatten the nested Tasks & Maybe\n\n// readFirst :: String -> Task Error (Maybe (Task Error String))\nconst readFirst = compose(map(map(readfile('utf-8'))), map(safeHead), readdir);\n"
  },
  {
    "path": "exercises/ch12/solution_a.js",
    "content": "// getJsons :: Map Route Route -> Task Error (Map Route JSON)\nconst getJsons = traverse(Task.of, httpGet);\n"
  },
  {
    "path": "exercises/ch12/solution_b.js",
    "content": "// startGame :: [Player] -> Either Error String\nconst startGame = compose(map(always('game started!')), traverse(Either.of, validate));\n"
  },
  {
    "path": "exercises/ch12/solution_c.js",
    "content": "// readFirst :: String -> Task Error (Maybe String)\nconst readFirst = compose(\n  chain(traverse(Task.of, readfile('utf-8'))),\n  map(safeHead),\n  readdir,\n);\n"
  },
  {
    "path": "exercises/ch12/validation_a.js",
    "content": "/* globals getJsons */\n\nconst throwUnexpected = () => {\n  throw new Error('The function gives incorrect results; a Task has resolved unexpectedly!');\n};\n\nconst res = getJsons(routes);\n\nassert(\n  res instanceof Task,\n  'The function has an invalid type; hint: `getJsons` must return a `Task`!',\n);\n\nres.fork(throwUnexpected, ($res) => {\n  assert(\n    $res.$value['/'] === 'json for /' && $res.$value['/about'] === 'json for /about',\n    'The function gives incorrect results; hint: did you correctly map `httpGet` over the Map\\'s values?',\n  );\n\n  const callees = getJsons.callees; // eslint-disable-line prefer-destructuring\n\n  if (callees && callees[0] === 'map' && callees[1] === 'sequence') {\n    throw new Error('The function could be written in a simpler form; hint: compose(sequence(of), map(fn)) === traverse(of, fn)');\n  }\n});\n"
  },
  {
    "path": "exercises/ch12/validation_b.js",
    "content": "/* globals startGame */\n\nconst res = startGame(new List([albert, theresa]));\n\nassert(\n  res instanceof Either,\n  'The function has an invalid type; hint: `startGame` must return a `Either`!',\n);\n\nassert(\n  res.isRight && res.$value === 'game started!',\n  'The function gives incorrect results; a game should have started for a list of valid players!',\n);\n\nconst rej = startGame(new List([gary, { what: 14 }]));\nassert(\n  rej.isLeft && rej.$value === 'must have name',\n  'The function gives incorrect results; a game shouldn\\'t be started if the list contains invalid players!',\n);\n\nconst callees = startGame.callees; // eslint-disable-line prefer-destructuring\n\nif (callees && callees[0] === 'map' && callees[1] === 'sequence') {\n  throw new Error('The function could be written in a simpler form; hint: compose(sequence(of), map(fn)) === traverse(of, fn)');\n}\n"
  },
  {
    "path": "exercises/ch12/validation_c.js",
    "content": "/* globals readFirst */\n\nconst res = readFirst('__dirname');\n\nconst throwUnexpected = () => {\n  throw new Error('The function gives incorrect results; a Task has resolved unexpectedly!');\n};\n\nassert(\n  res instanceof Task,\n  'The function has an invalid type; hint: `readFirst` must return a `Task`!',\n);\n\nres.fork(throwUnexpected, ($res) => {\n  assert(\n    $res instanceof Maybe,\n    'The function has an invalid type; hint: `readFirst` must return a `Task Error (Maybe String)`!',\n  );\n\n  assert(\n    $res.isJust && $res.$value === 'content of file1 (utf-8)',\n    'The function gives incorrect results.',\n  );\n});\n"
  },
  {
    "path": "exercises/package.json",
    "content": "{\n  \"name\": \"@mostly-adequate/exercises\",\n  \"version\": \"1.0.0\",\n  \"description\": \"Exercises coming with the Mostly Adequate Guide to Functional Programming\",\n  \"license\": \"MIT\",\n  \"repository\": {\n    \"type\": \"git\",\n    \"url\": \"https://github.com/MostlyAdequate/mostly-adequate-guide\"\n  },\n  \"author\": \"@mostly-adequate\",\n  \"bugs\": {\n    \"url\": \"https://github.com/MostlyAdequate/mostly-adequate-guide/issues\"\n  },\n  \"homepage\": \"https://github.com/MostlyAdequate/mostly-adequate-guide\",\n  \"dependencies\": {},\n  \"devDependencies\": {\n    \"cli\": \"^1.0.1\",\n    \"eslint\": \"^5.9.0\",\n    \"eslint-config-airbnb\": \"^16.1.0\",\n    \"eslint-plugin-import\": \"^2.8.0\",\n    \"eslint-plugin-jsx-a11y\": \"^6.0.2\",\n    \"eslint-plugin-react\": \"^7.5.1\",\n    \"live-server\": \"^1.2.1\",\n    \"mocha\": \"^4.1.0\"\n  },\n  \"scripts\": {\n    \"test\": \"mocha test/*.solutions.js\",\n    \"lint\": \"eslint .\",\n    \"ch04\": \"mocha test/ch04.js\",\n    \"ch05\": \"mocha test/ch05.js\",\n    \"ch06\": \"live-server --ignore='node_modules/*/**' ch06\",\n    \"ch08\": \"mocha test/ch08.js\",\n    \"ch09\": \"mocha test/ch09.js\",\n    \"ch10\": \"mocha test/ch10.js\",\n    \"ch11\": \"mocha test/ch11.js\",\n    \"ch12\": \"mocha test/ch12.js\"\n  }\n}\n"
  },
  {
    "path": "exercises/support.js",
    "content": "// NOTE We keep named function here to leverage this in the `compose` function,\n// and later on in the validations scripts.\n\n/* eslint-disable prefer-arrow-callback */\n\n\n/* ---------- Internals ---------- */\n\nfunction namedAs(value, fn) {\n  Object.defineProperty(fn, 'name', { value });\n  return fn;\n}\n\n\n// NOTE This file is loaded by gitbook's exercises plugin. When it does, there's an\n// `assert` function available in the global scope.\n\n/* eslint-disable no-undef, global-require */\nif (typeof assert !== 'function' && typeof require === 'function') {\n  global.assert = require('assert');\n}\n\nassert.arrayEqual = function assertArrayEqual(actual, expected, message = 'arrayEqual') {\n  if (actual.length !== expected.length) {\n    throw new Error(message);\n  }\n\n  for (let i = 0; i < expected.length; i += 1) {\n    if (expected[i] !== actual[i]) {\n      throw new Error(message);\n    }\n  }\n};\n/* eslint-enable no-undef, global-require */\n\n\nfunction inspect(x) {\n  if (x && typeof x.inspect === 'function') {\n    return x.inspect();\n  }\n\n  function inspectFn(f) {\n    return f.name ? f.name : f.toString();\n  }\n\n  function inspectTerm(t) {\n    switch (typeof t) {\n      case 'string':\n        return `'${t}'`;\n      case 'object': {\n        const ts = Object.keys(t).map(k => [k, inspect(t[k])]);\n        return `{${ts.map(kv => kv.join(': ')).join(', ')}}`;\n      }\n      default:\n        return String(t);\n    }\n  }\n\n  function inspectArgs(args) {\n    return Array.isArray(args) ? `[${args.map(inspect).join(', ')}]` : inspectTerm(args);\n  }\n\n  return (typeof x === 'function') ? inspectFn(x) : inspectArgs(x);\n}\n\n\n/* eslint-disable no-param-reassign */\nfunction withSpyOn(prop, obj, fn) {\n  const orig = obj[prop];\n  let called = false;\n  obj[prop] = function spy(...args) {\n    called = true;\n    return orig.call(this, ...args);\n  };\n  fn();\n  obj[prop] = orig;\n  return called;\n}\n/* eslint-enable no-param-reassign */\n\n\nconst typeMismatch = (src, got, fn) => `Type Mismatch in function '${fn}'\n\n        ${fn} :: ${got}\n\n      instead of\n\n        ${fn} :: ${src}`;\n\n\nconst capitalize = s => `${s[0].toUpperCase()}${s.substring(1)}`;\n\n\nconst ordinal = (i) => {\n  switch (i) {\n    case 1:\n      return '1st';\n    case 2:\n      return '2nd';\n    case 3:\n      return '3rd';\n    default:\n      return `${i}th`; // NOTE won't get any much bigger ...\n  }\n};\n\nconst getType = (x) => {\n  if (x === null) {\n    return 'Null';\n  }\n\n  if (typeof x === 'undefined') {\n    return '()';\n  }\n\n  if (Array.isArray(x)) {\n    return `[${x[0] ? getType(x[0]) : '?'}]`;\n  }\n\n  if (typeof x.getType === 'function') {\n    return x.getType();\n  }\n\n  if (x.constructor && x.constructor.name) {\n    return x.constructor.name;\n  }\n\n  return capitalize(typeof x);\n};\n\n\n/* ---------- Essential FP Functions ---------- */\n\n// NOTE A slightly pumped up version of `curry` which also keeps track of\n// whether a function was called partially or with all its arguments at once.\n// This is useful to provide insights during validation of exercises.\nfunction curry(fn) {\n  assert(\n    typeof fn === 'function',\n    typeMismatch('function -> ?', [getType(fn), '?'].join(' -> '), 'curry'),\n  );\n\n  const arity = fn.length;\n\n  return namedAs(fn.name, function $curry(...args) {\n    $curry.partially = this && this.partially;\n\n    if (args.length < arity) {\n      return namedAs(fn.name, $curry.bind({ partially: true }, ...args));\n    }\n\n    return fn.call(this || { partially: false }, ...args);\n  });\n}\n\n\n// NOTE A slightly pumped up version of `compose` which also keeps track of the chain\n// of callees. In the end, a function created with `compose` holds a `callees` variable\n// with the list of all the callees' names.\n// This is useful to provide insights during validation of exercises\nfunction compose(...fns) {\n  const n = fns.length;\n\n  return function $compose(...args) {\n    $compose.callees = [];\n\n    let $args = args;\n\n    for (let i = n - 1; i >= 0; i -= 1) {\n      const fn = fns[i];\n\n      assert(\n        typeof fn === 'function',\n        `Invalid Composition: ${ordinal(n - i)} element in a composition isn't a function`,\n      );\n\n      $compose.callees.push(fn.name);\n      $args = [fn.call(null, ...$args)];\n    }\n\n    return $args[0];\n  };\n}\n\n\n/* ---------- Algebraic Data Structures ---------- */\n\nclass Either {\n  static of(x) {\n    return new Right(x); // eslint-disable-line no-use-before-define\n  }\n\n  constructor(x) {\n    this.$value = x;\n  }\n}\n\n\nclass Left extends Either {\n  get isLeft() { // eslint-disable-line class-methods-use-this\n    return true;\n  }\n\n  get isRight() { // eslint-disable-line class-methods-use-this\n    return false;\n  }\n\n  ap() {\n    return this;\n  }\n\n  chain() {\n    return this;\n  }\n\n  inspect() {\n    return `Left(${inspect(this.$value)})`;\n  }\n\n  getType() {\n    return `(Either ${getType(this.$value)} ?)`;\n  }\n\n  join() {\n    return this;\n  }\n\n  map() {\n    return this;\n  }\n\n  sequence(of) {\n    return of(this);\n  }\n\n  traverse(of, fn) {\n    return of(this);\n  }\n}\n\n\nclass Right extends Either {\n  get isLeft() { // eslint-disable-line class-methods-use-this\n    return false;\n  }\n\n  get isRight() { // eslint-disable-line class-methods-use-this\n    return true;\n  }\n\n  ap(f) {\n    return f.map(this.$value);\n  }\n\n  chain(fn) {\n    return fn(this.$value);\n  }\n\n  inspect() {\n    return `Right(${inspect(this.$value)})`;\n  }\n\n  getType() {\n    return `(Either ? ${getType(this.$value)})`;\n  }\n\n  join() {\n    return this.$value;\n  }\n\n  map(fn) {\n    return Either.of(fn(this.$value));\n  }\n\n  sequence(of) {\n    return this.traverse(of, x => x);\n  }\n\n  traverse(of, fn) {\n    fn(this.$value).map(Either.of);\n  }\n}\n\n\nclass Identity {\n  static of(x) {\n    return new Identity(x);\n  }\n\n  constructor(x) {\n    this.$value = x;\n  }\n\n  ap(f) {\n    return f.map(this.$value);\n  }\n\n  chain(fn) {\n    return this.map(fn).join();\n  }\n\n  inspect() {\n    return `Identity(${inspect(this.$value)})`;\n  }\n\n  getType() {\n    return `(Identity ${getType(this.$value)})`;\n  }\n\n  join() {\n    return this.$value;\n  }\n\n  map(fn) {\n    return Identity.of(fn(this.$value));\n  }\n\n  sequence(of) {\n    return this.traverse(of, x => x);\n  }\n\n  traverse(of, fn) {\n    return fn(this.$value).map(Identity.of);\n  }\n}\n\nclass IO {\n  static of(x) {\n    return new IO(() => x);\n  }\n\n  constructor(io) {\n    assert(\n      typeof io === 'function',\n      'invalid `io` operation given to IO constructor. Use `IO.of` if you want to lift a value in a default minimal IO context.',\n    );\n\n    this.unsafePerformIO = io;\n  }\n\n  ap(f) {\n    return this.chain(fn => f.map(fn));\n  }\n\n  chain(fn) {\n    return this.map(fn).join();\n  }\n\n  inspect() {\n    return `IO(${inspect(this.unsafePerformIO())})`;\n  }\n\n  getType() {\n    return `(IO ${getType(this.unsafePerformIO())})`;\n  }\n\n\n  join() {\n    return this.unsafePerformIO();\n  }\n\n  map(fn) {\n    return new IO(compose(fn, this.unsafePerformIO));\n  }\n}\n\n\nclass Map {\n  constructor(x) {\n    assert(\n      typeof x === 'object' && x !== null,\n      'tried to create `Map` with non object-like',\n    );\n\n    this.$value = x;\n  }\n\n  inspect() {\n    return `Map(${inspect(this.$value)})`;\n  }\n\n  getType() {\n    const sample = this.$value[Object.keys(this.$value)[0]];\n\n    return `(Map String ${sample ? getType(sample) : '?'})`;\n  }\n\n  insert(k, v) {\n    const singleton = {};\n    singleton[k] = v;\n    return new Map(Object.assign({}, this.$value, singleton));\n  }\n\n  reduce(fn, zero) {\n    return this.reduceWithKeys((acc, _, k) => fn(acc, k), zero);\n  }\n\n  reduceWithKeys(fn, zero) {\n    return Object.keys(this.$value)\n      .reduce((acc, k) => fn(acc, this.$value[k], k), zero);\n  }\n\n  map(fn) {\n    return new Map(this.reduceWithKeys((obj, v, k) => {\n      obj[k] = fn(v); // eslint-disable-line no-param-reassign\n      return obj;\n    }, {}));\n  }\n\n  sequence(of) {\n    return this.traverse(of, x => x);\n  }\n\n  traverse(of, fn) {\n    return this.reduceWithKeys(\n      (f, a, k) => fn(a).map(b => m => m.insert(k, b)).ap(f),\n      of(new Map({})),\n    );\n  }\n}\n\n\nclass List {\n  static of(x) {\n    return new List([x]);\n  }\n\n  constructor(xs) {\n    assert(\n      Array.isArray(xs),\n      'tried to create `List` from non-array',\n    );\n\n    this.$value = xs;\n  }\n\n  concat(x) {\n    return new List(this.$value.concat(x));\n  }\n\n  inspect() {\n    return `List(${inspect(this.$value)})`;\n  }\n\n  getType() {\n    const sample = this.$value[0];\n\n    return `(List ${sample ? getType(sample) : '?'})`;\n  }\n\n  map(fn) {\n    return new List(this.$value.map(fn));\n  }\n\n  sequence(of) {\n    return this.traverse(of, x => x);\n  }\n\n  traverse(of, fn) {\n    return this.$value.reduce(\n      (f, a) => fn(a).map(b => bs => bs.concat(b)).ap(f),\n      of(new List([])),\n    );\n  }\n}\n\n\nclass Maybe {\n  static of(x) {\n    return new Maybe(x);\n  }\n\n  get isNothing() {\n    return this.$value === null || this.$value === undefined;\n  }\n\n  get isJust() {\n    return !this.isNothing;\n  }\n\n  constructor(x) {\n    this.$value = x;\n  }\n\n  ap(f) {\n    return this.isNothing ? this : f.map(this.$value);\n  }\n\n  chain(fn) {\n    return this.map(fn).join();\n  }\n\n  inspect() {\n    return this.isNothing ? 'Nothing' : `Just(${inspect(this.$value)})`;\n  }\n\n  getType() {\n    return `(Maybe ${this.isJust ? getType(this.$value) : '?'})`;\n  }\n\n  join() {\n    return this.isNothing ? this : this.$value;\n  }\n\n  map(fn) {\n    return this.isNothing ? this : Maybe.of(fn(this.$value));\n  }\n\n  sequence(of) {\n    return this.traverse(of, x => x);\n  }\n\n  traverse(of, fn) {\n    return this.isNothing ? of(this) : fn(this.$value).map(Maybe.of);\n  }\n}\n\n\nclass Task {\n  constructor(fork) {\n    assert(\n      typeof fork === 'function',\n      'invalid `fork` operation given to Task constructor. Use `Task.of` if you want to lift a value in a default minimal Task context.',\n    );\n\n    this.fork = fork;\n  }\n\n  static of(x) {\n    return new Task((_, resolve) => resolve(x));\n  }\n\n  static rejected(x) {\n    return new Task((reject, _) => reject(x));\n  }\n\n  ap(f) {\n    return this.chain(fn => f.map(fn));\n  }\n\n  chain(fn) {\n    return new Task((reject, resolve) => this.fork(reject, x => fn(x).fork(reject, resolve)));\n  }\n\n  inspect() { // eslint-disable-line class-methods-use-this\n    return 'Task(?)';\n  }\n\n  getType() { // eslint-disable-line class-methods-use-this\n    return '(Task ? ?)';\n  }\n\n  join() {\n    return this.chain(x => x);\n  }\n\n  map(fn) {\n    return new Task((reject, resolve) => this.fork(reject, compose(resolve, fn)));\n  }\n}\n\n// In nodejs the existance of a class method named `inspect` will trigger a deprecation warning\n// when passing an instance to `console.log`:\n// `(node:3845) [DEP0079] DeprecationWarning: Custom inspection function on Objects via .inspect() is deprecated`\n// The solution is to alias the existing inspect method with the special inspect symbol exported by node\nif (typeof module !== 'undefined' && typeof this !== 'undefined' && this.module !== module) {\n  const customInspect = require('util').inspect.custom;\n  const assignCustomInspect = it => it.prototype[customInspect] = it.prototype.inspect;\n  [Left, Right, Identity, IO, Map, List, Maybe, Task].forEach(assignCustomInspect);\n}\n\nconst identity = function identity(x) { return x; };\n\nconst either = curry(function either(f, g, e) {\n  if (e.isLeft) {\n    return f(e.$value);\n  }\n\n  return g(e.$value);\n});\n\nconst left = function left(x) { return new Left(x); };\n\nconst maybe = curry(function maybe(v, f, m) {\n  if (m.isNothing) {\n    return v;\n  }\n\n  return f(m.$value);\n});\n\nconst nothing = Maybe.of(null);\n\nconst reject = function reject(x) { return Task.rejected(x); };\n\nconst chain = curry(function chain(fn, m) {\n  assert(\n    typeof fn === 'function' && typeof m.chain === 'function',\n    typeMismatch('Monad m => (a -> m b) -> m a -> m a', [getType(fn), getType(m), 'm a'].join(' -> '), 'chain'),\n  );\n\n  return m.chain(fn);\n});\n\nconst join = function join(m) {\n  assert(\n    typeof m.chain === 'function',\n    typeMismatch('Monad m => m (m a) -> m a', [getType(m), 'm a'].join(' -> '), 'join'),\n  );\n\n  return m.join();\n};\n\nconst map = curry(function map(fn, f) {\n  assert(\n    typeof fn === 'function' && typeof f.map === 'function',\n    typeMismatch('Functor f => (a -> b) -> f a -> f b', [getType(fn), getType(f), 'f b'].join(' -> '), 'map'),\n  );\n\n  return f.map(fn);\n});\n\nconst sequence = curry(function sequence(of, x) {\n  assert(\n    typeof of === 'function' && typeof x.sequence === 'function',\n    typeMismatch('(Applicative f, Traversable t) => (a -> f a) -> t (f a) -> f (t a)', [getType(of), getType(x), 'f (t a)'].join(' -> '), 'sequence'),\n  );\n\n  return x.sequence(of);\n});\n\nconst traverse = curry(function traverse(of, fn, x) {\n  assert(\n    typeof of === 'function' && typeof fn === 'function' && typeof x.traverse === 'function',\n    typeMismatch(\n      '(Applicative f, Traversable t) => (a -> f a) -> (a -> f b) -> t a -> f (t b)',\n      [getType(of), getType(fn), getType(x), 'f (t b)'].join(' -> '),\n      'traverse',\n    ),\n  );\n\n  return x.traverse(of, fn);\n});\n\nconst unsafePerformIO = function unsafePerformIO(io) {\n  assert(\n    io instanceof IO,\n    typeMismatch('IO a', getType(io), 'unsafePerformIO'),\n  );\n\n  return io.unsafePerformIO();\n};\n\nconst liftA2 = curry(function liftA2(fn, a1, a2) {\n  assert(\n    typeof fn === 'function'\n      && typeof a1.map === 'function'\n      && typeof a2.ap === 'function',\n    typeMismatch('Applicative f => (a -> b -> c) -> f a -> f b -> f c', [getType(fn), getType(a1), getType(a2)].join(' -> '), 'liftA2'),\n  );\n\n  return a1.map(fn).ap(a2);\n});\n\nconst liftA3 = curry(function liftA3(fn, a1, a2, a3) {\n  assert(\n    typeof fn === 'function'\n      && typeof a1.map === 'function'\n      && typeof a2.ap === 'function'\n      && typeof a3.ap === 'function',\n    typeMismatch('Applicative f => (a -> b -> c -> d) -> f a -> f b -> f c -> f d', [getType(fn), getType(a1), getType(a2)].join(' -> '), 'liftA2'),\n  );\n\n  return a1.map(fn).ap(a2).ap(a3);\n});\n\nconst always = curry(function always(a, b) { return a; });\n\n\n/* ---------- Pointfree Classic Utilities ---------- */\n\nconst append = curry(function append(a, b) {\n  assert(\n    typeof a === 'string' && typeof b === 'string',\n    typeMismatch('String -> String -> String', [getType(a), getType(b), 'String'].join(' -> '), 'concat'),\n  );\n\n  return b.concat(a);\n});\n\nconst add = curry(function add(a, b) {\n  assert(\n    typeof a === 'number' && typeof b === 'number',\n    typeMismatch('Number -> Number -> Number', [getType(a), getType(b), 'Number'].join(' -> '), 'add'),\n  );\n\n  return a + b;\n});\n\nconst concat = curry(function concat(a, b) {\n  assert(\n    typeof a === 'string' && typeof b === 'string',\n    typeMismatch('String -> String -> String', [getType(a), getType(b), 'String'].join(' -> '), 'concat'),\n  );\n\n  return a.concat(b);\n});\n\nconst eq = curry(function eq(a, b) {\n  assert(\n    getType(a) === getType(b),\n    typeMismatch('a -> a -> Boolean', [getType(a), getType(b), 'Boolean'].join(' -> '), eq),\n  );\n\n  return a === b;\n});\n\nconst filter = curry(function filter(fn, xs) {\n  assert(\n    typeof fn === 'function' && Array.isArray(xs),\n    typeMismatch('(a -> Boolean) -> [a] -> [a]', [getType(fn), getType(xs), getType(xs)].join(' -> '), 'filter'),\n  );\n\n  return xs.filter(fn);\n});\n\nconst flip = curry(function flip(fn, a, b) {\n  assert(\n    typeof fn === 'function',\n    typeMismatch('(a -> b) -> (b -> a)', [getType(fn), '(b -> a)'].join(' -> '), 'flip'),\n  );\n\n  return fn(b, a);\n});\n\nconst forEach = curry(function forEach(fn, xs) {\n  assert(\n    typeof fn === 'function' && Array.isArray(xs),\n    typeMismatch('(a -> ()) -> [a] -> ()', [getType(fn), getType(xs), '()'].join(' -> '), 'forEach'),\n  );\n\n  xs.forEach(fn);\n});\n\nconst intercalate = curry(function intercalate(str, xs) {\n  assert(\n    typeof str === 'string' && Array.isArray(xs) && (xs.length === 0 || typeof xs[0] === 'string'),\n    typeMismatch('String -> [String] -> String', [getType(str), getType(xs), 'String'].join(' -> '), 'intercalate'),\n  );\n\n  return xs.join(str);\n});\n\nconst head = function head(xs) {\n  assert(\n    Array.isArray(xs) || typeof xs === 'string',\n    typeMismatch('[a] -> a', [getType(xs), 'a'].join(' -> '), 'head'),\n  );\n\n  return xs[0];\n};\n\nconst last = function last(xs) {\n  assert(\n    Array.isArray(xs) || typeof xs === 'string',\n    typeMismatch('[a] -> a', [getType(xs), 'a'].join(' -> '), 'last'),\n  );\n\n  return xs[xs.length - 1];\n};\n\nconst match = curry(function match(re, str) {\n  assert(\n    re instanceof RegExp && typeof str === 'string',\n    typeMismatch('RegExp -> String -> Boolean', [getType(re), getType(str), 'Boolean'].join(' -> '), 'match'),\n  );\n\n  return re.test(str);\n});\n\nconst prop = curry(function prop(p, obj) {\n  assert(\n    typeof p === 'string' && typeof obj === 'object' && obj !== null,\n    typeMismatch('String -> Object -> a', [getType(p), getType(obj), 'a'].join(' -> '), 'prop'),\n  );\n\n  return obj[p];\n});\n\nconst reduce = curry(function reduce(fn, zero, xs) {\n  assert(\n    typeof fn === 'function' && Array.isArray(xs),\n    typeMismatch('(b -> a -> b) -> b -> [a] -> b', [getType(fn), getType(zero), getType(xs), 'b'].join(' -> '), 'reduce'),\n  );\n\n  return xs.reduce(\n    function $reduceIterator($acc, $x) { return fn($acc, $x); },\n    zero,\n  );\n});\n\nconst safeHead = namedAs('safeHead', compose(Maybe.of, head));\n\nconst safeProp = curry(function safeProp(p, obj) { return Maybe.of(prop(p, obj)); });\n\nconst sortBy = curry(function sortBy(fn, xs) {\n  assert(\n    typeof fn === 'function' && Array.isArray(xs),\n    typeMismatch('Ord b => (a -> b) -> [a] -> [a]', [getType(fn), getType(xs), '[a]'].join(' -> '), 'sortBy'),\n  );\n\n  return xs.sort((a, b) => {\n    if (fn(a) === fn(b)) {\n      return 0;\n    }\n\n    return fn(a) > fn(b) ? 1 : -1;\n  });\n});\n\nconst split = curry(function split(s, str) {\n  assert(\n    typeof s === 'string' && typeof str === 'string',\n    typeMismatch('String -> String -> [String]', [getType(s), getType(str), '[String]'].join(' -> '), 'split'),\n  );\n\n  return str.split(s);\n});\n\nconst take = curry(function take(n, xs) {\n  assert(\n    typeof n === 'number' && (Array.isArray(xs) || typeof xs === 'string'),\n    typeMismatch('Number -> [a] -> [a]', [getType(n), getType(xs), getType(xs)].join(' -> '), 'take'),\n  );\n\n  return xs.slice(0, n);\n});\n\nconst toLowerCase = function toLowerCase(s) {\n  assert(\n    typeof s === 'string',\n    typeMismatch('String -> String', [getType(s), '?'].join(' -> '), 'toLowerCase'),\n  );\n\n  return s.toLowerCase();\n};\n\nconst toUpperCase = function toUpperCase(s) {\n  assert(\n    typeof s === 'string',\n    typeMismatch('String -> String', [getType(s), '?'].join(' -> '), 'toLowerCase'),\n  );\n\n  return s.toUpperCase();\n};\n\n\n/* ---------- Chapter 4 ---------- */\n\nconst keepHighest = function keepHighest(x, y) {\n  try {\n    keepHighest.calledBy = keepHighest.caller;\n  } catch (err) {\n    // NOTE node.js runs in strict mode and prohibit the usage of '.caller'\n    // There's a ugly hack to retrieve the caller from stack trace.\n    const [, caller] = /at (\\S+)/.exec(err.stack.split('\\n')[2]);\n\n    keepHighest.calledBy = namedAs(caller, () => {});\n  }\n\n  return x >= y ? x : y;\n};\n\n\n/* ---------- Chapter 5 ---------- */\n\nconst cars = [{\n  name: 'Ferrari FF',\n  horsepower: 660,\n  dollar_value: 700000,\n  in_stock: true,\n}, {\n  name: 'Spyker C12 Zagato',\n  horsepower: 650,\n  dollar_value: 648000,\n  in_stock: false,\n}, {\n  name: 'Jaguar XKR-S',\n  horsepower: 550,\n  dollar_value: 132000,\n  in_stock: true,\n}, {\n  name: 'Audi R8',\n  horsepower: 525,\n  dollar_value: 114200,\n  in_stock: false,\n}, {\n  name: 'Aston Martin One-77',\n  horsepower: 750,\n  dollar_value: 1850000,\n  in_stock: true,\n}, {\n  name: 'Pagani Huayra',\n  horsepower: 700,\n  dollar_value: 1300000,\n  in_stock: false,\n}];\n\nconst average = function average(xs) {\n  return xs.reduce(add, 0) / xs.length;\n};\n\n\n/* ---------- Chapter 8 ---------- */\n\nconst albert = {\n  id: 1,\n  active: true,\n  name: 'Albert',\n  address: {\n    street: {\n      number: 22,\n      name: 'Walnut St',\n    },\n  },\n};\n\nconst gary = {\n  id: 2,\n  active: false,\n  name: 'Gary',\n  address: {\n    street: {\n      number: 14,\n    },\n  },\n};\n\nconst theresa = {\n  id: 3,\n  active: true,\n  name: 'Theresa',\n};\n\nconst yi = { id: 4, name: 'Yi', active: true };\n\nconst showWelcome = namedAs('showWelcome', compose(concat('Welcome '), prop('name')));\n\nconst checkActive = function checkActive(user) {\n  return user.active\n    ? Either.of(user)\n    : left('Your account is not active');\n};\n\nconst save = function save(user) {\n  return new IO(() => Object.assign({}, user, { saved: true }));\n};\n\nconst validateUser = curry(function validateUser(validate, user) {\n  return validate(user).map(_ => user); // eslint-disable-line no-unused-vars\n});\n\n\n/* ---------- Chapter 9 ---------- */\n\nconst getFile = IO.of('/home/mostly-adequate/ch09.md');\n\nconst pureLog = function pureLog(str) { return new IO(() => { console.log(str); return str; }); };\n\nconst addToMailingList = function addToMailingList(email) { return IO.of([email]); };\n\nconst emailBlast = function emailBlast(list) { return IO.of(list.join(',')); };\n\nconst validateEmail = function validateEmail(x) {\n  return /\\S+@\\S+\\.\\S+/.test(x)\n    ? Either.of(x)\n    : left('invalid email');\n};\n\n\n/* ---------- Chapter 10 ---------- */\n\nconst localStorage = { player1: albert, player2: theresa };\n\nconst game = curry(function game(p1, p2) { return `${p1.name} vs ${p2.name}`; });\n\nconst getFromCache = function getFromCache(x) { return new IO(() => localStorage[x]); };\n\n\n/* ---------- Chapter 11 ---------- */\n\nconst findUserById = function findUserById(id) {\n  switch (id) {\n    case 1:\n      return Task.of(Either.of(albert));\n\n    case 2:\n      return Task.of(Either.of(gary));\n\n    case 3:\n      return Task.of(Either.of(theresa));\n\n    default:\n      return Task.of(left('not found'));\n  }\n};\n\nconst eitherToTask = namedAs('eitherToTask', either(Task.rejected, Task.of));\n\n\n/* ---------- Chapter 12 ---------- */\n\nconst httpGet = function httpGet(route) { return Task.of(`json for ${route}`); };\n\nconst routes = new Map({\n  '/': '/',\n  '/about': '/about',\n});\n\nconst validate = function validate(player) {\n  return player.name\n    ? Either.of(player)\n    : left('must have name');\n};\n\nconst readdir = function readdir(dir) {\n  return Task.of(['file1', 'file2', 'file3']);\n};\n\nconst readfile = curry(function readfile(encoding, file) {\n  return Task.of(`content of ${file} (${encoding})`);\n});\n\n\n/* ---------- Exports ---------- */\n\nif (typeof module === 'object') {\n  module.exports = {\n    // Utils\n    withSpyOn,\n\n    // Essential FP helpers\n    always,\n    compose,\n    curry,\n    either,\n    identity,\n    inspect,\n    left,\n    liftA2,\n    liftA3,\n    maybe,\n    nothing,\n    reject,\n\n    // Algebraic Data Structures\n    Either,\n    IO,\n    Identity,\n    Left,\n    List,\n    Map,\n    Maybe,\n    Right,\n    Task,\n\n    // Currified version of 'standard' functions\n    append,\n    add,\n    chain,\n    concat,\n    eq,\n    filter,\n    flip,\n    forEach,\n    head,\n    intercalate,\n    join,\n    last,\n    map,\n    match,\n    prop,\n    reduce,\n    safeHead,\n    safeProp,\n    sequence,\n    sortBy,\n    split,\n    take,\n    toLowerCase,\n    toUpperCase,\n    traverse,\n    unsafePerformIO,\n\n    // Chapter 04\n    keepHighest,\n\n    // Chapter 05\n    cars,\n    average,\n\n    // Chapter 08\n    albert,\n    gary,\n    theresa,\n    yi,\n    showWelcome,\n    checkActive,\n    save,\n    validateUser,\n\n    // Chapter 09\n    getFile,\n    pureLog,\n    addToMailingList,\n    emailBlast,\n    validateEmail,\n\n    // Chapter 10\n    localStorage,\n    getFromCache,\n    game,\n\n    // Chapter 11\n    findUserById,\n    eitherToTask,\n\n    // Chapter 12\n    httpGet,\n    routes,\n    validate,\n    readdir,\n    readfile,\n  };\n}\n"
  },
  {
    "path": "exercises/test/ch04.js",
    "content": "const { describe } = require('mocha');\nconst { runExercises } = require('../test-utils');\n\ndescribe('Exercises Chapter 04', () => {\n  runExercises('ch04');\n});\n"
  },
  {
    "path": "exercises/test/ch04.solutions.js",
    "content": "const { describe } = require('mocha');\nconst { runSolutions } = require('../test-utils');\n\ndescribe('Exercises Chapter 04', () => {\n  runSolutions('ch04');\n});\n"
  },
  {
    "path": "exercises/test/ch05.js",
    "content": "const { describe } = require('mocha');\nconst { runExercises } = require('../test-utils');\n\ndescribe('Exercises Chapter 05', () => {\n  runExercises('ch05');\n});\n"
  },
  {
    "path": "exercises/test/ch05.solutions.js",
    "content": "const { describe } = require('mocha');\nconst { runSolutions } = require('../test-utils');\n\ndescribe('Exercises Chapter 05', () => {\n  runSolutions('ch05');\n});\n"
  },
  {
    "path": "exercises/test/ch08.js",
    "content": "const { describe } = require('mocha');\nconst { runExercises } = require('../test-utils');\n\ndescribe('Exercises Chapter 08', () => {\n  runExercises('ch08');\n});\n"
  },
  {
    "path": "exercises/test/ch08.solutions.js",
    "content": "const { describe } = require('mocha');\nconst { runSolutions } = require('../test-utils');\n\ndescribe('Exercises Chapter 08', () => {\n  runSolutions('ch08');\n});\n"
  },
  {
    "path": "exercises/test/ch09.js",
    "content": "const { describe } = require('mocha');\nconst { runExercises } = require('../test-utils');\n\ndescribe('Exercises Chapter 09', () => {\n  runExercises('ch09');\n});\n"
  },
  {
    "path": "exercises/test/ch09.solutions.js",
    "content": "const { describe } = require('mocha');\nconst { runSolutions } = require('../test-utils');\n\ndescribe('Exercises Chapter 09', () => {\n  runSolutions('ch09');\n});\n"
  },
  {
    "path": "exercises/test/ch10.js",
    "content": "const { describe } = require('mocha');\nconst { runExercises } = require('../test-utils');\n\ndescribe('Exercises Chapter 10', () => {\n  runExercises('ch10');\n});\n\n"
  },
  {
    "path": "exercises/test/ch10.solutions.js",
    "content": "const { describe } = require('mocha');\nconst { runSolutions } = require('../test-utils');\n\ndescribe('Exercises Chapter 10', () => {\n  runSolutions('ch10');\n});\n\n"
  },
  {
    "path": "exercises/test/ch11.js",
    "content": "const { describe } = require('mocha');\nconst { runExercises } = require('../test-utils');\n\ndescribe('Exercises Chapter 11', () => {\n  runExercises('ch11');\n});\n\n"
  },
  {
    "path": "exercises/test/ch11.solutions.js",
    "content": "const { describe } = require('mocha');\nconst { runSolutions } = require('../test-utils');\n\ndescribe('Exercises Chapter 11', () => {\n  runSolutions('ch11');\n});\n\n"
  },
  {
    "path": "exercises/test/ch12.js",
    "content": "const { describe } = require('mocha');\nconst { runExercises } = require('../test-utils');\n\ndescribe('Exercises Chapter 12', () => {\n  runExercises('ch12');\n});\n\n"
  },
  {
    "path": "exercises/test/ch12.solutions.js",
    "content": "const { describe } = require('mocha');\nconst { runSolutions } = require('../test-utils');\n\ndescribe('Exercises Chapter 12', () => {\n  runSolutions('ch12');\n});\n\n"
  },
  {
    "path": "exercises/test-utils.js",
    "content": "#!/usr/bin/env node\n\nconst fs = require('fs');\nconst path = require('path');\nconst cli = require('cli');\nconst process = require('process');\nconst { it } = require('mocha');\nconst {\n  compose,\n  concat,\n  curry,\n  forEach,\n  map,\n  reduce,\n} = require('./support');\n\n\n/* -------- Internal -------- */\n\nconst filenameRe = base => new RegExp(`${base}_([a-z]).js`);\n\nconst readDir = d => fs.readdirSync(d);\n\nconst readFile = f => fs.readFileSync(f).toString('utf-8');\n\nconst writeFile = curry((f, data) => fs.writeFileSync(f, data));\n\nconst mkdir = d => fs.mkdirSync(d);\n\nconst mconcat = zero => reduce(concat, zero);\n\nconst evalFiles = compose(eval, mconcat(''), map(readFile)); // eslint-disable-line no-eval\n\nconst listToMap = xs => xs.reduce((m, [k, v]) => m.set(k, v), new Map());\n\n\n/* -------- Utils -------- */\n\nconst readExercises = (ch, sections = ['exercise', 'solution', 'validation']) => {\n  const folder = path.join(__dirname, ch);\n\n  const partition = reduce((pts, f) => {\n    forEach((section) => {\n      const re = filenameRe(section);\n\n      if (re.test(f)) {\n        const spec = re.exec(f)[1];\n        pts.get(section).set(spec, path.join(folder, f));\n      }\n    }, sections);\n\n    return pts;\n  }, listToMap(map(s => [s, new Map()], sections)));\n\n  return partition(readDir(folder));\n};\n\nconst defineSpecs = curry((input, exercises) => {\n  const support = path.join(__dirname, 'support.js');\n\n  forEach(([num, exercise]) => {\n    it(`exercise_${num}`, () => {\n      const validation = exercises.get('validation').get(num);\n\n      evalFiles([support, exercise, validation]);\n    });\n  }, [...exercises.get(input)]);\n});\n\nconst runSolutions = compose(defineSpecs('solution'), readExercises);\n\nconst runExercises = compose(defineSpecs('exercise'), readExercises);\n\n\n/* -------- Cli -------- */\n\nif (process.argv.length > 2 && process.argv[1] === __filename) {\n  const usage = `Usage: test-utils new\n\nAvailable options:\n  -h, --help                Show this help text\n  -c, --chapter             New chapter to create`;\n\n  const spec = curry((runner, chapter) => `const { describe } = require('mocha');\nconst { ${runner} } = require('../test-utils');\n\ndescribe('Exercises Chapter ${chapter}', () => {\n  ${runner}('ch${chapter}');\n});`);\n\n  const addTestScript = curry((pkg, chapter) => {\n    const { scripts } = pkg;\n\n    return {\n      ...pkg,\n      scripts: {\n        ...scripts,\n        [`ch${chapter}`]: `mocha test/ch${chapter}.js`,\n      },\n    };\n  });\n\n  const failWith = curry((ctx, msg) => {\n    ctx.fatal([msg, usage].join('\\n\\n'));\n  });\n\n  // NOTE Override the `getUsage` method of the cli which is... not satisfactory.\n  cli.getUsage = () => { console.error(usage); cli.exit(0); }; // eslint-disable-line no-console\n\n  cli.parse({\n    chapter: ['c', 'New chapter to create', 'int'],\n  });\n\n  cli.main(function main(args, options) {\n    cli.failWith = failWith(this);\n\n    if (args.length !== 1 || args[0] !== 'new') {\n      cli.failWith(`Unknown command: ${args.join(' ')}`);\n    }\n\n    if (!options.chapter) {\n      cli.failWith('Missing required Chapter');\n    }\n\n    if (readDir(__dirname).includes(`ch${options.chapter}`)) {\n      cli.failWith(`Chapter ${options.chapter} already exists`);\n    }\n\n    mkdir(path.join(__dirname, `ch${options.chapter}`));\n\n    writeFile(\n      path.join(__dirname, 'test', `ch${options.chapter}.js`),\n      spec('runExercises', options.chapter),\n    );\n\n    writeFile(\n      path.join(__dirname, 'test', `ch${options.chapter}.solutions.js`),\n      spec('runSolutions', options.chapter),\n    );\n\n    const pkg = addTestScript(require('./package.json'), options.chapter); // eslint-disable-line global-require\n\n    writeFile(\n      path.join(__dirname, 'package.json'),\n      JSON.stringify(pkg, null, 2),\n    );\n\n    console.error(`Bootstrapped Chapter ${options.chapter}.`); // eslint-disable-line no-console\n  });\n}\n\n\n/* -------- Exports -------- */\n\nmodule.exports = {\n  readExercises,\n  defineSpecs,\n  runSolutions,\n  runExercises,\n};\n"
  },
  {
    "path": "package.json",
    "content": "{\n  \"name\": \"mostly-adequate-guide\",\n  \"version\": \"1.0.0\",\n  \"description\": \"The Mostly Adequate Guide to Functional Programming\",\n  \"dependencies\": {\n    \"gitbook-plugin-exercises\": \"git+https://github.com/MostlyAdequate/plugin-exercises.git\",\n    \"gitbook-plugin-include-codeblock\": \"^3.2.2\"\n  },\n  \"devDependencies\": {\n    \"gitbook-cli\": \"^2.3.2\"\n  },\n  \"scripts\": {\n    \"setup\": \"$(npm bin)/gitbook install\",\n    \"start\": \"$(npm bin)/gitbook serve\",\n    \"generate-summary\": \"perl -n .generate-summary.pl ch*.md appendix_*.md > SUMMARY.md\",\n    \"generate-epub\": \"gitbook epub\",\n    \"generate-pdf\": \"gitbook pdf\"\n  },\n  \"repository\": {\n    \"type\": \"git\",\n    \"url\": \"git+https://github.com/MostlyAdequate/mostly-adequate-guide.git\"\n  },\n  \"keywords\": [\n    \"gitbook\",\n    \"javascript\",\n    \"guide\",\n    \"functional programming\"\n  ],\n  \"author\": \"Mostly Adequate Core Team\",\n  \"license\": \"CC BY-SA\",\n  \"bugs\": {\n    \"url\": \"https://github.com/MostlyAdequate/mostly-adequate-guide/issues\"\n  },\n  \"homepage\": \"https://github.com/MostlyAdequate/mostly-adequate-guide#readme\"\n}\n"
  },
  {
    "path": "styles/website.css",
    "content": ".book.color-theme-1 .book-body .page-wrapper .page-inner section.normal a {\n    color: initial;\n}\n"
  },
  {
    "path": "support/.eslintrc.js",
    "content": "const globals = Object\n  .keys(require('./support'))\n  .reduce((o, k) => ({ ...o, [k]: true }), { requirejs: true, assert: true });\n\nmodule.exports = {\n  extends: 'airbnb',\n  env: {\n    browser: true,\n    amd: true,\n  },\n  globals,\n  rules: {\n    'import/no-amd': 0,\n    'import/no-dynamic-require': 0,\n    'no-unused-vars': 0,\n    'object-curly-newline': [2, {\n      multiline: true,\n      consistent: true,\n      minProperties: 5,\n    }],\n  },\n};\n"
  },
  {
    "path": "support/.npmignore",
    "content": "ch*\ntest*\n.eslintrc.js\nnode-modules\ntest-util.js\nsupport.js\nbuild-appendixes\n"
  },
  {
    "path": "support/CHANGELOG.md",
    "content": "# 2.0.1 - 2019-06-26\n\n- Fix `Maybe.sequence` missing a `return` statement\n\n# 2.0.0 - 2019-05-24\n\n- Change `nothing :: () -> Maybe a` to `nothing :: Maybe a`\n\n# 1.2.0 - 2019-05-05\n\n- Fix `inspect` deprecation warning on node.js\n"
  },
  {
    "path": "support/README.md",
    "content": "# Mostly Adequate Guide to Functional Programming - Support\n\n## Overview \n\nThis package contains all functions and data-structure referenced in the\nappendixes of the [Mostly Adequate Guide to Functional Programming](https://github.com/MostlyAdequate/mostly-adequate-guide).\n\nThese functions have an educational purpose and aren't intended to be used in\nany production environment. They are however, a good learning material for anyone\ninterested in functional programming.\n\n## How to install\n\nThe package is available on `npm` and can be installed via the following incantation:\n\n```\nnpm install @mostly-adequate/support\n```\n\n## How to use\n\nThere's no particular structure to the module, everything is flat and exported\nfrom the root (the curious reader may have a quick glance at the `index.js` to\nget convinced about this). \n\nAlso, all top-level functions are curried so you don't have to worry about calling\n`curry` on any of them.\n\nFor example:\n\n```js\nconst { Maybe, liftA2, append, concat, reverse } = require('@mostly-adequate/support');\n\nconst a = Maybe.of(\"yltsoM\").map(reverse);\nconst b = Maybe.of(\"Adequate\").map(concat(\" \"));\n\nliftA2(append)(b)(a);\n// Just(\"Mostly Adequate\")\n```\n"
  },
  {
    "path": "support/build-appendixes",
    "content": "#!/usr/bin/env node\n\nconst fs = require('fs');\nconst path = require('path');\nconst { promisify } = require('util');\n\n/* Input / Output Configuration */\nconst OUTPUT = path.join(__dirname, 'index.js');\nconst INPUTDIR = path.join(__dirname, '..');\n\n\n/* Helpers */\nFunction.prototype.compose = function (f) { return x => f(this(x)); }\n\nfunction readFileP(filename, inDir = INPUTDIR) {\n  return promisify(fs.readFile)(path.join(inDir, filename));\n}\n\nfunction toString(x) {\n  return x.toString();\n}\n\nfunction parseDefinitions(data) {\n  const re = new RegExp('```js(.*)```', 'sm');\n  const paragraphs = data.split(/###?#?/);\n  return paragraphs\n    .map(x => re.exec(x))\n    .filter(x => x != null)\n    .map(x => x[1]);\n}\n\nfunction flatten(xss) {\n  return xss.reduce((acc, xs) => acc.concat(xs), []);\n}\n\nconst header = `/* LICENSE MIT-2.0 - @MostlyAdequate */\n/* eslint-disable no-use-before-define, max-len, class-methods-use-this */\n`;\n\n\n/* Actual function */\nPromise\n  .all([\n    readFileP('appendix_a.md').then(toString.compose(parseDefinitions)),\n    readFileP('appendix_b.md').then(toString.compose(parseDefinitions)),\n    readFileP('appendix_c.md').then(toString.compose(parseDefinitions)),\n  ])\n  .then((definitions) => {\n    definitions = flatten(definitions);\n    const exports_ = definitions\n      .map(x => x.match(/(const|class|function) ([a-zA-Z0-9]+)( |\\()/)[2])\n      .map(x => `exports.${x} = ${x};`);\n    const output = header + definitions.join('\\n') + '\\n\\n' + exports_.join('\\n');\n    return promisify(fs.writeFile)(OUTPUT, output);\n  })\n  .catch(console.error);\n"
  },
  {
    "path": "support/index.js",
    "content": "/* LICENSE MIT-2.0 - @MostlyAdequate */\n/* eslint-disable no-use-before-define, max-len, class-methods-use-this */\n\nconst util = require('util');\n\n// always :: a -> b -> a\nconst always = curry((a, b) => a);\n\n\n// compose :: ((a -> b), (b -> c),  ..., (y -> z)) -> a -> z\nconst compose = (...fns) => (...args) => fns.reduceRight((res, fn) => [fn.call(null, ...res)], args)[0];\n\n\n// curry :: ((a, b, ...) -> c) -> a -> b -> ... -> c\nfunction curry(fn) {\n  const arity = fn.length;\n\n  return function $curry(...args) {\n    if (args.length < arity) {\n      return $curry.bind(null, ...args);\n    }\n\n    return fn.call(null, ...args);\n  };\n}\n\n\n// either :: (a -> c) -> (b -> c) -> Either a b -> c\nconst either = curry((f, g, e) => {\n  if (e.isLeft) {\n    return f(e.$value);\n  }\n\n  return g(e.$value);\n});\n\n\n// identity :: x -> x\nconst identity = x => x;\n\n\n// inspect :: a -> String\nconst inspect = (x) => {\n  if (x && typeof x.inspect === 'function') {\n    return x.inspect();\n  }\n\n  function inspectFn(f) {\n    return f.name ? f.name : f.toString();\n  }\n\n  function inspectTerm(t) {\n    switch (typeof t) {\n      case 'string':\n        return `'${t}'`;\n      case 'object': {\n        const ts = Object.keys(t).map(k => [k, inspect(t[k])]);\n        return `{${ts.map(kv => kv.join(': ')).join(', ')}}`;\n      }\n      default:\n        return String(t);\n    }\n  }\n\n  function inspectArgs(args) {\n    return Array.isArray(args) ? `[${args.map(inspect).join(', ')}]` : inspectTerm(args);\n  }\n\n  return (typeof x === 'function') ? inspectFn(x) : inspectArgs(x);\n};\n\n\n// left :: a -> Either a b\nconst left = a => new Left(a);\n\n\n// liftA2 :: (Applicative f) => (a1 -> a2 -> b) -> f a1 -> f a2 -> f b\nconst liftA2 = curry((fn, a1, a2) => a1.map(fn).ap(a2));\n\n\n// liftA3 :: (Applicative f) => (a1 -> a2 -> a3 -> b) -> f a1 -> f a2 -> f a3 -> f b\nconst liftA3 = curry((fn, a1, a2, a3) => a1.map(fn).ap(a2).ap(a3));\n\n\n// maybe :: b -> (a -> b) -> Maybe a -> b\nconst maybe = curry((v, f, m) => {\n  if (m.isNothing) {\n    return v;\n  }\n\n  return f(m.$value);\n});\n\n\nconst createCompose = curry((F, G) => class Compose {\n  constructor(x) {\n    this.$value = x;\n  }\n\n  [util.inspect.custom]() {\n    return `Compose(${inspect(this.$value)})`;\n  }\n\n  // ----- Pointed (Compose F G)\n  static of(x) {\n    return new Compose(F(G(x)));\n  }\n\n  // ----- Functor (Compose F G)\n  map(fn) {\n    return new Compose(this.$value.map(x => x.map(fn)));\n  }\n\n  // ----- Applicative (Compose F G)\n  ap(f) {\n    return f.map(this.$value);\n  }\n});\n\n\nclass Either {\n  constructor(x) {\n    this.$value = x;\n  }\n\n  // ----- Pointed (Either a)\n  static of(x) {\n    return new Right(x);\n  }\n}\n\n\nclass Left extends Either {\n  get isLeft() {\n    return true;\n  }\n\n  get isRight() {\n    return false;\n  }\n\n  static of(x) {\n    throw new Error('`of` called on class Left (value) instead of Either (type)');\n  }\n\n  [util.inspect.custom]() {\n    return `Left(${inspect(this.$value)})`;\n  }\n\n  // ----- Functor (Either a)\n  map() {\n    return this;\n  }\n\n  // ----- Applicative (Either a)\n  ap() {\n    return this;\n  }\n\n  // ----- Monad (Either a)\n  chain() {\n    return this;\n  }\n\n  join() {\n    return this;\n  }\n\n  // ----- Traversable (Either a)\n  sequence(of) {\n    return of(this);\n  }\n\n  traverse(of, fn) {\n    return of(this);\n  }\n}\n\n\nclass Right extends Either {\n  get isLeft() {\n    return false;\n  }\n\n  get isRight() {\n    return true;\n  }\n\n  static of(x) {\n    throw new Error('`of` called on class Right (value) instead of Either (type)');\n  }\n\n  [util.inspect.custom]() {\n    return `Right(${inspect(this.$value)})`;\n  }\n\n  // ----- Functor (Either a)\n  map(fn) {\n    return Either.of(fn(this.$value));\n  }\n\n  // ----- Applicative (Either a)\n  ap(f) {\n    return f.map(this.$value);\n  }\n\n  // ----- Monad (Either a)\n  chain(fn) {\n    return fn(this.$value);\n  }\n\n  join() {\n    return this.$value;\n  }\n\n  // ----- Traversable (Either a)\n  sequence(of) {\n    return this.traverse(of, identity);\n  }\n\n  traverse(of, fn) {\n    fn(this.$value).map(Either.of);\n  }\n}\n\n\nclass Identity {\n  constructor(x) {\n    this.$value = x;\n  }\n\n  [util.inspect.custom]() {\n    return `Identity(${inspect(this.$value)})`;\n  }\n\n  // ----- Pointed Identity\n  static of(x) {\n    return new Identity(x);\n  }\n\n  // ----- Functor Identity\n  map(fn) {\n    return Identity.of(fn(this.$value));\n  }\n\n  // ----- Applicative Identity\n  ap(f) {\n    return f.map(this.$value);\n  }\n\n  // ----- Monad Identity\n  chain(fn) {\n    return this.map(fn).join();\n  }\n\n  join() {\n    return this.$value;\n  }\n\n  // ----- Traversable Identity\n  sequence(of) {\n    return this.traverse(of, identity);\n  }\n\n  traverse(of, fn) {\n    return fn(this.$value).map(Identity.of);\n  }\n}\n\n\nclass IO {\n  constructor(fn) {\n    this.unsafePerformIO = fn;\n  }\n\n  [util.inspect.custom]() {\n    return 'IO(?)';\n  }\n\n  // ----- Pointed IO\n  static of(x) {\n    return new IO(() => x);\n  }\n\n  // ----- Functor IO\n  map(fn) {\n    return new IO(compose(fn, this.unsafePerformIO));\n  }\n\n  // ----- Applicative IO\n  ap(f) {\n    return this.chain(fn => f.map(fn));\n  }\n\n  // ----- Monad IO\n  chain(fn) {\n    return this.map(fn).join();\n  }\n\n  join() {\n    return new IO(() => this.unsafePerformIO().unsafePerformIO());\n  }\n}\n\n\nclass List {\n  constructor(xs) {\n    this.$value = xs;\n  }\n\n  [util.inspect.custom]() {\n    return `List(${inspect(this.$value)})`;\n  }\n\n  concat(x) {\n    return new List(this.$value.concat(x));\n  }\n\n  // ----- Pointed List\n  static of(x) {\n    return new List([x]);\n  }\n\n  // ----- Functor List\n  map(fn) {\n    return new List(this.$value.map(fn));\n  }\n\n  // ----- Traversable List\n  sequence(of) {\n    return this.traverse(of, identity);\n  }\n\n  traverse(of, fn) {\n    return this.$value.reduce(\n      (f, a) => fn(a).map(b => bs => bs.concat(b)).ap(f),\n      of(new List([])),\n    );\n  }\n}\n\n\nclass Map {\n  constructor(x) {\n    this.$value = x;\n  }\n\n  [util.inspect.custom]() {\n    return `Map(${inspect(this.$value)})`;\n  }\n\n  insert(k, v) {\n    const singleton = {};\n    singleton[k] = v;\n    return Map.of(Object.assign({}, this.$value, singleton));\n  }\n\n  reduceWithKeys(fn, zero) {\n    return Object.keys(this.$value)\n      .reduce((acc, k) => fn(acc, this.$value[k], k), zero);\n  }\n\n  // ----- Functor (Map a)\n  map(fn) {\n    return this.reduceWithKeys(\n      (m, v, k) => m.insert(k, fn(v)),\n      new Map({}),\n    );\n  }\n\n  // ----- Traversable (Map a)\n  sequence(of) {\n    return this.traverse(of, identity);\n  }\n\n  traverse(of, fn) {\n    return this.reduceWithKeys(\n      (f, a, k) => fn(a).map(b => m => m.insert(k, b)).ap(f),\n      of(new Map({})),\n    );\n  }\n}\n\n\nclass Maybe {\n  get isNothing() {\n    return this.$value === null || this.$value === undefined;\n  }\n\n  get isJust() {\n    return !this.isNothing;\n  }\n\n  constructor(x) {\n    this.$value = x;\n  }\n\n  [util.inspect.custom]() {\n    return this.isNothing ? 'Nothing' : `Just(${inspect(this.$value)})`;\n  }\n\n  // ----- Pointed Maybe\n  static of(x) {\n    return new Maybe(x);\n  }\n\n  // ----- Functor Maybe\n  map(fn) {\n    return this.isNothing ? this : Maybe.of(fn(this.$value));\n  }\n\n  // ----- Applicative Maybe\n  ap(f) {\n    return this.isNothing ? this : f.map(this.$value);\n  }\n\n  // ----- Monad Maybe\n  chain(fn) {\n    return this.map(fn).join();\n  }\n\n  join() {\n    return this.isNothing ? this : this.$value;\n  }\n\n  // ----- Traversable Maybe\n  sequence(of) {\n    return this.traverse(of, identity);\n  }\n\n  traverse(of, fn) {\n    return this.isNothing ? of(this) : fn(this.$value).map(Maybe.of);\n  }\n}\n\n\nclass Task {\n  constructor(fork) {\n    this.fork = fork;\n  }\n\n  [util.inspect.custom]() {\n    return 'Task(?)';\n  }\n\n  static rejected(x) {\n    return new Task((reject_, _) => reject_(x));\n  }\n\n  // ----- Pointed (Task a)\n  static of(x) {\n    return new Task((_, resolve) => resolve(x));\n  }\n\n  // ----- Functor (Task a)\n  map(fn) {\n    return new Task((reject_, resolve) => this.fork(reject_, compose(resolve, fn)));\n  }\n\n  // ----- Applicative (Task a)\n  ap(f) {\n    return this.chain(fn => f.map(fn));\n  }\n\n  // ----- Monad (Task a)\n  chain(fn) {\n    return new Task((reject_, resolve) => this.fork(reject_, x => fn(x).fork(reject_, resolve)));\n  }\n\n  join() {\n    return this.chain(identity);\n  }\n}\n\n\n// nothing :: Maybe a\nconst nothing = Maybe.of(null);\n\n\n// reject :: a -> Task a b\nconst reject = a => Task.rejected(a);\n\n\n// flip :: (a -> b -> c) -> b -> a -> c\nconst flip = curry((fn, a, b) => fn(b, a));\n\n\n// concat :: String -> String -> String\nconst concat = curry((a, b) => a.concat(b));\n\n\n// add :: Number -> Number -> Number\nconst add = curry((a, b) => a + b);\n\n\n// append :: String -> String -> String\nconst append = flip(concat);\n\n\n// chain :: Monad m => (a -> m b) -> m a -> m b\nconst chain = curry((fn, m) => m.chain(fn));\n\n\n// eq :: Eq a => a -> a -> Boolean\nconst eq = curry((a, b) => a === b);\n\n\n// filter :: (a -> Boolean) -> [a] -> [a]\nconst filter = curry((fn, xs) => xs.filter(fn));\n\n\n// forEach :: (a -> ()) -> [a] -> ()\nconst forEach = curry((fn, xs) => xs.forEach(fn));\n\n\n// head :: [a] -> a\nconst head = xs => xs[0];\n\n\n// intercalate :: String -> [String] -> String\nconst intercalate = curry((str, xs) => xs.join(str));\n\n\n// join :: Monad m => m (m a) -> m a\nconst join = m => m.join();\n\n\n// last :: [a] -> a\nconst last = xs => xs[xs.length - 1];\n\n\n// map :: Functor f => (a -> b) -> f a -> f b\nconst map = curry((fn, f) => f.map(fn));\n\n\n// match :: RegExp -> String -> Boolean\nconst match = curry((re, str) => re.test(str));\n\n\n// prop :: String -> Object -> a\nconst prop = curry((p, obj) => obj[p]);\n\n\n// reduce :: (b -> a -> b) -> b -> [a] -> b\nconst reduce = curry((fn, zero, xs) => xs.reduce(fn, zero));\n\n\n// replace :: RegExp -> String -> String -> String\nconst replace = curry((re, rpl, str) => str.replace(re, rpl));\n\n\n// reverse :: [a] -> [a]\nconst reverse = x => (Array.isArray(x) ? x.reverse() : x.split('').reverse().join(''));\n\n\n// safeHead :: [a] -> Maybe a\nconst safeHead = compose(Maybe.of, head);\n\n\n// safeLast :: [a] -> Maybe a\nconst safeLast = compose(Maybe.of, last);\n\n\n// safeProp :: String -> Object -> Maybe a\nconst safeProp = curry((p, obj) => compose(Maybe.of, prop(p))(obj));\n\n\n// sequence :: (Applicative f, Traversable t) => (a -> f a) -> t (f a) -> f (t a)\nconst sequence = curry((of, f) => f.sequence(of));\n\n\n// sortBy :: Ord b => (a -> b) -> [a] -> [a]\nconst sortBy = curry((fn, xs) => xs.sort((a, b) => {\n  if (fn(a) === fn(b)) {\n    return 0;\n  }\n\n  return fn(a) > fn(b) ? 1 : -1;\n}));\n\n\n// split :: String -> String -> [String]\nconst split = curry((sep, str) => str.split(sep));\n\n\n// take :: Number -> [a] -> [a]\nconst take = curry((n, xs) => xs.slice(0, n));\n\n\n// toLowerCase :: String -> String\nconst toLowerCase = s => s.toLowerCase();\n\n\n// toString :: a -> String\nconst toString = String;\n\n\n// toUpperCase :: String -> String\nconst toUpperCase = s => s.toUpperCase();\n\n\n// traverse :: (Applicative f, Traversable t) => (a -> f a) -> (a -> f b) -> t a -> f (t b)\nconst traverse = curry((of, fn, f) => f.traverse(of, fn));\n\n\n// unsafePerformIO :: IO a -> a\nconst unsafePerformIO = io => io.unsafePerformIO();\n\n\nexports.always = always;\nexports.compose = compose;\nexports.curry = curry;\nexports.either = either;\nexports.identity = identity;\nexports.inspect = inspect;\nexports.left = left;\nexports.liftA2 = liftA2;\nexports.liftA3 = liftA3;\nexports.maybe = maybe;\nexports.nothing = nothing;\nexports.reject = reject;\nexports.createCompose = createCompose;\nexports.Either = Either;\nexports.Left = Left;\nexports.Right = Right;\nexports.Identity = Identity;\nexports.IO = IO;\nexports.List = List;\nexports.Map = Map;\nexports.Maybe = Maybe;\nexports.Task = Task;\nexports.add = add;\nexports.append = append;\nexports.chain = chain;\nexports.concat = concat;\nexports.eq = eq;\nexports.filter = filter;\nexports.flip = flip;\nexports.forEach = forEach;\nexports.head = head;\nexports.intercalate = intercalate;\nexports.join = join;\nexports.last = last;\nexports.map = map;\nexports.match = match;\nexports.prop = prop;\nexports.reduce = reduce;\nexports.replace = replace;\nexports.reverse = reverse;\nexports.safeHead = safeHead;\nexports.safeLast = safeLast;\nexports.safeProp = safeProp;\nexports.sequence = sequence;\nexports.sortBy = sortBy;\nexports.split = split;\nexports.take = take;\nexports.toLowerCase = toLowerCase;\nexports.toString = toString;\nexports.toUpperCase = toUpperCase;\nexports.traverse = traverse;\nexports.unsafePerformIO = unsafePerformIO;\n"
  },
  {
    "path": "support/package.json",
    "content": "{\n  \"name\": \"@mostly-adequate/support\",\n  \"version\": \"2.0.1\",\n  \"description\": \"Support functions and data-structures from the Mostly Adequate Guide to Functional Programming\",\n  \"license\": \"MIT\",\n  \"main\": \"index.js\",\n  \"repository\": {\n    \"type\": \"git\",\n    \"url\": \"https://github.com/MostlyAdequate/mostly-adequate-guide\"\n  },\n  \"author\": \"@mostly-adequate\",\n  \"bugs\": {\n    \"url\": \"https://github.com/MostlyAdequate/mostly-adequate-guide/issues\"\n  },\n  \"homepage\": \"https://github.com/MostlyAdequate/mostly-adequate-guide/support\",\n  \"keywords\": [\n    \"functional programming\",\n    \"mostly adequate\",\n    \"guide\",\n    \"fp\"\n  ],\n  \"dependencies\": {},\n  \"devDependencies\": {\n    \"eslint\": \"^5.9.0\",\n    \"eslint-config-airbnb\": \"^16.1.0\",\n    \"eslint-plugin-import\": \"^2.8.0\",\n    \"eslint-plugin-jsx-a11y\": \"^6.0.2\",\n    \"eslint-plugin-react\": \"^7.5.1\"\n  },\n  \"scripts\": {\n    \"lint\": \"eslint .\"\n  }\n}\n"
  }
]