{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# The Four Fundamental Operations of Definite Action\n",
    "\n",
    "All definite actions (computer program) can be defined by four fundamental patterns of combination:\n",
    "\n",
    "1. Sequence\n",
    "2. Branch\n",
    "3. Loop\n",
    "4. Parallel"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Sequence\n",
    "\n",
    "Do one thing after another.  In joy this is represented by putting two symbols together, juxtaposition:\n",
    "\n",
    "    foo bar\n",
    "\n",
    "Operations have inputs and outputs.  The outputs of `foo` must be compatible in \"arity\", type, and shape with the inputs of `bar`."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Branch\n",
    "\n",
    "Do one thing or another.\n",
    "\n",
    "    boolean [F] [T] branch\n",
    "\n",
    "\n",
    "       t [F] [T] branch\n",
    "    ----------------------\n",
    "              T\n",
    "\n",
    "\n",
    "       f [F] [T] branch\n",
    "    ----------------------\n",
    "          F\n",
    "\n",
    "\n",
    "    branch == unit cons swap pick i\n",
    "\n",
    "    boolean [F] [T] branch\n",
    "    boolean [F] [T] unit cons swap pick i\n",
    "    boolean [F] [[T]] cons swap pick i\n",
    "    boolean [[F] [T]] swap pick i\n",
    "    [[F] [T]] boolean pick i\n",
    "    [F-or-T] i"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Given some branch function `G`:\n",
    "\n",
    "    G == [F] [T] branch\n",
    "\n",
    "Used in a sequence like so:\n",
    "\n",
    "    foo G bar\n",
    "\n",
    "The inputs and outputs of `F` and `T` must be compatible with the outputs for `foo` and the inputs of `bar`, respectively.\n",
    "\n",
    "    foo F bar\n",
    "\n",
    "    foo T bar"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### `ifte`\n",
    "\n",
    "Often it will be easier on the programmer to write branching code with the predicate specified in a quote.  The `ifte` combinator provides this (`T` for \"then\" and `E` for \"else\"):\n",
    "\n",
    "    [P] [T] [E] ifte\n",
    "\n",
    "Defined in terms of `branch`:\n",
    "\n",
    "    ifte == [nullary not] dip branch\n",
    "\n",
    "\n",
    "In this case, `P` must be compatible with the stack and return a Boolean value, and `T` and `E` both must be compatible with the preceeding and following functions, as described above for `F` and `T`.  (Note that in the current implementation we are depending on Python for the underlying semantics, so the Boolean value doesn't *have* to be Boolean because Python's rules for \"truthiness\" will be used to evaluate it.  I reflect this in the structure of the stack effect comment of `branch`, it will only accept Boolean values, and in the definition of `ifte` above by including `not` in the quote, which also has the effect that the subject quotes are in the proper order for `branch`.)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Loop\n",
    "\n",
    "Do one thing zero or more times.\n",
    "\n",
    "    boolean [Q] loop\n",
    "\n",
    "\n",
    "       t [Q] loop\n",
    "    ----------------\n",
    "       Q [Q] loop\n",
    "\n",
    "\n",
    "       ... f [Q] loop\n",
    "    --------------------\n",
    "       ...\n",
    "\n",
    "The `loop` combinator generates a copy of itself in the true branch.  This is the hallmark of recursive defintions.  In Thun there is no equivalent to conventional loops.  (There is, however, the `x` combinator, defined as `x == dup i`, which permits recursive constructs that do not need to be directly self-referential, unlike `loop` and `genrec`.)\n",
    "\n",
    "    loop == [] swap [dup dip loop] cons branch\n",
    "\n",
    "    boolean [Q] loop\n",
    "    boolean [Q] [] swap [dup dip loop] cons branch\n",
    "    boolean [] [Q] [dup dip loop] cons branch\n",
    "    boolean [] [[Q] dup dip loop] branch\n",
    "\n",
    "In action the false branch does nothing while the true branch does:\n",
    "\n",
    "    t [] [[Q] dup dip loop] branch\n",
    "          [Q] dup dip loop\n",
    "          [Q] [Q] dip loop\n",
    "          Q [Q] loop"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Because `loop` expects and consumes a Boolean value, the `Q` function must be compatible with the previous stack *and itself* with a boolean flag for the next iteration:\n",
    "\n",
    "    Q == G b\n",
    "\n",
    "    Q [Q] loop\n",
    "    G b [Q] loop\n",
    "    G Q [Q] loop\n",
    "    G G b [Q] loop\n",
    "    G G Q [Q] loop\n",
    "    G G G b [Q] loop\n",
    "    G G G\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### `while`\n",
    "\n",
    "Keep doing `B` _while_ some predicate `P` is true.  This is convenient as the predicate function is made nullary automatically and the body function can be designed without regard to leaving a Boolean flag for the next iteration:\n",
    "\n",
    "\n",
    "\n",
    "                [P] [B] while\n",
    "    --------------------------------------\n",
    "       [P] nullary [B [P] nullary] loop\n",
    "\n",
    "\n",
    "    while == swap [nullary] cons dup dipd concat loop\n",
    "\n",
    "\n",
    "    [P] [B] while\n",
    "    [P] [B] swap [nullary] cons dup dipd concat loop\n",
    "    [B] [P] [nullary] cons dup dipd concat loop\n",
    "    [B] [[P] nullary] dup dipd concat loop\n",
    "    [B] [[P] nullary] [[P] nullary] dipd concat loop\n",
    "    [P] nullary [B] [[P] nullary] concat loop\n",
    "    [P] nullary [B [P] nullary] loop\n",
    "\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Parallel\n",
    "\n",
    "The *parallel* operation indicates that two (or more) functions *do not interfere* with each other and so can run in parallel.  The main difficulty in this sort of thing is orchestrating the recombining (\"join\" or \"wait\") of the results of the functions after they finish.\n",
    "\n",
    "The current implementaions and the following definitions *are not actually parallel* (yet), but there is no reason they couldn't be reimplemented in terms of e.g. Python threads.  I am not concerned with performance of the system just yet, only the elegance of the code it allows us to write."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### `cleave`\n",
    "\n",
    "Joy has a few parallel combinators, the main one being `cleave`:\n",
    "\n",
    "                   ... x [A] [B] cleave\n",
    "    ---------------------------------------------------------\n",
    "       ... [x ...] [A] infra first [x ...] [B] infra first\n",
    "    ---------------------------------------------------------\n",
    "                       ... a b\n",
    "\n",
    "The `cleave` combinator expects a value and two quotes and it executes each quote in \"separate universes\" such that neither can affect the other, then it takes the first item from the stack in each universe and replaces the value and quotes with their respective results.\n",
    "\n",
    "(I think this corresponds to the \"fork\" operator, the little upward-pointed triangle, that takes two functions `A :: x -> a` and `B :: x -> b` and returns a function `F :: x -> (a, b)`, in Conal Elliott's \"Compiling to Categories\" paper, et. al.)\n",
    "\n",
    "Just a thought, if you `cleave` two jobs and one requires more time to finish than the other you'd like to be able to assign resources accordingly so that they both finish at the same time."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### \"Apply\" Functions\n",
    "\n",
    "There are also `app2` and `app3` which run a single quote on more than one value:\n",
    "\n",
    "                     ... y x [Q] app2\n",
    "     ---------------------------------------------------------\n",
    "        ... [y ...] [Q] infra first [x ...] [Q] infra first\n",
    "\n",
    "\n",
    "            ... z y x [Q] app3\n",
    "     ---------------------------------\n",
    "        ... [z ...] [Q] infra first\n",
    "            [y ...] [Q] infra first\n",
    "            [x ...] [Q] infra first\n",
    "\n",
    "Because the quoted program can be `i` we can define `cleave` in terms of `app2`:\n",
    "\n",
    "    cleave == [i] app2 [popd] dip"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "(I'm not sure why `cleave` was specified to take that value, I may make a combinator that does the same thing but without expecting a value.)\n",
    "\n",
    "    clv == [i] app2\n",
    "\n",
    "       [A] [B] clv\n",
    "    ------------------\n",
    "         a b"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### `map`\n",
    "\n",
    "The common `map` function in Joy should also be though of as a *parallel* operator:\n",
    "\n",
    "    [a b c ...] [Q] map\n",
    "\n",
    "There is no reason why the implementation of `map` couldn't distribute the `Q` function over e.g. a pool of worker CPUs."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### `pam`\n",
    "\n",
    "One of my favorite combinators, the `pam` combinator is just:\n",
    "\n",
    "    pam == [i] map\n",
    "\n",
    "This can be used to run any number of programs separately on the current stack and combine their (first) outputs in a result list.\n",
    "\n",
    "       [[A] [B] [C] ...] [i] map\n",
    "    -------------------------------\n",
    "       [ a   b   c  ...]"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Handling Other Kinds of Join\n",
    "\n",
    "The `cleave` operators and others all have pretty brutal join semantics: everything works and we always wait for every sub-computation.  We can imagine a few different potentially useful patterns of \"joining\" results from parallel combinators."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### first-to-finish\n",
    "\n",
    "Thinking about variations of `pam` there could be one that only returns the first result of the first-to-finish sub-program, or the stack could be replaced by its output stack.\n",
    "\n",
    "The other sub-programs would be cancelled."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### \"Fulminators\"\n",
    "\n",
    "Also known as \"Futures\" or \"Promises\" (by *everybody* else.  \"Fulinators\" is what I was going to call them when I was thinking about implementing them in Thun.)\n",
    "\n",
    "The runtime could be amended to permit \"thunks\" representing the results of in-progress computations to be left on the stack and picked up by subsequent functions.  These would themselves be able to leave behind more \"thunks\", the values of which depend on the eventual resolution of the values of the previous thunks.\n",
    "\n",
    "In this way you can create \"chains\" (and more complex shapes) out of normal-looking code that consist of a kind of call-graph interspersed with \"asyncronous\" ... events?\n",
    "\n",
    "In any case, until I can find a rigorous theory that shows that this sort of thing works perfectly in Joy code I'm not going to worry about it.  (And I think the Categories can deal with it anyhow?  Incremental evaluation, yeah?)\n",
    "\n"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 2",
   "language": "python",
   "name": "python2"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 2
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython2",
   "version": "2.7.12"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
