OSDN Git Service

a97a93e787db1a203332d0c95ca5cf3fe7000ca8
[joypy/Thun.git] / docs / 0. This Implementation of Joy in Python.ipynb
1 {
2  "cells": [
3   {
4    "cell_type": "markdown",
5    "metadata": {},
6    "source": [
7     "# Joypy\n",
8     "## Joy in Python\n",
9     "\n",
10     "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",
11     "\n",
12     "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."
13    ]
14   },
15   {
16    "cell_type": "markdown",
17    "metadata": {},
18    "source": [
19     "### [Read-Eval-Print Loop (REPL)](https://en.wikipedia.org/wiki/Read%E2%80%93eval%E2%80%93print_loop)\n",
20     "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",
21     "\n",
22     "    $ python -m joy\n",
23     "    Joypy - Copyright © 2017 Simon Forman\n",
24     "    This program comes with ABSOLUTELY NO WARRANTY; for details type \"warranty\".\n",
25     "    This is free software, and you are welcome to redistribute it\n",
26     "    under certain conditions; type \"sharing\" for details.\n",
27     "    Type \"words\" to see a list of all words, and \"[<name>] help\" to print the\n",
28     "    docs for a word.\n",
29     "\n",
30     "\n",
31     "     <-top\n",
32     "\n",
33     "    joy? _\n",
34     "\n",
35     "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",
36     "\n",
37     "    joy? 23 sqr 18 +\n",
38     "           . 23 sqr 18 +\n",
39     "        23 . sqr 18 +\n",
40     "        23 . dup mul 18 +\n",
41     "     23 23 . mul 18 +\n",
42     "       529 . 18 +\n",
43     "    529 18 . +\n",
44     "       547 . \n",
45     "\n",
46     "    547 <-top\n",
47     "\n",
48     "    joy? \n"
49    ]
50   },
51   {
52    "cell_type": "markdown",
53    "metadata": {},
54    "source": [
55     "# Stacks (aka list, quote, sequence, etc.)\n",
56     "\n",
57     "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."
58    ]
59   },
60   {
61    "cell_type": "code",
62    "execution_count": 1,
63    "metadata": {},
64    "outputs": [
65     {
66      "name": "stdout",
67      "output_type": "stream",
68      "text": [
69       "§ Stack\n",
70       "\n",
71       "\n",
72       "When talking about Joy we use the terms \"stack\", \"list\", \"sequence\" and\n",
73       "\"aggregate\" to mean the same thing: a simple datatype that permits\n",
74       "certain operations such as iterating and pushing and popping values from\n",
75       "(at least) one end.\n",
76       "\n",
77       "We use the venerable two-tuple recursive form of sequences where the\n",
78       "empty tuple () is the empty stack and (head, rest) gives the recursive\n",
79       "form of a stack with one or more items on it.\n",
80       "\n",
81       "  ()\n",
82       "  (1, ())\n",
83       "  (2, (1, ()))\n",
84       "  (3, (2, (1, ())))\n",
85       "  ...\n",
86       "\n",
87       "And so on.\n",
88       "\n",
89       "\n",
90       "We have two very simple functions to build up a stack from a Python\n",
91       "iterable and also to iterate through a stack and yield its items\n",
92       "one-by-one in order, and two functions to generate string representations\n",
93       "of stacks:\n",
94       "\n",
95       "  list_to_stack()\n",
96       "\n",
97       "  iter_stack()\n",
98       "\n",
99       "  expression_to_string()  (prints left-to-right)\n",
100       "\n",
101       "  stack_to_string()  (prints right-to-left)\n",
102       "\n",
103       "\n",
104       "A word about the stack data structure.\n",
105       "\n",
106       "Python has very nice \"tuple packing and unpacking\" in its syntax which\n",
107       "means we can directly \"unpack\" the expected arguments to a Joy function.\n",
108       "\n",
109       "For example:\n",
110       "\n",
111       "  def dup(stack):\n",
112       "    head, tail = stack\n",
113       "    return head, (head, tail)\n",
114       "\n",
115       "We replace the argument \"stack\" by the expected structure of the stack,\n",
116       "in this case \"(head, tail)\", and Python takes care of de-structuring the\n",
117       "incoming argument and assigning values to the names.  Note that Python\n",
118       "syntax doesn't require parentheses around tuples used in expressions\n",
119       "where they would be redundant.\n"
120      ]
121     }
122    ],
123    "source": [
124     "import inspect\n",
125     "import joy.utils.stack\n",
126     "\n",
127     "\n",
128     "print inspect.getdoc(joy.utils.stack)"
129    ]
130   },
131   {
132    "cell_type": "markdown",
133    "metadata": {},
134    "source": [
135     "### The utility functions maintain order.\n",
136     "The 0th item in the list will be on the top of the stack and *vise versa*."
137    ]
138   },
139   {
140    "cell_type": "code",
141    "execution_count": 2,
142    "metadata": {},
143    "outputs": [
144     {
145      "data": {
146       "text/plain": [
147        "(1, (2, (3, ())))"
148       ]
149      },
150      "execution_count": 2,
151      "metadata": {},
152      "output_type": "execute_result"
153     }
154    ],
155    "source": [
156     "joy.utils.stack.list_to_stack([1, 2, 3])"
157    ]
158   },
159   {
160    "cell_type": "code",
161    "execution_count": 3,
162    "metadata": {},
163    "outputs": [
164     {
165      "data": {
166       "text/plain": [
167        "[1, 2, 3]"
168       ]
169      },
170      "execution_count": 3,
171      "metadata": {},
172      "output_type": "execute_result"
173     }
174    ],
175    "source": [
176     "list(joy.utils.stack.iter_stack((1, (2, (3, ())))))"
177    ]
178   },
179   {
180    "cell_type": "markdown",
181    "metadata": {},
182    "source": [
183     "This requires reversing the sequence (or iterating backwards) otherwise:"
184    ]
185   },
186   {
187    "cell_type": "code",
188    "execution_count": 4,
189    "metadata": {},
190    "outputs": [
191     {
192      "name": "stdout",
193      "output_type": "stream",
194      "text": [
195       "(3, (2, (1, ())))\n",
196       "[3, 2, 1]\n"
197      ]
198     }
199    ],
200    "source": [
201     "stack = ()\n",
202     "\n",
203     "for n in [1, 2, 3]:\n",
204     "    stack = n, stack\n",
205     "\n",
206     "print stack\n",
207     "print list(joy.utils.stack.iter_stack(stack))"
208    ]
209   },
210   {
211    "cell_type": "markdown",
212    "metadata": {},
213    "source": [
214     "### Purely Functional Datastructures.\n",
215     "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)*."
216    ]
217   },
218   {
219    "cell_type": "markdown",
220    "metadata": {},
221    "source": [
222     "# The `joy()` function.\n",
223     "## An Interpreter\n",
224     "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",
225     "\n",
226     "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.)"
227    ]
228   },
229   {
230    "cell_type": "code",
231    "execution_count": 5,
232    "metadata": {},
233    "outputs": [
234     {
235      "name": "stdout",
236      "output_type": "stream",
237      "text": [
238       "def joy(stack, expression, dictionary, viewer=None):\n",
239       "  '''\n",
240       "  Evaluate the Joy expression on the stack.\n",
241       "  '''\n",
242       "  while expression:\n",
243       "\n",
244       "    if viewer: viewer(stack, expression)\n",
245       "\n",
246       "    term, expression = expression\n",
247       "    if isinstance(term, Symbol):\n",
248       "      term = dictionary[term]\n",
249       "      stack, expression, dictionary = term(stack, expression, dictionary)\n",
250       "    else:\n",
251       "      stack = term, stack\n",
252       "\n",
253       "  if viewer: viewer(stack, expression)\n",
254       "  return stack, expression, dictionary\n",
255       "\n"
256      ]
257     }
258    ],
259    "source": [
260     "import joy.joy\n",
261     "\n",
262     "print inspect.getsource(joy.joy.joy)"
263    ]
264   },
265   {
266    "cell_type": "markdown",
267    "metadata": {},
268    "source": [
269     "### View function\n",
270     "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."
271    ]
272   },
273   {
274    "cell_type": "markdown",
275    "metadata": {},
276    "source": [
277     "### The `TracePrinter`.\n",
278     "\n",
279     "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."
280    ]
281   },
282   {
283    "cell_type": "markdown",
284    "metadata": {},
285    "source": [
286     "### [Continuation-Passing Style](https://en.wikipedia.org/wiki/Continuation-passing_style)\n",
287     "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."
288    ]
289   },
290   {
291    "cell_type": "markdown",
292    "metadata": {},
293    "source": [
294     "# Parser"
295    ]
296   },
297   {
298    "cell_type": "code",
299    "execution_count": 6,
300    "metadata": {},
301    "outputs": [
302     {
303      "name": "stdout",
304      "output_type": "stream",
305      "text": [
306       "§ Converting text to a joy expression.\n",
307       "\n",
308       "This module exports a single function:\n",
309       "\n",
310       "  text_to_expression(text)\n",
311       "\n",
312       "As well as a single Symbol class and a single Exception type:\n",
313       "\n",
314       "  ParseError\n",
315       "\n",
316       "When supplied with a string this function returns a Python datastructure\n",
317       "that represents the Joy datastructure described by the text expression.\n",
318       "Any unbalanced square brackets will raise a ParseError.\n"
319      ]
320     }
321    ],
322    "source": [
323     "import joy.parser\n",
324     "\n",
325     "print inspect.getdoc(joy.parser)"
326    ]
327   },
328   {
329    "cell_type": "markdown",
330    "metadata": {},
331    "source": [
332     "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."
333    ]
334   },
335   {
336    "cell_type": "code",
337    "execution_count": 7,
338    "metadata": {},
339    "outputs": [
340     {
341      "name": "stdout",
342      "output_type": "stream",
343      "text": [
344       "def _parse(tokens):\n",
345       "  '''\n",
346       "  Return a stack/list expression of the tokens.\n",
347       "  '''\n",
348       "  frame = []\n",
349       "  stack = []\n",
350       "  for tok in tokens:\n",
351       "    if tok == '[':\n",
352       "      stack.append(frame)\n",
353       "      frame = []\n",
354       "      stack[-1].append(frame)\n",
355       "    elif tok == ']':\n",
356       "      try:\n",
357       "        frame = stack.pop()\n",
358       "      except IndexError:\n",
359       "        raise ParseError('One or more extra closing brackets.')\n",
360       "      frame[-1] = list_to_stack(frame[-1])\n",
361       "    else:\n",
362       "      frame.append(tok)\n",
363       "  if stack:\n",
364       "    raise ParseError('One or more unclosed brackets.')\n",
365       "  return list_to_stack(frame)\n",
366       "\n"
367      ]
368     }
369    ],
370    "source": [
371     "print inspect.getsource(joy.parser._parse)"
372    ]
373   },
374   {
375    "cell_type": "markdown",
376    "metadata": {},
377    "source": [
378     "That's pretty much all there is to it."
379    ]
380   },
381   {
382    "cell_type": "code",
383    "execution_count": 8,
384    "metadata": {},
385    "outputs": [
386     {
387      "data": {
388       "text/plain": [
389        "(1, (2, (3, (4, (5, ())))))"
390       ]
391      },
392      "execution_count": 8,
393      "metadata": {},
394      "output_type": "execute_result"
395     }
396    ],
397    "source": [
398     "joy.parser.text_to_expression('1 2 3 4 5')  # A simple sequence."
399    ]
400   },
401   {
402    "cell_type": "code",
403    "execution_count": 9,
404    "metadata": {},
405    "outputs": [
406     {
407      "data": {
408       "text/plain": [
409        "((1, (2, (3, ()))), (4, (5, ())))"
410       ]
411      },
412      "execution_count": 9,
413      "metadata": {},
414      "output_type": "execute_result"
415     }
416    ],
417    "source": [
418     "joy.parser.text_to_expression('[1 2 3] 4 5')  # Three items, the first is a list with three items"
419    ]
420   },
421   {
422    "cell_type": "code",
423    "execution_count": 10,
424    "metadata": {},
425    "outputs": [
426     {
427      "data": {
428       "text/plain": [
429        "(1, (23, (('four', ((-5.0, ()), (cons, ()))), (8888, ()))))"
430       ]
431      },
432      "execution_count": 10,
433      "metadata": {},
434      "output_type": "execute_result"
435     }
436    ],
437    "source": [
438     "joy.parser.text_to_expression('1 23 [\"four\" [-5.0] cons] 8888')  # A mixed bag. cons is\n",
439     "                                                                 # a Symbol, no lookup at\n",
440     "                                                                 # parse-time.  Haiku docs."
441    ]
442   },
443   {
444    "cell_type": "code",
445    "execution_count": 11,
446    "metadata": {},
447    "outputs": [
448     {
449      "data": {
450       "text/plain": [
451        "((), ((), ((), ((), ((), ())))))"
452       ]
453      },
454      "execution_count": 11,
455      "metadata": {},
456      "output_type": "execute_result"
457     }
458    ],
459    "source": [
460     "joy.parser.text_to_expression('[][][][][]')  # Five empty lists."
461    ]
462   },
463   {
464    "cell_type": "code",
465    "execution_count": 12,
466    "metadata": {},
467    "outputs": [
468     {
469      "data": {
470       "text/plain": [
471        "((((((), ()), ()), ()), ()), ())"
472       ]
473      },
474      "execution_count": 12,
475      "metadata": {},
476      "output_type": "execute_result"
477     }
478    ],
479    "source": [
480     "joy.parser.text_to_expression('[[[[[]]]]]')  # Five nested lists."
481    ]
482   },
483   {
484    "cell_type": "markdown",
485    "metadata": {},
486    "source": [
487     "# Library\n",
488     "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."
489    ]
490   },
491   {
492    "cell_type": "code",
493    "execution_count": 13,
494    "metadata": {},
495    "outputs": [
496     {
497      "name": "stdout",
498      "output_type": "stream",
499      "text": [
500       "!= % & * *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"
501      ]
502     }
503    ],
504    "source": [
505     "import joy.library\n",
506     "\n",
507     "print ' '.join(sorted(joy.library.initialize()))"
508    ]
509   },
510   {
511    "cell_type": "markdown",
512    "metadata": {},
513    "source": [
514     "Many of the functions are defined in Python, like `dip`:"
515    ]
516   },
517   {
518    "cell_type": "code",
519    "execution_count": 14,
520    "metadata": {},
521    "outputs": [
522     {
523      "name": "stdout",
524      "output_type": "stream",
525      "text": [
526       "def dip(stack, expression, dictionary):\n",
527       "  (quote, (x, stack)) = stack\n",
528       "  expression = x, expression\n",
529       "  return stack, pushback(quote, expression), dictionary\n",
530       "\n"
531      ]
532     }
533    ],
534    "source": [
535     "print inspect.getsource(joy.library.dip)"
536    ]
537   },
538   {
539    "cell_type": "markdown",
540    "metadata": {},
541    "source": [
542     "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."
543    ]
544   },
545   {
546    "cell_type": "code",
547    "execution_count": 15,
548    "metadata": {},
549    "outputs": [
550     {
551      "name": "stdout",
552      "output_type": "stream",
553      "text": [
554       "second == rest first\n",
555       "third == rest rest first\n",
556       "product == 1 swap [*] step\n",
557       "swons == swap cons\n",
558       "swoncat == swap concat\n",
559       "flatten == [] swap [concat] step\n",
560       "unit == [] cons\n",
561       "quoted == [unit] dip\n",
562       "unquoted == [i] dip\n",
563       "enstacken == stack [clear] dip\n",
564       "disenstacken == ? [uncons ?] loop pop\n",
565       "? == dup truthy\n",
566       "dinfrirst == dip infra first\n",
567       "nullary == [stack] dinfrirst\n",
568       "unary == [stack [pop] dip] dinfrirst\n",
569       "binary == [stack [popop] dip] dinfrirst\n",
570       "ternary == [stack [popop pop] dip] dinfrirst\n",
571       "pam == [i] map\n",
572       "run == [] swap infra\n",
573       "sqr == dup mul\n",
574       "size == 0 swap [pop ++] step\n",
575       "cleave == [i] app2 [popd] dip\n",
576       "average == [sum 1.0 *] [size] cleave /\n",
577       "gcd == 1 [tuck modulus dup 0 >] loop pop\n",
578       "least_fraction == dup [gcd] infra [div] concat map\n",
579       "*fraction == [uncons] dip uncons [swap] dip concat [*] infra [*] dip cons\n",
580       "*fraction0 == concat [[swap] dip * [*] dip] infra\n",
581       "down_to_zero == [0 >] [dup --] while\n",
582       "range_to_zero == unit [down_to_zero] infra\n",
583       "anamorphism == [pop []] swap [dip swons] genrec\n",
584       "range == [0 <=] [1 - dup] anamorphism\n",
585       "while == swap [nullary] cons dup dipd concat loop\n",
586       "dudipd == dup dipd\n",
587       "primrec == [i] genrec\n",
588       "\n"
589      ]
590     }
591    ],
592    "source": [
593     "print joy.library.definitions"
594    ]
595   },
596   {
597    "cell_type": "markdown",
598    "metadata": {},
599    "source": [
600     "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",
601     "\n",
602     "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",
603     "\n",
604     "#### \"There should be only one.\"\n",
605     "\n",
606     "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",
607     "\n",
608     "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",
609     "\n",
610     "#### Literary Code Library\n",
611     "\n",
612     "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",
613     "\n",
614     "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",
615     "\n",
616     "There seems to be an elegance and power to the notation.\n"
617    ]
618   },
619   {
620    "cell_type": "code",
621    "execution_count": null,
622    "metadata": {},
623    "outputs": [],
624    "source": [
625     "  "
626    ]
627   }
628  ],
629  "metadata": {
630   "kernelspec": {
631    "display_name": "Python 2",
632    "language": "python",
633    "name": "python2"
634   },
635   "language_info": {
636    "codemirror_mode": {
637     "name": "ipython",
638     "version": 2
639    },
640    "file_extension": ".py",
641    "mimetype": "text/x-python",
642    "name": "python",
643    "nbconvert_exporter": "python",
644    "pygments_lexer": "ipython2",
645    "version": "2.7.13"
646   }
647  },
648  "nbformat": 4,
649  "nbformat_minor": 2
650 }