{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Joypy\n",
    "\n",
    "## Joy in Python\n",
    "\n",
    "This implementation is meant as a tool for exploring the programming model and method of Joy.  Python seems like a great implementation language for Joy for several reasons.\n",
    "\n",
    "We can lean on the Python immutable types for our basic semantics and types: ints, floats, strings, and tuples, which enforces functional purity.  We get garbage collection for free.  Compilation via Cython.  Glue language with loads of libraries."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### [Read-Eval-Print Loop (REPL)](https://en.wikipedia.org/wiki/Read%E2%80%93eval%E2%80%93print_loop)\n",
    "The main way to interact with the Joy interpreter is through a simple [REPL](https://en.wikipedia.org/wiki/Read%E2%80%93eval%E2%80%93print_loop) that you start by running the package:\n",
    "\n",
    "    $ python -m joy\n",
    "    Joypy - Copyright © 2017 Simon Forman\n",
    "    This program comes with ABSOLUTELY NO WARRANTY; for details type \"warranty\".\n",
    "    This is free software, and you are welcome to redistribute it\n",
    "    under certain conditions; type \"sharing\" for details.\n",
    "    Type \"words\" to see a list of all words, and \"[<name>] help\" to print the\n",
    "    docs for a word.\n",
    "\n",
    "\n",
    "     <-top\n",
    "\n",
    "    joy? _\n",
    "\n",
    "The `<-top` marker points to the top of the (initially empty) stack.  You can enter Joy notation at the prompt and a [trace of evaluation](#The-TracePrinter.) will be printed followed by the stack and prompt again:\n",
    "\n",
    "    joy? 23 sqr 18 +\n",
    "           . 23 sqr 18 +\n",
    "        23 . sqr 18 +\n",
    "        23 . dup mul 18 +\n",
    "     23 23 . mul 18 +\n",
    "       529 . 18 +\n",
    "    529 18 . +\n",
    "       547 . \n",
    "\n",
    "    547 <-top\n",
    "\n",
    "    joy? \n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Stacks (aka list, quote, sequence, etc.)\n",
    "\n",
    "In Joy, in addition to the types Boolean, integer, float, and string, there is a single sequence type represented by enclosing a sequence of terms in brackets `[...]`.  This sequence type is used to represent both the stack and the expression.  It is a [cons list](https://en.wikipedia.org/wiki/Cons#Lists) made from Python tuples."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "§ Stack\n",
      "\n",
      "\n",
      "When talking about Joy we use the terms \"stack\", \"list\", \"sequence\" and\n",
      "\"aggregate\" to mean the same thing: a simple datatype that permits\n",
      "certain operations such as iterating and pushing and popping values from\n",
      "(at least) one end.\n",
      "\n",
      "We use the venerable two-tuple recursive form of sequences where the\n",
      "empty tuple () is the empty stack and (head, rest) gives the recursive\n",
      "form of a stack with one or more items on it.\n",
      "\n",
      "  ()\n",
      "  (1, ())\n",
      "  (2, (1, ()))\n",
      "  (3, (2, (1, ())))\n",
      "  ...\n",
      "\n",
      "And so on.\n",
      "\n",
      "\n",
      "We have two very simple functions to build up a stack from a Python\n",
      "iterable and also to iterate through a stack and yield its items\n",
      "one-by-one in order, and two functions to generate string representations\n",
      "of stacks:\n",
      "\n",
      "  list_to_stack()\n",
      "\n",
      "  iter_stack()\n",
      "\n",
      "  expression_to_string()  (prints left-to-right)\n",
      "\n",
      "  stack_to_string()  (prints right-to-left)\n",
      "\n",
      "\n",
      "A word about the stack data structure.\n",
      "\n",
      "Python has very nice \"tuple packing and unpacking\" in its syntax which\n",
      "means we can directly \"unpack\" the expected arguments to a Joy function.\n",
      "\n",
      "For example:\n",
      "\n",
      "  def dup(stack):\n",
      "    head, tail = stack\n",
      "    return head, (head, tail)\n",
      "\n",
      "We replace the argument \"stack\" by the expected structure of the stack,\n",
      "in this case \"(head, tail)\", and Python takes care of de-structuring the\n",
      "incoming argument and assigning values to the names.  Note that Python\n",
      "syntax doesn't require parentheses around tuples used in expressions\n",
      "where they would be redundant.\n"
     ]
    }
   ],
   "source": [
    "import inspect\n",
    "import joy.utils.stack\n",
    "\n",
    "\n",
    "print inspect.getdoc(joy.utils.stack)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### The utility functions maintain order.\n",
    "The 0th item in the list will be on the top of the stack and *vise versa*."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "(1, (2, (3, ())))"
      ]
     },
     "execution_count": 2,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "joy.utils.stack.list_to_stack([1, 2, 3])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "[1, 2, 3]"
      ]
     },
     "execution_count": 3,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "list(joy.utils.stack.iter_stack((1, (2, (3, ())))))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "This requires reversing the sequence (or iterating backwards) otherwise:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "(3, (2, (1, ())))\n",
      "[3, 2, 1]\n"
     ]
    }
   ],
   "source": [
    "stack = ()\n",
    "\n",
    "for n in [1, 2, 3]:\n",
    "    stack = n, stack\n",
    "\n",
    "print stack\n",
    "print list(joy.utils.stack.iter_stack(stack))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Purely Functional Datastructures.\n",
    "Because Joy lists are made out of Python tuples they are immutable, so all Joy datastructures are *[purely functional](https://en.wikipedia.org/wiki/Purely_functional_data_structure)*."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# The `joy()` function.\n",
    "## An Interpreter\n",
    "The `joy()` function is extrememly simple.  It accepts a stack, an expression, and a dictionary, and it iterates through the expression putting values onto the stack and delegating execution to functions it looks up in the dictionary.\n",
    "\n",
    "Each function is passed the stack, expression, and dictionary and returns them.  Whatever the function returns becomes the new stack, expression, and dictionary.  (The dictionary is passed to enable e.g. writing words that let you enter new words into the dictionary at runtime, which nothing does yet and may be a bad idea, and the `help` command.)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "def joy(stack, expression, dictionary, viewer=None):\n",
      "  '''\n",
      "  Evaluate the Joy expression on the stack.\n",
      "  '''\n",
      "  while expression:\n",
      "\n",
      "    if viewer: viewer(stack, expression)\n",
      "\n",
      "    term, expression = expression\n",
      "    if isinstance(term, Symbol):\n",
      "      term = dictionary[term]\n",
      "      stack, expression, dictionary = term(stack, expression, dictionary)\n",
      "    else:\n",
      "      stack = term, stack\n",
      "\n",
      "  if viewer: viewer(stack, expression)\n",
      "  return stack, expression, dictionary\n",
      "\n"
     ]
    }
   ],
   "source": [
    "import joy.joy\n",
    "\n",
    "print inspect.getsource(joy.joy.joy)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### View function\n",
    "The `joy()` function accepts a \"viewer\" function which it calls on each iteration passing the current stack and expression just before evaluation.  This can be used for tracing, breakpoints, retrying after exceptions, or interrupting an evaluation and saving to disk or sending over the network to resume later.  The stack and expression together contain all the state of the computation at each step."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### The `TracePrinter`.\n",
    "\n",
    "A `viewer` records each step of the evaluation of a Joy program.  The `TracePrinter` has a facility for printing out a trace of the evaluation, one line per step.  Each step is aligned to the current interpreter position, signified by a period separating the stack on the left from the pending expression (\"continuation\") on the right."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### [Continuation-Passing Style](https://en.wikipedia.org/wiki/Continuation-passing_style)\n",
    "One day I thought, What happens if you rewrite Joy to use [CSP](https://en.wikipedia.org/wiki/Continuation-passing_style)?  I made all the functions accept and return the expression as well as the stack and found that all the combinators could be rewritten to work by modifying the expression rather than making recursive calls to the `joy()` function."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Parser"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "§ Converting text to a joy expression.\n",
      "\n",
      "This module exports a single function:\n",
      "\n",
      "  text_to_expression(text)\n",
      "\n",
      "As well as a single Symbol class and a single Exception type:\n",
      "\n",
      "  ParseError\n",
      "\n",
      "When supplied with a string this function returns a Python datastructure\n",
      "that represents the Joy datastructure described by the text expression.\n",
      "Any unbalanced square brackets will raise a ParseError.\n"
     ]
    }
   ],
   "source": [
    "import joy.parser\n",
    "\n",
    "print inspect.getdoc(joy.parser)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The parser is extremely simple, the undocumented `re.Scanner` class does most of the tokenizing work and then you just build the tuple structure out of the tokens.  There's no Abstract Syntax Tree or anything like that."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "def _parse(tokens):\n",
      "  '''\n",
      "  Return a stack/list expression of the tokens.\n",
      "  '''\n",
      "  frame = []\n",
      "  stack = []\n",
      "  for tok in tokens:\n",
      "    if tok == '[':\n",
      "      stack.append(frame)\n",
      "      frame = []\n",
      "      stack[-1].append(frame)\n",
      "    elif tok == ']':\n",
      "      try:\n",
      "        frame = stack.pop()\n",
      "      except IndexError:\n",
      "        raise ParseError('One or more extra closing brackets.')\n",
      "      frame[-1] = list_to_stack(frame[-1])\n",
      "    else:\n",
      "      frame.append(tok)\n",
      "  if stack:\n",
      "    raise ParseError('One or more unclosed brackets.')\n",
      "  return list_to_stack(frame)\n",
      "\n"
     ]
    }
   ],
   "source": [
    "print inspect.getsource(joy.parser._parse)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "That's pretty much all there is to it."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "(1, (2, (3, (4, (5, ())))))"
      ]
     },
     "execution_count": 8,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "joy.parser.text_to_expression('1 2 3 4 5')  # A simple sequence."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "((1, (2, (3, ()))), (4, (5, ())))"
      ]
     },
     "execution_count": 9,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "joy.parser.text_to_expression('[1 2 3] 4 5')  # Three items, the first is a list with three items"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "(1, (23, (('four', ((-5.0, ()), (cons, ()))), (8888, ()))))"
      ]
     },
     "execution_count": 10,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "joy.parser.text_to_expression('1 23 [\"four\" [-5.0] cons] 8888')  # A mixed bag. cons is\n",
    "                                                                 # a Symbol, no lookup at\n",
    "                                                                 # parse-time.  Haiku docs."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "((), ((), ((), ((), ((), ())))))"
      ]
     },
     "execution_count": 11,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "joy.parser.text_to_expression('[][][][][]')  # Five empty lists."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "((((((), ()), ()), ()), ()), ())"
      ]
     },
     "execution_count": 12,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "joy.parser.text_to_expression('[[[[[]]]]]')  # Five nested lists."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Library\n",
    "The Joy library of functions (aka commands, or \"words\" after Forth usage) encapsulates all the actual functionality (no pun intended) of the Joy system.  There are simple functions such as addition `add` (or `+`, the library module supports aliases), and combinators which provide control-flow and higher-order operations."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "!= % & * *fraction *fraction0 + ++ - -- / < << <= <> = > >= >> ? ^ add anamorphism and app1 app2 app3 average b binary branch choice clear cleave concat cons dinfrirst dip dipd dipdd disenstacken div down_to_zero dudipd dup dupd dupdip enstacken eq first flatten floordiv gcd ge genrec getitem gt help i id ifte infra le least_fraction loop lshift lt map min mod modulus mul ne neg not nullary or over pam parse pm pop popd popdd popop pow pred primrec product quoted range range_to_zero rem remainder remove rest reverse roll< roll> rolldown rollup rshift run second select sharing shunt size sqr sqrt stack step sub succ sum swaack swap swoncat swons ternary third times truediv truthy tuck unary uncons unit unquoted unstack void warranty while words x xor zip •\n"
     ]
    }
   ],
   "source": [
    "import joy.library\n",
    "\n",
    "print ' '.join(sorted(joy.library.initialize()))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Many of the functions are defined in Python, like `dip`:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 14,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "def dip(stack, expression, dictionary):\n",
      "  (quote, (x, stack)) = stack\n",
      "  expression = x, expression\n",
      "  return stack, pushback(quote, expression), dictionary\n",
      "\n"
     ]
    }
   ],
   "source": [
    "print inspect.getsource(joy.library.dip)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Some functions are defined in equations in terms of other functions.  When the interpreter executes a definition function that function just pushes its body expression onto the pending expression (the continuation) and returns control to the interpreter."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 15,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "second == rest first\n",
      "third == rest rest first\n",
      "product == 1 swap [*] step\n",
      "swons == swap cons\n",
      "swoncat == swap concat\n",
      "flatten == [] swap [concat] step\n",
      "unit == [] cons\n",
      "quoted == [unit] dip\n",
      "unquoted == [i] dip\n",
      "enstacken == stack [clear] dip\n",
      "disenstacken == ? [uncons ?] loop pop\n",
      "? == dup truthy\n",
      "dinfrirst == dip infra first\n",
      "nullary == [stack] dinfrirst\n",
      "unary == [stack [pop] dip] dinfrirst\n",
      "binary == [stack [popop] dip] dinfrirst\n",
      "ternary == [stack [popop pop] dip] dinfrirst\n",
      "pam == [i] map\n",
      "run == [] swap infra\n",
      "sqr == dup mul\n",
      "size == 0 swap [pop ++] step\n",
      "cleave == [i] app2 [popd] dip\n",
      "average == [sum 1.0 *] [size] cleave /\n",
      "gcd == 1 [tuck modulus dup 0 >] loop pop\n",
      "least_fraction == dup [gcd] infra [div] concat map\n",
      "*fraction == [uncons] dip uncons [swap] dip concat [*] infra [*] dip cons\n",
      "*fraction0 == concat [[swap] dip * [*] dip] infra\n",
      "down_to_zero == [0 >] [dup --] while\n",
      "range_to_zero == unit [down_to_zero] infra\n",
      "anamorphism == [pop []] swap [dip swons] genrec\n",
      "range == [0 <=] [1 - dup] anamorphism\n",
      "while == swap [nullary] cons dup dipd concat loop\n",
      "dudipd == dup dipd\n",
      "primrec == [i] genrec\n",
      "\n"
     ]
    }
   ],
   "source": [
    "print joy.library.definitions"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Currently, there's no function to add new definitions to the dictionary from \"within\" Joy code itself.  Adding new definitions remains a meta-interpreter action.  You have to do it yourself, in Python, and wash your hands afterward.\n",
    "\n",
    "It would be simple enough to define one, but it would open the door to *name binding* and break the idea that all state is captured in the stack and expression.  There's an implicit *standard dictionary* that defines the actual semantics of the syntactic stack and expression datastructures (which only contain symbols, not the actual functions.  Pickle some and see for yourself.)\n",
    "\n",
    "#### \"There should be only one.\"\n",
    "\n",
    "Which brings me to talking about one of my hopes and dreams for this notation:  \"There should be only one.\"  What I mean is that there should be one universal standard dictionary of commands, and all bespoke work done in a UI for purposes takes place by direct interaction and macros.  There would be a *Grand Refactoring* biannually (two years, not six months, that's semi-annually) where any new definitions factored out of the usage and macros of the previous time, along with new algorithms and such, were entered into the dictionary and posted to e.g. IPFS.\n",
    "\n",
    "Code should not burgeon wildly, as it does today.  The variety of code should map more-or-less to the well-factored variety of human computably-solvable problems.  There shouldn't be dozens of chat apps, JS frameworks, programming languages.  It's a waste of time, a [fractal \"thundering herd\" attack](https://en.wikipedia.org/wiki/Thundering_herd_problem) on human mentality.\n",
    "\n",
    "#### Literary Code Library\n",
    "\n",
    "If you read over the other notebooks you'll see that developing code in Joy is a lot like doing simple mathematics, and the descriptions of the code resemble math papers.  The code also works the first time, no bugs.  If you have any experience programming at all, you are probably skeptical, as I was, but it seems to work: deriving code mathematically seems to lead to fewer errors.\n",
    "\n",
    "But my point now is that this great ratio of textual explanation to wind up with code that consists of a few equations and could fit on an index card is highly desirable.  Less code has fewer errors.  The structure of Joy engenders a kind of thinking that seems to be very effective for developing structured processes.\n",
    "\n",
    "There seems to be an elegance and power to the notation.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "  "
   ]
  }
 ],
 "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
}
