{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Recursion Combinators\n",
    "\n",
    "This article describes the `genrec` combinator and how to use it, and then gives several specializations.\n",
    "The `genrec` combinator isn't the only way to make recursive functions in Joy, you can also use the `x` combinator with a `branch` to create recursive functions.  (Because definitions aren't checked for self-reference you can also define recursive functions directly in definitions, but this, I believe, should be considered bad form.)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## General Recursive Function\n",
    "\n",
    "In Joy recursive functions are defined by the `genrec` combinator which accepts four quoted programs:\n",
    "\n",
    "    F == [if] [then] [rec1] [rec2] genrec\n",
    "\n",
    "This can be thought of as transforming into an \"if..then..else\" expression using the `ifte` combinator and containing a quoted copy of itself in the \"else\" branch:\n",
    "\n",
    "    F == [if] [then] [rec1 [F] rec2] ifte\n",
    "\n",
    "From [\"Recursion Theory and Joy\"](https://www.kevinalbrecht.com/code/joy-mirror/j05cmp.html) by Manfred von Thun:\n",
    "\n",
    "> \"The genrec combinator takes four program parameters in addition to\n",
    "whatever data parameters it needs. Fourth from the top is an if-part,\n",
    "followed by a then-part. If the if-part yields true, then the then-part\n",
    "is executed and the combinator terminates. The other two parameters are\n",
    "the rec1-part and the rec2-part. If the if-part yields false, the\n",
    "rec1-part is executed. Following that the four program parameters and\n",
    "the combinator are again pushed onto the stack bundled up in a quoted\n",
    "form. Then the rec2-part is executed, where it will find the bundled\n",
    "form. Typically it will then execute the bundled form, either with i or\n",
    "with app2, or some other combinator.\"\n",
    "\n",
    "It's a fantastic paper and if you like this you should really go read that.\n",
    "This notebook is much lighter.\n",
    "We're going to look at things from the point-of-view of the [\"Bananas, Lenses, & Barbed Wire\"](http://citeseerx.ist.psu.edu/viewdoc/summary?doi=10.1.1.41.125) paper, all about hylomorphisms, anamorphisms, catamorphisms, etc."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## [Hylomorphism](https://en.wikipedia.org/wiki/Hylomorphism_%28computer_science%29)\n",
    "\n",
    "A [hylomorphism](https://en.wikipedia.org/wiki/Hylomorphism_%28computer_science%29) is a recursive function `H` that converts a value of type `𝔸` into a value of type `ℂ` by means of:\n",
    "\n",
    "- A generator `G` from `𝔸` to `(𝔹, 𝔸)`\n",
    "- A combiner `Q` from `(𝔹, ℂ)` to `ℂ`\n",
    "- A predicate `P` from `𝔸` to `Bool` to detect the base case\n",
    "- A base case value `c` of type `ℂ`, and\n",
    "- Recursive calls (zero or more); it has a \"call stack in the form of a cons list\".\n",
    "\n",
    "It may be helpful to see this function implemented in pseudocode (Python).\n",
    "\n",
    "    def hylomorphism(c, Q, P, G):\n",
    "        '''Return a hylomorphism function H.'''\n",
    "\n",
    "        def H(a):\n",
    "            if P(a):\n",
    "                return c\n",
    "            b, aa = G(a)\n",
    "            return Q(b, H(aa))\n",
    "\n",
    "        return H\n",
    "\n",
    "Note that during evaluation of `H()` the intermediate `b` values are stored in the Python call stack.  This is what is meant by \"call stack in the form of a cons list\"."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Hylomorphism in Joy\n",
    "\n",
    "       a H\n",
    "    ---------\n",
    "        c\n",
    "\n",
    "We can define a combinator `hylomorphism` that will make a hylomorphism combinator `H` from constituent parts. (The reason for the order of the parameters will become clear below):\n",
    "\n",
    "    H == [P] c [G] [Q] hylomorphism\n",
    "\n",
    "The function `H` is recursive, so we start with `ifte` and set the else-part to some function `J` that will contain a quoted copy of `H`.\n",
    "The then-part just discards the leftover `a` and replaces it with the base case value `c`:\n",
    "\n",
    "    H == [P] [pop c] [J] ifte\n",
    "\n",
    "The else-part `J` gets just the argument `a` on the stack.\n",
    "\n",
    "    a J\n",
    "\n",
    "The first thing to do is use the generator `G` which produces values `b` and a new `a′`:\n",
    "\n",
    "        a G\n",
    "    ----------\n",
    "       a′ b\n",
    "\n",
    "So:\n",
    "\n",
    "    J == G J′\n",
    "\n",
    "Then we recur with `H` on `a′`:\n",
    "\n",
    "       a′ b [H] dip\n",
    "    ------------------\n",
    "         a′ H b\n",
    "    ------------------\n",
    "          c′ b\n",
    "\n",
    "So:\n",
    "\n",
    "    J′ == [H] dip J″\n",
    "\n",
    "And run `Q` on the result:\n",
    "\n",
    "       c′ b Q\n",
    "    ------------\n",
    "         c\n",
    "So:\n",
    "\n",
    "    J″ == Q\n",
    "\n",
    "Summing up:\n",
    "\n",
    "    J  == G J′\n",
    "    J′ == [H] dip J″\n",
    "    J″ == Q\n",
    "\n",
    "This gives us a definition for `J`:\n",
    "\n",
    "    J == G [H] dip Q\n",
    "\n",
    "Plug it in and convert to genrec:\n",
    "\n",
    "    H == [P] [pop c] [     J     ] ifte\n",
    "         [P] [pop c] [G [H] dip Q] ifte\n",
    "         [P] [pop c] [G]   [dip Q] genrec\n",
    "\n",
    "This is the form of a hylomorphism in Joy, which nicely illustrates that\n",
    "it is a simple specialization of the general recursion combinator.\n",
    "\n",
    "    [P]      c  [G]     [Q] hylomorphism\n",
    "    [P] [pop c] [G] [dip Q] genrec"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Derivation of `hylomorphism` combinator\n",
    "\n",
    "Now we just need to derive a definition that builds the `genrec` arguments out of the pieces given to the `hylomorphism` combinator.\n",
    "\n",
    "       [P]      c  [G]     [Q] hylomorphism\n",
    "    ------------------------------------------\n",
    "       [P] [pop c] [G] [dip Q] genrec\n",
    "\n",
    "Working in reverse:\n",
    "\n",
    "- Use `swoncat` twice to decouple `[c]` and `[Q]`.\n",
    "- Use `unit` to dequote `c`.\n",
    "- Use `dipd` to untangle `[unit [pop] swoncat]` from the givens.\n",
    "\n",
    "    H == [P] [pop c]              [G]                  [dip Q] genrec\n",
    "         [P] [c]    [pop] swoncat [G]        [Q] [dip] swoncat genrec\n",
    "         [P] c unit [pop] swoncat [G]        [Q] [dip] swoncat genrec\n",
    "         [P] c [G] [Q] [unit [pop] swoncat] dipd [dip] swoncat genrec\n",
    "\n",
    "At this point all of the parameters of the hylomorphism are to the left so we have a definition for `hylomorphism`:\n",
    "\n",
    "    hylomorphism == [unit [pop] swoncat] dipd [dip] swoncat genrec"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": []
    }
   ],
   "source": [
    "[hylomorphism [unit [pop] swoncat] dipd [dip] swoncat genrec] inscribe"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Example: Finding [Triangular Numbers](https://en.wikipedia.org/wiki/Triangular_number)\n",
    "Let's write a function that, given a positive integer, returns the sum of all positive integers less than that one.  (In this case the types `𝔸`, `𝔹` and `ℂ` are all `int`.)\n",
    "\n",
    "To sum a range of integers from 0 to *n* - 1:\n",
    "\n",
    "- `[P]` is `[1 <=]`\n",
    "- `c` is `0`\n",
    "- `[G]` is `[-- dup]`\n",
    "- `[Q]` is `[+]`"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": []
    }
   ],
   "source": [
    "[triangular_number [1 <=] 0 [-- dup] [+] hylomorphism] inscribe"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Let's try it:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "10"
     ]
    }
   ],
   "source": [
    "5 triangular_number"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[0 0 1 3 6 10 15 21]"
     ]
    }
   ],
   "source": [
    "clear\n",
    "\n",
    "[0 1 2 3 4 5 6 7] [triangular_number] map"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Neat!"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "In the Wikipedia entry for [hylomorphism](https://en.wikipedia.org/wiki/Hylomorphism_%28computer_science%29) it says:\n",
    "\n",
    "> a hylomorphism is a recursive function, corresponding to the composition of an [anamorphism](https://en.wikipedia.org/wiki/Anamorphism) (which first builds a set of results; also known as 'unfolding') followed by a [catamorphism](https://en.wikipedia.org/wiki/Catamorphism) (which then folds these results into a final return value).\n",
    "\n",
    "\n",
    "\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Anamorphism\n",
    "An anamorphism can be defined as a hylomorphism that uses `[]` for `c` and\n",
    "`swons` for `Q`.  An anamorphic function builds a list of values.\n",
    "\n",
    "    A == [P] [] [G] [swons] hylomorphism\n",
    "\n",
    "An example of an anamorphism is the `range` function which generates the list of integers from $0$ to $n - 1$ given $n$.\n",
    "\n",
    "    range == [0 <=] [] [-- dup] [swons] hylomorphism"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": []
    }
   ],
   "source": [
    "clear "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": []
    }
   ],
   "source": [
    "[range [0 <=] [] [-- dup] [swons] hylomorphism] inscribe"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {
    "scrolled": false
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "                                                                                     5 • range\n",
      "                                                                                     5 • [0 <=] [] [-- dup] [swons] hylomorphism\n",
      "                                                                              5 [0 <=] • [] [-- dup] [swons] hylomorphism\n",
      "                                                                           5 [0 <=] [] • [-- dup] [swons] hylomorphism\n",
      "                                                                  5 [0 <=] [] [-- dup] • [swons] hylomorphism\n",
      "                                                          5 [0 <=] [] [-- dup] [swons] • hylomorphism\n",
      "                                                          5 [0 <=] [] [-- dup] [swons] • [unit [pop] swoncat] dipd [dip] swoncat genrec\n",
      "                                     5 [0 <=] [] [-- dup] [swons] [unit [pop] swoncat] • dipd [dip] swoncat genrec\n",
      "                                                                           5 [0 <=] [] • unit [pop] swoncat [-- dup] [swons] [dip] swoncat genrec\n",
      "                                                                         5 [0 <=] [[]] • [pop] swoncat [-- dup] [swons] [dip] swoncat genrec\n",
      "                                                                   5 [0 <=] [[]] [pop] • swoncat [-- dup] [swons] [dip] swoncat genrec\n",
      "                                                                   5 [0 <=] [[]] [pop] • swap concat [-- dup] [swons] [dip] swoncat genrec\n",
      "                                                                   5 [0 <=] [pop] [[]] • concat [-- dup] [swons] [dip] swoncat genrec\n",
      "                                                                     5 [0 <=] [pop []] • [-- dup] [swons] [dip] swoncat genrec\n",
      "                                                            5 [0 <=] [pop []] [-- dup] • [swons] [dip] swoncat genrec\n",
      "                                                    5 [0 <=] [pop []] [-- dup] [swons] • [dip] swoncat genrec\n",
      "                                              5 [0 <=] [pop []] [-- dup] [swons] [dip] • swoncat genrec\n",
      "                                              5 [0 <=] [pop []] [-- dup] [swons] [dip] • swap concat genrec\n",
      "                                              5 [0 <=] [pop []] [-- dup] [dip] [swons] • concat genrec\n",
      "                                                5 [0 <=] [pop []] [-- dup] [dip swons] • genrec\n",
      "    5 [0 <=] [pop []] [-- dup [[0 <=] [pop []] [-- dup] [dip swons] genrec] dip swons] • ifte\n",
      "5 [-- dup [[0 <=] [pop []] [-- dup] [dip swons] genrec] dip swons] [pop []] [5] [0 <=] • infra first choice i\n",
      "                                                                                     5 • 0 <= [[pop []] [-- dup [[0 <=] [pop []] [-- dup] [dip swons] genrec] dip swons] 5] swaack first choice i\n",
      "                                                                                   5 0 • <= [[pop []] [-- dup [[0 <=] [pop []] [-- dup] [dip swons] genrec] dip swons] 5] swaack first choice i\n",
      "                                                                                   5 0 • le [[pop []] [-- dup [[0 <=] [pop []] [-- dup] [dip swons] genrec] dip swons] 5] swaack first choice i\n",
      "                                                                                 false • [[pop []] [-- dup [[0 <=] [pop []] [-- dup] [dip swons] genrec] dip swons] 5] swaack first choice i\n",
      "   false [[pop []] [-- dup [[0 <=] [pop []] [-- dup] [dip swons] genrec] dip swons] 5] • swaack first choice i\n",
      "   5 [-- dup [[0 <=] [pop []] [-- dup] [dip swons] genrec] dip swons] [pop []] [false] • first choice i\n",
      "     5 [-- dup [[0 <=] [pop []] [-- dup] [dip swons] genrec] dip swons] [pop []] false • choice i\n",
      "                    5 [-- dup [[0 <=] [pop []] [-- dup] [dip swons] genrec] dip swons] • i\n",
      "                                                                                     5 • -- dup [[0 <=] [pop []] [-- dup] [dip swons] genrec] dip swons\n",
      "                                                                                     5 • 1 - dup [[0 <=] [pop []] [-- dup] [dip swons] genrec] dip swons\n",
      "                                                                                   5 1 • - dup [[0 <=] [pop []] [-- dup] [dip swons] genrec] dip swons\n",
      "                                                                                   5 1 • sub dup [[0 <=] [pop []] [-- dup] [dip swons] genrec] dip swons\n",
      "                                                                                     4 • dup [[0 <=] [pop []] [-- dup] [dip swons] genrec] dip swons\n",
      "                                                                                   4 4 • [[0 <=] [pop []] [-- dup] [dip swons] genrec] dip swons\n",
      "                                     4 4 [[0 <=] [pop []] [-- dup] [dip swons] genrec] • dip swons\n",
      "                                                                                     4 • [0 <=] [pop []] [-- dup] [dip swons] genrec 4 swons\n",
      "                                                                              4 [0 <=] • [pop []] [-- dup] [dip swons] genrec 4 swons\n",
      "                                                                     4 [0 <=] [pop []] • [-- dup] [dip swons] genrec 4 swons\n",
      "                                                            4 [0 <=] [pop []] [-- dup] • [dip swons] genrec 4 swons\n",
      "                                                4 [0 <=] [pop []] [-- dup] [dip swons] • genrec 4 swons\n",
      "    4 [0 <=] [pop []] [-- dup [[0 <=] [pop []] [-- dup] [dip swons] genrec] dip swons] • ifte 4 swons\n",
      "4 [-- dup [[0 <=] [pop []] [-- dup] [dip swons] genrec] dip swons] [pop []] [4] [0 <=] • infra first choice i 4 swons\n",
      "                                                                                     4 • 0 <= [[pop []] [-- dup [[0 <=] [pop []] [-- dup] [dip swons] genrec] dip swons] 4] swaack first choice i 4 swons\n",
      "                                                                                   4 0 • <= [[pop []] [-- dup [[0 <=] [pop []] [-- dup] [dip swons] genrec] dip swons] 4] swaack first choice i 4 swons\n",
      "                                                                                   4 0 • le [[pop []] [-- dup [[0 <=] [pop []] [-- dup] [dip swons] genrec] dip swons] 4] swaack first choice i 4 swons\n",
      "                                                                                 false • [[pop []] [-- dup [[0 <=] [pop []] [-- dup] [dip swons] genrec] dip swons] 4] swaack first choice i 4 swons\n",
      "   false [[pop []] [-- dup [[0 <=] [pop []] [-- dup] [dip swons] genrec] dip swons] 4] • swaack first choice i 4 swons\n",
      "   4 [-- dup [[0 <=] [pop []] [-- dup] [dip swons] genrec] dip swons] [pop []] [false] • first choice i 4 swons\n",
      "     4 [-- dup [[0 <=] [pop []] [-- dup] [dip swons] genrec] dip swons] [pop []] false • choice i 4 swons\n",
      "                    4 [-- dup [[0 <=] [pop []] [-- dup] [dip swons] genrec] dip swons] • i 4 swons\n",
      "                                                                                     4 • -- dup [[0 <=] [pop []] [-- dup] [dip swons] genrec] dip swons 4 swons\n",
      "                                                                                     4 • 1 - dup [[0 <=] [pop []] [-- dup] [dip swons] genrec] dip swons 4 swons\n",
      "                                                                                   4 1 • - dup [[0 <=] [pop []] [-- dup] [dip swons] genrec] dip swons 4 swons\n",
      "                                                                                   4 1 • sub dup [[0 <=] [pop []] [-- dup] [dip swons] genrec] dip swons 4 swons\n",
      "                                                                                     3 • dup [[0 <=] [pop []] [-- dup] [dip swons] genrec] dip swons 4 swons\n",
      "                                                                                   3 3 • [[0 <=] [pop []] [-- dup] [dip swons] genrec] dip swons 4 swons\n",
      "                                     3 3 [[0 <=] [pop []] [-- dup] [dip swons] genrec] • dip swons 4 swons\n",
      "                                                                                     3 • [0 <=] [pop []] [-- dup] [dip swons] genrec 3 swons 4 swons\n",
      "                                                                              3 [0 <=] • [pop []] [-- dup] [dip swons] genrec 3 swons 4 swons\n",
      "                                                                     3 [0 <=] [pop []] • [-- dup] [dip swons] genrec 3 swons 4 swons\n",
      "                                                            3 [0 <=] [pop []] [-- dup] • [dip swons] genrec 3 swons 4 swons\n",
      "                                                3 [0 <=] [pop []] [-- dup] [dip swons] • genrec 3 swons 4 swons\n",
      "    3 [0 <=] [pop []] [-- dup [[0 <=] [pop []] [-- dup] [dip swons] genrec] dip swons] • ifte 3 swons 4 swons\n",
      "3 [-- dup [[0 <=] [pop []] [-- dup] [dip swons] genrec] dip swons] [pop []] [3] [0 <=] • infra first choice i 3 swons 4 swons\n",
      "                                                                                     3 • 0 <= [[pop []] [-- dup [[0 <=] [pop []] [-- dup] [dip swons] genrec] dip swons] 3] swaack first choice i 3 swons 4 swons\n",
      "                                                                                   3 0 • <= [[pop []] [-- dup [[0 <=] [pop []] [-- dup] [dip swons] genrec] dip swons] 3] swaack first choice i 3 swons 4 swons\n",
      "                                                                                   3 0 • le [[pop []] [-- dup [[0 <=] [pop []] [-- dup] [dip swons] genrec] dip swons] 3] swaack first choice i 3 swons 4 swons\n",
      "                                                                                 false • [[pop []] [-- dup [[0 <=] [pop []] [-- dup] [dip swons] genrec] dip swons] 3] swaack first choice i 3 swons 4 swons\n",
      "   false [[pop []] [-- dup [[0 <=] [pop []] [-- dup] [dip swons] genrec] dip swons] 3] • swaack first choice i 3 swons 4 swons\n",
      "   3 [-- dup [[0 <=] [pop []] [-- dup] [dip swons] genrec] dip swons] [pop []] [false] • first choice i 3 swons 4 swons\n",
      "     3 [-- dup [[0 <=] [pop []] [-- dup] [dip swons] genrec] dip swons] [pop []] false • choice i 3 swons 4 swons\n",
      "                    3 [-- dup [[0 <=] [pop []] [-- dup] [dip swons] genrec] dip swons] • i 3 swons 4 swons\n",
      "                                                                                     3 • -- dup [[0 <=] [pop []] [-- dup] [dip swons] genrec] dip swons 3 swons 4 swons\n",
      "                                                                                     3 • 1 - dup [[0 <=] [pop []] [-- dup] [dip swons] genrec] dip swons 3 swons 4 swons\n",
      "                                                                                   3 1 • - dup [[0 <=] [pop []] [-- dup] [dip swons] genrec] dip swons 3 swons 4 swons\n",
      "                                                                                   3 1 • sub dup [[0 <=] [pop []] [-- dup] [dip swons] genrec] dip swons 3 swons 4 swons\n",
      "                                                                                     2 • dup [[0 <=] [pop []] [-- dup] [dip swons] genrec] dip swons 3 swons 4 swons\n",
      "                                                                                   2 2 • [[0 <=] [pop []] [-- dup] [dip swons] genrec] dip swons 3 swons 4 swons\n",
      "                                     2 2 [[0 <=] [pop []] [-- dup] [dip swons] genrec] • dip swons 3 swons 4 swons\n",
      "                                                                                     2 • [0 <=] [pop []] [-- dup] [dip swons] genrec 2 swons 3 swons 4 swons\n",
      "                                                                              2 [0 <=] • [pop []] [-- dup] [dip swons] genrec 2 swons 3 swons 4 swons\n",
      "                                                                     2 [0 <=] [pop []] • [-- dup] [dip swons] genrec 2 swons 3 swons 4 swons\n",
      "                                                            2 [0 <=] [pop []] [-- dup] • [dip swons] genrec 2 swons 3 swons 4 swons\n",
      "                                                2 [0 <=] [pop []] [-- dup] [dip swons] • genrec 2 swons 3 swons 4 swons\n",
      "    2 [0 <=] [pop []] [-- dup [[0 <=] [pop []] [-- dup] [dip swons] genrec] dip swons] • ifte 2 swons 3 swons 4 swons\n",
      "2 [-- dup [[0 <=] [pop []] [-- dup] [dip swons] genrec] dip swons] [pop []] [2] [0 <=] • infra first choice i 2 swons 3 swons 4 swons\n",
      "                                                                                     2 • 0 <= [[pop []] [-- dup [[0 <=] [pop []] [-- dup] [dip swons] genrec] dip swons] 2] swaack first choice i 2 swons 3 swons 4 swons\n",
      "                                                                                   2 0 • <= [[pop []] [-- dup [[0 <=] [pop []] [-- dup] [dip swons] genrec] dip swons] 2] swaack first choice i 2 swons 3 swons 4 swons\n",
      "                                                                                   2 0 • le [[pop []] [-- dup [[0 <=] [pop []] [-- dup] [dip swons] genrec] dip swons] 2] swaack first choice i 2 swons 3 swons 4 swons\n",
      "                                                                                 false • [[pop []] [-- dup [[0 <=] [pop []] [-- dup] [dip swons] genrec] dip swons] 2] swaack first choice i 2 swons 3 swons 4 swons\n",
      "   false [[pop []] [-- dup [[0 <=] [pop []] [-- dup] [dip swons] genrec] dip swons] 2] • swaack first choice i 2 swons 3 swons 4 swons\n",
      "   2 [-- dup [[0 <=] [pop []] [-- dup] [dip swons] genrec] dip swons] [pop []] [false] • first choice i 2 swons 3 swons 4 swons\n",
      "     2 [-- dup [[0 <=] [pop []] [-- dup] [dip swons] genrec] dip swons] [pop []] false • choice i 2 swons 3 swons 4 swons\n",
      "                    2 [-- dup [[0 <=] [pop []] [-- dup] [dip swons] genrec] dip swons] • i 2 swons 3 swons 4 swons\n",
      "                                                                                     2 • -- dup [[0 <=] [pop []] [-- dup] [dip swons] genrec] dip swons 2 swons 3 swons 4 swons\n",
      "                                                                                     2 • 1 - dup [[0 <=] [pop []] [-- dup] [dip swons] genrec] dip swons 2 swons 3 swons 4 swons\n",
      "                                                                                   2 1 • - dup [[0 <=] [pop []] [-- dup] [dip swons] genrec] dip swons 2 swons 3 swons 4 swons\n",
      "                                                                                   2 1 • sub dup [[0 <=] [pop []] [-- dup] [dip swons] genrec] dip swons 2 swons 3 swons 4 swons\n",
      "                                                                                     1 • dup [[0 <=] [pop []] [-- dup] [dip swons] genrec] dip swons 2 swons 3 swons 4 swons\n",
      "                                                                                   1 1 • [[0 <=] [pop []] [-- dup] [dip swons] genrec] dip swons 2 swons 3 swons 4 swons\n",
      "                                     1 1 [[0 <=] [pop []] [-- dup] [dip swons] genrec] • dip swons 2 swons 3 swons 4 swons\n",
      "                                                                                     1 • [0 <=] [pop []] [-- dup] [dip swons] genrec 1 swons 2 swons 3 swons 4 swons\n",
      "                                                                              1 [0 <=] • [pop []] [-- dup] [dip swons] genrec 1 swons 2 swons 3 swons 4 swons\n",
      "                                                                     1 [0 <=] [pop []] • [-- dup] [dip swons] genrec 1 swons 2 swons 3 swons 4 swons\n",
      "                                                            1 [0 <=] [pop []] [-- dup] • [dip swons] genrec 1 swons 2 swons 3 swons 4 swons\n",
      "                                                1 [0 <=] [pop []] [-- dup] [dip swons] • genrec 1 swons 2 swons 3 swons 4 swons\n",
      "    1 [0 <=] [pop []] [-- dup [[0 <=] [pop []] [-- dup] [dip swons] genrec] dip swons] • ifte 1 swons 2 swons 3 swons 4 swons\n",
      "1 [-- dup [[0 <=] [pop []] [-- dup] [dip swons] genrec] dip swons] [pop []] [1] [0 <=] • infra first choice i 1 swons 2 swons 3 swons 4 swons\n",
      "                                                                                     1 • 0 <= [[pop []] [-- dup [[0 <=] [pop []] [-- dup] [dip swons] genrec] dip swons] 1] swaack first choice i 1 swons 2 swons 3 swons 4 swons\n",
      "                                                                                   1 0 • <= [[pop []] [-- dup [[0 <=] [pop []] [-- dup] [dip swons] genrec] dip swons] 1] swaack first choice i 1 swons 2 swons 3 swons 4 swons\n",
      "                                                                                   1 0 • le [[pop []] [-- dup [[0 <=] [pop []] [-- dup] [dip swons] genrec] dip swons] 1] swaack first choice i 1 swons 2 swons 3 swons 4 swons\n",
      "                                                                                 false • [[pop []] [-- dup [[0 <=] [pop []] [-- dup] [dip swons] genrec] dip swons] 1] swaack first choice i 1 swons 2 swons 3 swons 4 swons\n",
      "   false [[pop []] [-- dup [[0 <=] [pop []] [-- dup] [dip swons] genrec] dip swons] 1] • swaack first choice i 1 swons 2 swons 3 swons 4 swons\n",
      "   1 [-- dup [[0 <=] [pop []] [-- dup] [dip swons] genrec] dip swons] [pop []] [false] • first choice i 1 swons 2 swons 3 swons 4 swons\n",
      "     1 [-- dup [[0 <=] [pop []] [-- dup] [dip swons] genrec] dip swons] [pop []] false • choice i 1 swons 2 swons 3 swons 4 swons\n",
      "                    1 [-- dup [[0 <=] [pop []] [-- dup] [dip swons] genrec] dip swons] • i 1 swons 2 swons 3 swons 4 swons\n",
      "                                                                                     1 • -- dup [[0 <=] [pop []] [-- dup] [dip swons] genrec] dip swons 1 swons 2 swons 3 swons 4 swons\n",
      "                                                                                     1 • 1 - dup [[0 <=] [pop []] [-- dup] [dip swons] genrec] dip swons 1 swons 2 swons 3 swons 4 swons\n",
      "                                                                                   1 1 • - dup [[0 <=] [pop []] [-- dup] [dip swons] genrec] dip swons 1 swons 2 swons 3 swons 4 swons\n",
      "                                                                                   1 1 • sub dup [[0 <=] [pop []] [-- dup] [dip swons] genrec] dip swons 1 swons 2 swons 3 swons 4 swons\n",
      "                                                                                     0 • dup [[0 <=] [pop []] [-- dup] [dip swons] genrec] dip swons 1 swons 2 swons 3 swons 4 swons\n",
      "                                                                                   0 0 • [[0 <=] [pop []] [-- dup] [dip swons] genrec] dip swons 1 swons 2 swons 3 swons 4 swons\n",
      "                                     0 0 [[0 <=] [pop []] [-- dup] [dip swons] genrec] • dip swons 1 swons 2 swons 3 swons 4 swons\n",
      "                                                                                     0 • [0 <=] [pop []] [-- dup] [dip swons] genrec 0 swons 1 swons 2 swons 3 swons 4 swons\n",
      "                                                                              0 [0 <=] • [pop []] [-- dup] [dip swons] genrec 0 swons 1 swons 2 swons 3 swons 4 swons\n",
      "                                                                     0 [0 <=] [pop []] • [-- dup] [dip swons] genrec 0 swons 1 swons 2 swons 3 swons 4 swons\n",
      "                                                            0 [0 <=] [pop []] [-- dup] • [dip swons] genrec 0 swons 1 swons 2 swons 3 swons 4 swons\n",
      "                                                0 [0 <=] [pop []] [-- dup] [dip swons] • genrec 0 swons 1 swons 2 swons 3 swons 4 swons\n",
      "    0 [0 <=] [pop []] [-- dup [[0 <=] [pop []] [-- dup] [dip swons] genrec] dip swons] • ifte 0 swons 1 swons 2 swons 3 swons 4 swons\n",
      "0 [-- dup [[0 <=] [pop []] [-- dup] [dip swons] genrec] dip swons] [pop []] [0] [0 <=] • infra first choice i 0 swons 1 swons 2 swons 3 swons 4 swons\n",
      "                                                                                     0 • 0 <= [[pop []] [-- dup [[0 <=] [pop []] [-- dup] [dip swons] genrec] dip swons] 0] swaack first choice i 0 swons 1 swons 2 swons 3 swons 4 swons\n",
      "                                                                                   0 0 • <= [[pop []] [-- dup [[0 <=] [pop []] [-- dup] [dip swons] genrec] dip swons] 0] swaack first choice i 0 swons 1 swons 2 swons 3 swons 4 swons\n",
      "                                                                                   0 0 • le [[pop []] [-- dup [[0 <=] [pop []] [-- dup] [dip swons] genrec] dip swons] 0] swaack first choice i 0 swons 1 swons 2 swons 3 swons 4 swons\n",
      "                                                                                  true • [[pop []] [-- dup [[0 <=] [pop []] [-- dup] [dip swons] genrec] dip swons] 0] swaack first choice i 0 swons 1 swons 2 swons 3 swons 4 swons\n",
      "    true [[pop []] [-- dup [[0 <=] [pop []] [-- dup] [dip swons] genrec] dip swons] 0] • swaack first choice i 0 swons 1 swons 2 swons 3 swons 4 swons\n",
      "    0 [-- dup [[0 <=] [pop []] [-- dup] [dip swons] genrec] dip swons] [pop []] [true] • first choice i 0 swons 1 swons 2 swons 3 swons 4 swons\n",
      "      0 [-- dup [[0 <=] [pop []] [-- dup] [dip swons] genrec] dip swons] [pop []] true • choice i 0 swons 1 swons 2 swons 3 swons 4 swons\n",
      "                                                                            0 [pop []] • i 0 swons 1 swons 2 swons 3 swons 4 swons\n",
      "                                                                                     0 • pop [] 0 swons 1 swons 2 swons 3 swons 4 swons\n",
      "                                                                                       • [] 0 swons 1 swons 2 swons 3 swons 4 swons\n",
      "                                                                                    [] • 0 swons 1 swons 2 swons 3 swons 4 swons\n",
      "                                                                                  [] 0 • swons 1 swons 2 swons 3 swons 4 swons\n",
      "                                                                                   [0] • 1 swons 2 swons 3 swons 4 swons\n",
      "                                                                                 [0] 1 • swons 2 swons 3 swons 4 swons\n",
      "                                                                                 [1 0] • 2 swons 3 swons 4 swons\n",
      "                                                                               [1 0] 2 • swons 3 swons 4 swons\n",
      "                                                                               [2 1 0] • 3 swons 4 swons\n",
      "                                                                             [2 1 0] 3 • swons 4 swons\n",
      "                                                                             [3 2 1 0] • 4 swons\n",
      "                                                                           [3 2 1 0] 4 • swons\n",
      "                                                                           [4 3 2 1 0] • \n",
      "\n",
      "[4 3 2 1 0]"
     ]
    }
   ],
   "source": [
    "5 range"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Catamorphism\n",
    "A catamorphic function tears down a list term-by-term and makes some new value.\n",
    "It can be defined as a hylomorphism that uses `[uncons swap]` for `[G]`\n",
    "and `[[] =]` (or just `[not]`) for the predicate `[P]`.\n",
    "\n",
    "    C == [not] c [uncons swap] [Q] hylomorphism\n",
    "\n",
    "An example of a catamorphism is the sum function.\n",
    "\n",
    "    sum == [not] 0 [uncons swap] [+] hylomorphism"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": []
    }
   ],
   "source": [
    "clear "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": []
    }
   ],
   "source": [
    "[sum [not] 0 [uncons swap] [+] hylomorphism] inscribe"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "15"
     ]
    }
   ],
   "source": [
    "[5 4 3 2 1] sum"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": []
    }
   ],
   "source": [
    "clear "
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The [\"Bananas, Lenses, & Barbed Wire\"](http://citeseerx.ist.psu.edu/viewdoc/summary?doi=10.1.1.41.125) paper mentions the\n",
    "\n",
    "### \"Fusion Law\" for catamorphisms\n",
    "\n",
    "    f . (| b, (+) |) = (| c, (x) |)  <==  f b = c /\\ f( a (+) as ) = a (x) (f as)\n",
    "\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The [\"Bananas, Lenses, & Barbed Wire\"](http://citeseerx.ist.psu.edu/viewdoc/summary?doi=10.1.1.41.125) paper mentions the\n",
    "\n",
    "### \"Fusion Law\" for catamorphisms\n",
    "\n",
    "    f ∘ ⦇b,⨁⦈ = ⦇c,⨂⦈  ⇐  f b = c ∧ f(a ⨁ as) = a ⨂ (f as)\n",
    "\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "    b [⨁] catamorphism f == c [⨂] catamorphism\n",
    "    \n",
    "    f == 10 *\n",
    "    \n",
    "    0 [+] catamorphism f\n",
    "    \n",
    "    0 f == 0\n",
    "    \n",
    "    as a + f  ==  as f a ⨂\n",
    "    \n",
    "    ⨂ = f +\n",
    "    \n",
    "    0 [+] catamorphism f  = 0 [f +] catamorphism\n",
    "    "
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "⨁ ⨂ ∘ ∧ ⦇ ⦈ ⇐"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### The `step` combinator\n",
    "The `step` combinator will often be easier to use than `catamorphism`."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 21,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\n",
      "==== Help on step ====\n",
      "\n",
      "Run a quoted program on each item in a sequence.\n",
      "::\n",
      "\n",
      "       ... [] [Q] . step\n",
      "    -----------------------\n",
      "          ... .\n",
      "\n",
      "\n",
      "       ... [a] [Q] . step\n",
      "    ------------------------\n",
      "         ... a . Q\n",
      "\n",
      "\n",
      "       ... [a b c] [Q] . step\n",
      "    ----------------------------------------\n",
      "             ... a . Q [b c] [Q] step\n",
      "\n",
      "The step combinator executes the quotation on each member of the list\n",
      "on top of the stack.\n",
      "\n",
      "---- end (step)\n",
      "\n",
      "\n"
     ]
    }
   ],
   "source": [
    "[step] help"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 22,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": []
    }
   ],
   "source": [
    "[sum 0 swap [+] step] inscribe"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 23,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "15"
     ]
    }
   ],
   "source": [
    "[5 4 3 2 1] sum"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Hylo- is Ana- then Cata-\n",
    "\n",
    "    anamorphism == [] swap [swons] hylomorphism\n",
    "    \n",
    "    catamorphism == [[not] swap [uncons swap]] dip hylomorphism\n",
    "\n",
    "A hylomorphism can be thought of as the composition of an anamorphism and a catamorphism:\n",
    "\n",
    "    [P] [G] anamorphism c [Q] catamorphism == [P] c [G] [Q] hylomorphism\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "For example, `triangular_number` could be defined as the composition of the `range` and `sum` functions:\n",
    "\n",
    "    triangular_number == range sum"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 15,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[0 0 1 3 6 10 15 21]"
     ]
    }
   ],
   "source": [
    "clear\n",
    "\n",
    "[0 1 2 3 4 5 6 7] [range sum] map"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "However, this creates (and destroys) an intermediate list, which is a waste."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Variations\n",
    "\n",
    "Let's review the operation of the hylomorphism:\n",
    "\n",
    "    [P] c [G] [Q] H₁ == [P] [pop c] [G] [dip Q] genrec\n",
    "\n",
    "    ... a G [H₁] dip Q\n",
    "    ... a′ b [H₁] dip Q\n",
    "    ... a′ H₁ b Q\n",
    "       <predicate omitted>\n",
    "    ... a′ G [H₁] dip Q b Q\n",
    "    ... a″ b′ [H₁] dip Q b Q\n",
    "    ... a″ H₁ b′ Q b Q\n",
    "       <predicate omitted>\n",
    "    ... a″ G [H₁] dip Q b′ Q b Q\n",
    "    ... a‴ b″ [H₁] dip Q b′ Q b Q\n",
    "    ... a‴ H₁ b″ Q b′ Q b Q\n",
    "       <predicate omitted>\n",
    "    ... a‴ pop c b″ Q b′ Q b Q\n",
    "    ... c b″ Q b′ Q b Q\n",
    "    ... c′ b′ Q b Q\n",
    "    ... c″ b Q\n",
    "    ... c‴\n",
    "\n",
    "Notice that `b` values and the `Q` combiner function get pushed into the pending expression (\"continuation\")."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### A tail-recursive version\n",
    "\n",
    "Now let's try a version that doesn't do that. When you can start with the identity value `c` on the stack and the combiner `Q` can operate as you go using the intermediate results immediately rather than queuing them up, we can do this:\n",
    "\n",
    "    [P] c [G] [Q] H₂ == c [pop P] [popd] [[G] dip Q] tailrec\n",
    "\n",
    "An important difference is that the combiner function `Q` must accept its arguments in the reverse order and take into account the presence of the `a` value:\n",
    "\n",
    "    ... a c [G] dip Q H₂\n",
    "    ... a G c Q H₂\n",
    "    ... a′ b c Q H₂\n",
    "    ... a′ c′ H₂\n",
    "       <predicate omitted>\n",
    "    ... a′ c′ [G] dip Q H₂\n",
    "    ... a′ G c′ Q H₂\n",
    "    ... a″ b c′ Q H₂\n",
    "    ... a″ c″ H₂\n",
    "       <predicate omitted>\n",
    "    ... a″ c″ [G] dip Q H₂\n",
    "    ... a″ G c″ Q H₂\n",
    "    ... a‴ b c″ Q H₂\n",
    "    ... a‴ c‴ H₂\n",
    "       <predicate omitted>\n",
    "    ... a‴ c‴ popd\n",
    "    ... c‴"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Note that the `c` values are processed by the `Q` combiner function in reverse order as compared to the original version.\n",
    "\n",
    "#### `range` with `H₂`\n",
    "\n",
    "For example, if we reimplement the `range` function in the tail-recursive style it generates the list with $0$ at the head rather than $n - 1$:\n",
    "\n",
    "    range_reverse == [] [pop 0 <=] [popd] [[-- dup] dip cons] tailrec\n",
    "       "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": []
    }
   ],
   "source": [
    "clear "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": []
    }
   ],
   "source": [
    "[range_reverse [] [pop 0 <=] [popd] [[-- dup] dip cons] tailrec] inscribe"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {
    "scrolled": true
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[4 3 2 1 0] [0 1 2 3 4]"
     ]
    }
   ],
   "source": [
    "5 [range] [range_reverse] cleave"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Instead of making `Q` take account of the `c` value we could do this:\n",
    "\n",
    "    ... a′ b c [Q] ccons dip swap H₂\n",
    "    ... a′ [b c Q] dip swap H₂\n",
    "    ... b c Q a′ swap H₂\n",
    "    ... c′ a′ swap H₂\n",
    "    ... a′ c′ H₂\n",
    "\n",
    "This shows that any function `Q` can be converted to `[Q] ccons dip swap` to deal with that `a` value on the stack."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### the old version\n",
    "\n",
    "Now let's try a version that doesn't do that. When you can start with the identity value `c` on the stack and the combiner `Q` can operate as you go using the intermediate results immediately rather than queuing them up, we can do this:\n",
    "\n",
    "    [P] c [G] [Q] H₂ == c swap [P] [pop] [G [Q] dip] tailrec\n",
    "\n",
    "An important difference is that the generator function must return its results in the reverse order, and both `Q` and `G` have to take into account the presence of the `c` value:\n",
    "\n",
    "    ... c a G [Q] dip H₂\n",
    "    ... c b a′ [Q] dip H₂\n",
    "    ... c b Q a′ H₂\n",
    "    ... c′ a′ H₂\n",
    "       <predicate omitted>\n",
    "    ... c′ a′ G [Q] dip H₂\n",
    "    ... c′ b′ a″ [Q] dip H₂\n",
    "    ... c′ b′ Q a″ H₂\n",
    "    ... c″ a″ H₂\n",
    "       <predicate omitted>\n",
    "    ... c″ a″ G [Q] dip H₂\n",
    "    ... c″ b″ a‴ [Q] dip H₂\n",
    "    ... c″ b″ Q a‴ H₂\n",
    "    ... c‴ a‴ H₂\n",
    "       <predicate omitted>\n",
    "    ... c‴ a‴ pop\n",
    "    ... c‴\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Four Specializations\n",
    "There are (at least) four kinds of recursive combinator, depending on two choices.  The first choice is whether the combiner function `Q` should be evaluated during the recursion or pushed into the pending expression to be \"collapsed\" at the end.  The second choice is whether the combiner needs to operate on the current value of the datastructure or the generator's output, in other words, whether `Q` or `G` should run first in the recursive branch.\n",
    "\n",
    "    H1 ==        [P] [pop c] [G             ] [dip Q] genrec\n",
    "    H2 == c swap [P] [pop]   [G [Q]    dip  ] [i]     genrec\n",
    "    H3 ==        [P] [pop c] [  [G] dupdip  ] [dip Q] genrec\n",
    "    H4 == c swap [P] [pop]   [  [Q] dupdip G] [i]     genrec\n",
    "\n",
    "The working of the generator function `G` differs slightly for each.  Consider the recursive branches:\n",
    "\n",
    "    ... a G [H1] dip Q                w/ a G == a′ b\n",
    "    \n",
    "    ... c a G [Q] dip H2                 a G == b  a′\n",
    "    \n",
    "    ... a [G] dupdip [H3] dip Q          a G == a′\n",
    "    \n",
    "    ... c a [Q] dupdip G H4              a G == a′\n",
    "\n",
    "The following four sections illustrate how these work, omitting the predicate evaluation."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### `H1`\n",
    "\n",
    "This form builds up a pending expression (continuation) that contains the intermediate results along with the pending combiner functions.  When the base case is reached the last term is replaced by the identity value `c` and the continuation \"collapses\" into the final result using the combiner `Q`.\n",
    "\n",
    "    H1 == [P] [pop c] [G] [dip Q] genrec\n",
    "\n",
    "    ... a G [H1] dip Q\n",
    "    ... a′ b [H1] dip Q\n",
    "    ... a′ H1 b Q\n",
    "       <predicate omitted>\n",
    "    ... a′ G [H1] dip Q b Q\n",
    "    ... a″ b′ [H1] dip Q b Q\n",
    "    ... a″ H1 b′ Q b Q\n",
    "       <predicate omitted>\n",
    "    ... a″ G [H1] dip Q b′ Q b Q\n",
    "    ... a‴ b″ [H1] dip Q b′ Q b Q\n",
    "    ... a‴ H1 b″ Q b′ Q b Q\n",
    "       <predicate omitted>\n",
    "    ... a‴ pop c b″ Q b′ Q b Q\n",
    "    ... c b″ Q b′ Q b Q\n",
    "    ... c′ b′ Q b Q\n",
    "    ... c″ b Q\n",
    "    ... c‴"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### `H2`\n",
    "\n",
    "When you can start with the identity value `c` on the stack and the combiner `Q` can operate as you go using the intermediate results immediately rather than queuing them up, use this form.\n",
    "An important difference is that the generator function must return its results in the reverse order,\n",
    "and both `Q` and `G` have to take into account the presence of the `c` value:\n",
    "\n",
    "    H2 == c swap [P] [pop] [G [Q] dip] tailrec\n",
    "\n",
    "    ... c a G [Q] dip H2\n",
    "    ... c b a′ [Q] dip H2\n",
    "    ... c b Q a′ H2\n",
    "    ... c′ a′ H2\n",
    "       <predicate omitted>\n",
    "    ... c′ a′ G [Q] dip H2\n",
    "    ... c′ b′ a″ [Q] dip H2\n",
    "    ... c′ b′ Q a″ H2\n",
    "    ... c″ a″ H2\n",
    "       <predicate omitted>\n",
    "    ... c″ a″ G [Q] dip H2\n",
    "    ... c″ b″ a‴ [Q] dip H2\n",
    "    ... c″ b″ Q a‴ H2\n",
    "    ... c‴ a‴ H2\n",
    "       <predicate omitted>\n",
    "    ... c‴ a‴ pop\n",
    "    ... c‴\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### `H3`\n",
    "\n",
    "If you examine the traces above you'll see that the combiner `Q` only gets to operate on the results of `G`, it never \"sees\" the first value `a`.  If the combiner and the generator both need to work on the current value then `dup` must be used, and the generator must produce one item instead of two (the b is instead the duplicate of a.)\n",
    "\n",
    "\n",
    "    H3 == [P] [pop c] [[G] dupdip] [dip Q] genrec\n",
    "\n",
    "    ... a [G] dupdip [H3] dip Q\n",
    "    ... a G a [H3] dip Q\n",
    "    ... a′ a [H3] dip Q\n",
    "    ... a′ H3 a Q\n",
    "       <predicate omitted>\n",
    "    ... a′ [G] dupdip [H3] dip Q a Q\n",
    "    ... a′ G a′ [H3] dip Q a Q\n",
    "    ... a″ a′ [H3] dip Q a Q\n",
    "    ... a″ H3 a′ Q a Q\n",
    "       <predicate omitted>\n",
    "    ... a″ [G] dupdip [H3] dip Q a′ Q a Q\n",
    "    ... a″ G a″ [H3] dip Q a′ Q a Q\n",
    "    ... a‴ a″ [H3] dip Q a′ Q a Q\n",
    "    ... a‴ H3 a″ Q a′ Q a Q\n",
    "       <predicate omitted>\n",
    "    ... a‴ pop c a″ Q a′ Q a Q\n",
    "    ... c a″ Q a′ Q a Q\n",
    "    ... c′ a′ Q a Q\n",
    "    ... c‴ a Q\n",
    "    ... c‴"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### `H4`\n",
    "\n",
    "And, last but not least, if you can combine as you go, starting with `c`, and the combiner `Q` needs to work on the current item, this is the form:\n",
    "\n",
    "    H4 == c swap [P] [pop] [[Q] dupdip G] primrec\n",
    "\n",
    "    ... c a [Q] dupdip G H4\n",
    "    ... c a Q a G H4\n",
    "    ... c′ a G H4\n",
    "    ... c′ a′ H4\n",
    "       <predicate omitted>\n",
    "    ... c′ a′ [Q] dupdip G H4\n",
    "    ... c′ a′ Q a′ G H4\n",
    "    ... c‴ a′ G H4\n",
    "    ... c‴ a″ H4\n",
    "       <predicate omitted>\n",
    "    ... c‴ a″ [Q] dupdip G H4\n",
    "    ... c‴ a″ Q a″ G H4\n",
    "    ... c‴ a″ G H4\n",
    "    ... c‴ a‴ H4\n",
    "       <predicate omitted>\n",
    "    ... c‴ a‴ pop\n",
    "    ... c‴"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### `range` et. al.\n",
    "\n",
    "An example of an anamorphism is the `range` function which generates the list of integers from 0 to *n* - 1 given *n*.\n",
    "\n",
    "Each of the above variations can be used to make four slightly different `range` functions."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### `range` with `H1`\n",
    "    H1 == [P]    [pop c]  [G]      [dip Q]     genrec\n",
    "       == [0 <=] [pop []] [-- dup] [dip swons] genrec"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": []
    }
   ],
   "source": [
    "clear "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": []
    }
   ],
   "source": [
    "[range [0 <=] [] [-- dup] [swons] hylomorphism] inscribe"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {
    "scrolled": false
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[4 3 2 1 0]"
     ]
    }
   ],
   "source": [
    "5 range"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### `range` with `H2`\n",
    "    H2 == c  swap [P]    [pop] [G      [Q]     dip] tailrec\n",
    "       == [] swap [0 <=] [pop] [-- dup [swons] dip] tailrec"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": []
    }
   ],
   "source": [
    "clear "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": []
    }
   ],
   "source": [
    "[range_reverse [] swap [0 <=] [pop] [-- dup [swons] dip] tailrec] inscribe"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "metadata": {
    "scrolled": true
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[0 1 2 3 4]"
     ]
    }
   ],
   "source": [
    "5 range_reverse"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### `range` with `H3`\n",
    "    H3 == [P]    [pop c]  [[G]  dupdip] [dip Q]     genrec\n",
    "       == [0 <=] [pop []] [[--] dupdip] [dip swons] genrec"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": []
    }
   ],
   "source": [
    "clear "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": []
    }
   ],
   "source": [
    "[ranger [0 <=] [pop []] [[--] dupdip] [dip swons] genrec] inscribe"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "metadata": {
    "scrolled": true
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[5 4 3 2 1]"
     ]
    }
   ],
   "source": [
    "5 ranger"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### `range` with `H4`\n",
    "    H4 == c  swap [P]    [pop] [[Q]     dupdip G ] primrec\n",
    "       == [] swap [0 <=] [pop] [[swons] dupdip --] primrec"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 14,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": []
    }
   ],
   "source": [
    "clear "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 15,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": []
    }
   ],
   "source": [
    "[ranger_reverse [] swap [0 <=] [pop] [[swons] dupdip --] tailrec] inscribe"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 16,
   "metadata": {
    "scrolled": true
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[1 2 3 4 5]"
     ]
    }
   ],
   "source": [
    "5 ranger_reverse"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Example: Factorial Function\n",
    "\n",
    "For the Factorial function:\n",
    "\n",
    "    H4 == c swap [P] [pop] [[Q] dupdip G] tailrec\n",
    "\n",
    "With:\n",
    "\n",
    "    c == 1\n",
    "    Q == *\n",
    "    G == --\n",
    "    P == 1 <="
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 24,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": []
    }
   ],
   "source": [
    "clear"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 25,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": []
    }
   ],
   "source": [
    "[factorial 1 swap [1 <=] [pop] [[*] dupdip --] tailrec] inscribe"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 26,
   "metadata": {
    "scrolled": false
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "120"
     ]
    }
   ],
   "source": [
    "5 factorial"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Example: Filter Function\n",
    "\n",
    "An often-used function is `filter` which takes a list and a predicate and makes a new list with only those items from the input list that make the predicate true:\n",
    "\n",
    "       [...] [P] filter\n",
    "    ----------------------\n",
    "            [...]′\n",
    "\n",
    "Let's start by making a simpler function that just recreates the input list:\n",
    "\n",
    "    F == [not] [] [J] ifte\n",
    "\n",
    "To figure out the recursive branch `J` we start by setting a dummy list in front of it.\n",
    "\n",
    "    [a b c] J\n",
    "    [a b c] uncons swap J′\n",
    "    a [b c]        swap J′\n",
    "    [b c] a             J′\n",
    "\n",
    "    J == uncons swap J′\n",
    "\n",
    "We don't have the output list to which to `cons` that `a` so we recur instead and *then* `cons` (more precisely `swons`) it:\n",
    "\n",
    "    J′ == [Q] dip swons\n",
    "\n",
    "    [b c] a [Q] dip swons\n",
    "    [b c] Q a swons\n",
    "    ...\n",
    "    [c] Q b swons a swons\n",
    "    ...\n",
    "    [] c swons b swons a swons\n",
    "    ...\n",
    "    [a b c]\n",
    "\n",
    "So:\n",
    "\n",
    "    J == uncons swap [Q] dip swons\n",
    "\n",
    "And:\n",
    "\n",
    "    F == [not] [] [uncons swap [F] dip swons] ifte\n",
    "         [not] [] [uncons swap]   [dip swons] genrec\n",
    "\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 27,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": []
    }
   ],
   "source": [
    "clear"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 28,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[1 2 3]"
     ]
    }
   ],
   "source": [
    "[1 2 3] [not] [] [uncons swap] [dip swons] genrec"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "scrolled": false
   },
   "source": [
    "It would seem that all we need to do now is turn the `swons` into an expression that applies the input `P` predicate to the items and only puts them on the output list if they pass.\n",
    "\n",
    "    filter == [not] [] [uncons swap] [dip W] genrec\n",
    "\n",
    "Resulting in, e.g.:\n",
    "\n",
    "    [] c W b W a W\n",
    "\n",
    "However, the input list will be on the stack just below the item, so `W` has to take account of that.  If our predicate function doesn't use any values from below the item under consideration then we're okay, but if it does then we have to deal with the input list somehow.\n",
    "\n",
    "We know `W` would be something like:\n",
    "\n",
    "    W == [...[P]...] [swons] [pop] ifte\n",
    "\n",
    "Let's examine the situation:\n",
    "\n",
    "    ... [...] item [...[P]...] [swons] [pop] ifte\n",
    "\n",
    "Since the predicate of the `ifte` combinator is applied `nullary` we can just `pop` the output list:\n",
    "\n",
    "    ... [...] item popd P\n",
    "\n",
    "And since `[P]` is already a quote:\n",
    "\n",
    "    W == [popd P] [swons] [pop] ifte\n",
    "\n",
    "Ergo:\n",
    "\n",
    "    [P] filter == [not] [] [uncons swap] [dip [popd P] [swons] [pop] ifte] genrec\n",
    "\n",
    "Getting that `P` into position is straightforward.  Working in reverse:\n",
    "\n",
    "    [not] [] [uncons swap] [dip [popd P] [swons] [pop] ifte] genrec\n",
    "\n",
    "Undip the first three terms:\n",
    "\n",
    "    [dip [popd P] [swons] [pop] ifte] [[not] [] [uncons swap]] dip genrec\n",
    "                                      ^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n",
    "\n",
    "Take off the `[dip]` prefix:\n",
    "\n",
    "    [[popd P] [swons] [pop] ifte] [dip] swoncat [[not] [] [uncons swap]] dip genrec\n",
    "                                  ^^^^^^^^^^^^^\n",
    "\n",
    "Uncons the term containing `P`:\n",
    "\n",
    "    [popd P] [[swons] [pop] ifte] cons [dip] swoncat [[not] [] [uncons swap]] dip genrec\n",
    "    ^^^^^^^^                      ^^^^\n",
    "\n",
    "And then take off the `[popd]` prefix:\n",
    "\n",
    "    [P] [popd] swoncat [[swons] [pop] ifte] cons [dip] swoncat [[not] [] [uncons swap]] dip genrec\n",
    "        ^^^^^^^^^^^^^^\n",
    "\n",
    "And so:\n",
    "\n",
    "    filter == [popd] swoncat [[swons] [pop] ifte] cons [dip] swoncat [[not] [] [uncons swap]] dip genrec\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 29,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": []
    }
   ],
   "source": [
    "clear"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 30,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": []
    }
   ],
   "source": [
    "[filter [popd] swoncat [[swons] [pop] ifte] cons [dip] swoncat [[not] [] [uncons swap]] dip genrec] inscribe"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 31,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[1 2 3 4 5 6 7 8] [2 mod not]"
     ]
    }
   ],
   "source": [
    "[1 2 3 4 5 6 7 8] [2 mod not]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 32,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[2 4 6 8]"
     ]
    }
   ],
   "source": [
    "filter"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "scrolled": false
   },
   "source": [
    "This isn't completely satisfying.  For one thing, it would be nice to apply the predicate as we go so we are not putting items (and `W`) onto the expression for items that will fail the predicate `P`."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Example: `tails`\n",
    "An example of a paramorphism for lists given in the [\"Bananas...\" paper](http://citeseerx.ist.psu.edu/viewdoc/summary?doi=10.1.1.41.125) is `tails` which returns the list of \"tails\" of a list.\n",
    "\n",
    "        [1 2 3] tails\n",
    "    --------------------\n",
    "       [[] [3] [2 3]]\n",
    "    \n",
    "\n",
    "We can build as we go, and we want `Q` to run after `G`, so we use pattern `H2`:\n",
    "\n",
    "    H2 == c swap [P] [pop] [G [Q] dip] tailrec\n",
    "\n",
    "We would use:\n",
    "\n",
    "    c == []\n",
    "    Q == swons\n",
    "    G == rest dup\n",
    "    P == not"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 33,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": []
    }
   ],
   "source": [
    "clear"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 34,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": []
    }
   ],
   "source": [
    "[tails [] swap [not] [pop] [rest dup [swons] dip] tailrec] inscribe"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 35,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[[] [3] [2 3]]"
     ]
    }
   ],
   "source": [
    "[1 2 3] tails"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Conclusion: Patterns of Recursion\n",
    "Our story so far...\n",
    "\n",
    "\n",
    "### Hylo-, Ana-, Cata-\n",
    "\n",
    "    H == [P  ] [pop c ] [G          ] [dip Q        ] genrec\n",
    "    A == [P  ] [pop []] [G          ] [dip swap cons] genrec\n",
    "    C == [not] [pop c ] [uncons swap] [dip Q        ] genrec\n",
    "\n",
    "### Para-, ?-, ?-\n",
    "\n",
    "    P == c  swap [P  ] [pop] [[Q        ] dupdip G          ] primrec\n",
    "    ? == [] swap [P  ] [pop] [[swap cons] dupdip G          ] primrec\n",
    "    ? == c  swap [not] [pop] [[Q        ] dupdip uncons swap] primrec\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Appendix: Fun with Symbols\n",
    "\n",
    "    |[ (c, Q), (G, P) ]| == (|c, Q|) • [(G, P)]\n",
    "\n",
    "[\"Bananas, Lenses, & Barbed Wire\"](http://citeseerx.ist.psu.edu/viewdoc/summary?doi=10.1.1.41.125)\n",
    "\n",
    "    (|...|)  [(...)]  [<...>]\n",
    "\n",
    "I think they are having slightly too much fun with the symbols.  However, \"Too much is always better than not enough.\""
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Joypy",
   "language": "",
   "name": "thun"
  },
  "language_info": {
   "file_extension": ".joy",
   "mimetype": "text/plain",
   "name": "Joy"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
