diff --git a/docs/sphinx_docs/_build/doctrees/environment.pickle b/docs/sphinx_docs/_build/doctrees/environment.pickle index df73e23..f090715 100644 Binary files a/docs/sphinx_docs/_build/doctrees/environment.pickle and b/docs/sphinx_docs/_build/doctrees/environment.pickle differ diff --git a/docs/sphinx_docs/_build/doctrees/lib.doctree b/docs/sphinx_docs/_build/doctrees/lib.doctree index 681efe5..785d5bb 100644 Binary files a/docs/sphinx_docs/_build/doctrees/lib.doctree and b/docs/sphinx_docs/_build/doctrees/lib.doctree differ diff --git a/docs/sphinx_docs/_build/doctrees/notebooks/Derivatives_of_Regular_Expressions.doctree b/docs/sphinx_docs/_build/doctrees/notebooks/Derivatives_of_Regular_Expressions.doctree index c5f9725..165ff02 100644 Binary files a/docs/sphinx_docs/_build/doctrees/notebooks/Derivatives_of_Regular_Expressions.doctree and b/docs/sphinx_docs/_build/doctrees/notebooks/Derivatives_of_Regular_Expressions.doctree differ diff --git a/docs/sphinx_docs/_build/doctrees/notebooks/Developing.doctree b/docs/sphinx_docs/_build/doctrees/notebooks/Developing.doctree index c628a79..5204cb8 100644 Binary files a/docs/sphinx_docs/_build/doctrees/notebooks/Developing.doctree and b/docs/sphinx_docs/_build/doctrees/notebooks/Developing.doctree differ diff --git a/docs/sphinx_docs/_build/doctrees/notebooks/Generator_Programs.doctree b/docs/sphinx_docs/_build/doctrees/notebooks/Generator_Programs.doctree index ccb3948..eac2cc4 100644 Binary files a/docs/sphinx_docs/_build/doctrees/notebooks/Generator_Programs.doctree and b/docs/sphinx_docs/_build/doctrees/notebooks/Generator_Programs.doctree differ diff --git a/docs/sphinx_docs/_build/doctrees/notebooks/Intro.doctree b/docs/sphinx_docs/_build/doctrees/notebooks/Intro.doctree index 005112d..1a78f94 100644 Binary files a/docs/sphinx_docs/_build/doctrees/notebooks/Intro.doctree and b/docs/sphinx_docs/_build/doctrees/notebooks/Intro.doctree differ diff --git a/docs/sphinx_docs/_build/doctrees/notebooks/Ordered_Binary_Trees.doctree b/docs/sphinx_docs/_build/doctrees/notebooks/Ordered_Binary_Trees.doctree index 67405fe..38d5c96 100644 Binary files a/docs/sphinx_docs/_build/doctrees/notebooks/Ordered_Binary_Trees.doctree and b/docs/sphinx_docs/_build/doctrees/notebooks/Ordered_Binary_Trees.doctree differ diff --git a/docs/sphinx_docs/_build/doctrees/notebooks/Quadratic.doctree b/docs/sphinx_docs/_build/doctrees/notebooks/Quadratic.doctree index 9506af3..11a77fc 100644 Binary files a/docs/sphinx_docs/_build/doctrees/notebooks/Quadratic.doctree and b/docs/sphinx_docs/_build/doctrees/notebooks/Quadratic.doctree differ diff --git a/docs/sphinx_docs/_build/doctrees/notebooks/Recursion_Combinators.doctree b/docs/sphinx_docs/_build/doctrees/notebooks/Recursion_Combinators.doctree index fd0934b..03d6d1d 100644 Binary files a/docs/sphinx_docs/_build/doctrees/notebooks/Recursion_Combinators.doctree and b/docs/sphinx_docs/_build/doctrees/notebooks/Recursion_Combinators.doctree differ diff --git a/docs/sphinx_docs/_build/doctrees/notebooks/Replacing.doctree b/docs/sphinx_docs/_build/doctrees/notebooks/Replacing.doctree index 2ad1055..3bde7b5 100644 Binary files a/docs/sphinx_docs/_build/doctrees/notebooks/Replacing.doctree and b/docs/sphinx_docs/_build/doctrees/notebooks/Replacing.doctree differ diff --git a/docs/sphinx_docs/_build/doctrees/notebooks/Treestep.doctree b/docs/sphinx_docs/_build/doctrees/notebooks/Treestep.doctree index 91f5241..62d36b7 100644 Binary files a/docs/sphinx_docs/_build/doctrees/notebooks/Treestep.doctree and b/docs/sphinx_docs/_build/doctrees/notebooks/Treestep.doctree differ diff --git a/docs/sphinx_docs/_build/doctrees/notebooks/TypeChecking.doctree b/docs/sphinx_docs/_build/doctrees/notebooks/TypeChecking.doctree index ad9a5c1..646bf47 100644 Binary files a/docs/sphinx_docs/_build/doctrees/notebooks/TypeChecking.doctree and b/docs/sphinx_docs/_build/doctrees/notebooks/TypeChecking.doctree differ diff --git a/docs/sphinx_docs/_build/doctrees/notebooks/Types.doctree b/docs/sphinx_docs/_build/doctrees/notebooks/Types.doctree index 9ba07c8..e144f9e 100644 Binary files a/docs/sphinx_docs/_build/doctrees/notebooks/Types.doctree and b/docs/sphinx_docs/_build/doctrees/notebooks/Types.doctree differ diff --git a/docs/sphinx_docs/_build/doctrees/notebooks/Zipper.doctree b/docs/sphinx_docs/_build/doctrees/notebooks/Zipper.doctree index 22f043b..e51d16c 100644 Binary files a/docs/sphinx_docs/_build/doctrees/notebooks/Zipper.doctree and b/docs/sphinx_docs/_build/doctrees/notebooks/Zipper.doctree differ diff --git a/docs/sphinx_docs/_build/html/_sources/lib.rst.txt b/docs/sphinx_docs/_build/html/_sources/lib.rst.txt index b765192..2b93e4f 100644 --- a/docs/sphinx_docs/_build/html/_sources/lib.rst.txt +++ b/docs/sphinx_docs/_build/html/_sources/lib.rst.txt @@ -2,7 +2,7 @@ Functions Grouped by, er, Function with Examples ------------------------------------------------ -.. code:: ipython2 +.. code:: python from notebook_preamble import J, V @@ -19,7 +19,7 @@ it's "off the shelf" technology.) ``clear`` ~~~~~~~~~ -.. code:: ipython2 +.. code:: python J('1 2 3 clear') @@ -32,7 +32,7 @@ it's "off the shelf" technology.) ``dup`` ``dupd`` ~~~~~~~~~~~~~~~~ -.. code:: ipython2 +.. code:: python J('1 2 3 dup') @@ -42,7 +42,7 @@ it's "off the shelf" technology.) 1 2 3 3 -.. code:: ipython2 +.. code:: python J('1 2 3 dupd') @@ -58,7 +58,7 @@ it's "off the shelf" technology.) (I may have these paired up wrong. I.e. ``disenstacken`` should be ``unstack`` and vice versa.) -.. code:: ipython2 +.. code:: python J('1 2 3 enstacken') # Replace the stack with a quote of itself. @@ -68,7 +68,7 @@ it's "off the shelf" technology.) [3 2 1] -.. code:: ipython2 +.. code:: python J('4 5 6 [3 2 1] disenstacken') # Unpack a list onto the stack. @@ -78,7 +78,7 @@ it's "off the shelf" technology.) 4 5 6 3 2 1 -.. code:: ipython2 +.. code:: python J('1 2 3 stack') # Get the stack on the stack. @@ -88,7 +88,7 @@ it's "off the shelf" technology.) 1 2 3 [3 2 1] -.. code:: ipython2 +.. code:: python J('1 2 3 [4 5 6] unstack') # Replace the stack with the list on top. # The items appear reversed but they are not, @@ -103,7 +103,7 @@ it's "off the shelf" technology.) ``pop`` ``popd`` ``popop`` ~~~~~~~~~~~~~~~~~~~~~~~~~~ -.. code:: ipython2 +.. code:: python J('1 2 3 pop') @@ -113,7 +113,7 @@ it's "off the shelf" technology.) 1 2 -.. code:: ipython2 +.. code:: python J('1 2 3 popd') @@ -123,7 +123,7 @@ it's "off the shelf" technology.) 1 3 -.. code:: ipython2 +.. code:: python J('1 2 3 popop') @@ -139,7 +139,7 @@ it's "off the shelf" technology.) The "down" and "up" refer to the movement of two of the top three items (displacing the third.) -.. code:: ipython2 +.. code:: python J('1 2 3 roll<') @@ -149,7 +149,7 @@ The "down" and "up" refer to the movement of two of the top three items 2 3 1 -.. code:: ipython2 +.. code:: python J('1 2 3 roll>') @@ -162,7 +162,7 @@ The "down" and "up" refer to the movement of two of the top three items ``swap`` ~~~~~~~~ -.. code:: ipython2 +.. code:: python J('1 2 3 swap') @@ -175,7 +175,7 @@ The "down" and "up" refer to the movement of two of the top three items ``tuck`` ``over`` ~~~~~~~~~~~~~~~~~ -.. code:: ipython2 +.. code:: python J('1 2 3 tuck') @@ -185,7 +185,7 @@ The "down" and "up" refer to the movement of two of the top three items 1 3 2 3 -.. code:: ipython2 +.. code:: python J('1 2 3 over') @@ -198,7 +198,7 @@ The "down" and "up" refer to the movement of two of the top three items ``unit`` ``quoted`` ``unquoted`` ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -.. code:: ipython2 +.. code:: python J('1 2 3 unit') @@ -208,7 +208,7 @@ The "down" and "up" refer to the movement of two of the top three items 1 2 [3] -.. code:: ipython2 +.. code:: python J('1 2 3 quoted') @@ -218,7 +218,7 @@ The "down" and "up" refer to the movement of two of the top three items 1 [2] 3 -.. code:: ipython2 +.. code:: python J('1 [2] 3 unquoted') @@ -228,7 +228,7 @@ The "down" and "up" refer to the movement of two of the top three items 1 2 3 -.. code:: ipython2 +.. code:: python V('1 [dup] 3 unquoted') # Unquoting evaluates. Be aware. @@ -253,7 +253,7 @@ List words ``concat`` ``swoncat`` ``shunt`` ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -.. code:: ipython2 +.. code:: python J('[1 2 3] [4 5 6] concat') @@ -263,7 +263,7 @@ List words [1 2 3 4 5 6] -.. code:: ipython2 +.. code:: python J('[1 2 3] [4 5 6] swoncat') @@ -273,7 +273,7 @@ List words [4 5 6 1 2 3] -.. code:: ipython2 +.. code:: python J('[1 2 3] [4 5 6] shunt') @@ -286,7 +286,7 @@ List words ``cons`` ``swons`` ``uncons`` ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -.. code:: ipython2 +.. code:: python J('1 [2 3] cons') @@ -296,7 +296,7 @@ List words [1 2 3] -.. code:: ipython2 +.. code:: python J('[2 3] 1 swons') @@ -306,7 +306,7 @@ List words [1 2 3] -.. code:: ipython2 +.. code:: python J('[1 2 3] uncons') @@ -319,7 +319,7 @@ List words ``first`` ``second`` ``third`` ``rest`` ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -.. code:: ipython2 +.. code:: python J('[1 2 3 4] first') @@ -329,7 +329,7 @@ List words 1 -.. code:: ipython2 +.. code:: python J('[1 2 3 4] second') @@ -339,7 +339,7 @@ List words 2 -.. code:: ipython2 +.. code:: python J('[1 2 3 4] third') @@ -349,7 +349,7 @@ List words 3 -.. code:: ipython2 +.. code:: python J('[1 2 3 4] rest') @@ -362,7 +362,7 @@ List words ``flatten`` ~~~~~~~~~~~ -.. code:: ipython2 +.. code:: python J('[[1] [2 [3] 4] [5 6]] flatten') @@ -377,7 +377,7 @@ List words ``at`` and ``getitem`` are the same function. ``of == swap at`` -.. code:: ipython2 +.. code:: python J('[10 11 12 13 14] 2 getitem') @@ -387,7 +387,7 @@ List words 12 -.. code:: ipython2 +.. code:: python J('[1 2 3 4] 0 at') @@ -397,7 +397,7 @@ List words 1 -.. code:: ipython2 +.. code:: python J('2 [1 2 3 4] of') @@ -407,7 +407,7 @@ List words 3 -.. code:: ipython2 +.. code:: python J('[1 2 3 4] 2 drop') @@ -417,7 +417,7 @@ List words [3 4] -.. code:: ipython2 +.. code:: python J('[1 2 3 4] 2 take') # reverses the order @@ -432,7 +432,7 @@ List words ``remove`` ~~~~~~~~~~ -.. code:: ipython2 +.. code:: python J('[1 2 3 1 4] 1 remove') @@ -445,7 +445,7 @@ List words ``reverse`` ~~~~~~~~~~~ -.. code:: ipython2 +.. code:: python J('[1 2 3 4] reverse') @@ -458,7 +458,7 @@ List words ``size`` ~~~~~~~~ -.. code:: ipython2 +.. code:: python J('[1 1 1 1] size') @@ -475,7 +475,7 @@ List words put the old stack on top of the new one. Think of it as a context switch. Niether of the lists/stacks change their order. -.. code:: ipython2 +.. code:: python J('1 2 3 [4 5 6] swaack') @@ -488,7 +488,7 @@ switch. Niether of the lists/stacks change their order. ``choice`` ``select`` ~~~~~~~~~~~~~~~~~~~~~ -.. code:: ipython2 +.. code:: python J('23 9 1 choice') @@ -498,7 +498,7 @@ switch. Niether of the lists/stacks change their order. 9 -.. code:: ipython2 +.. code:: python J('23 9 0 choice') @@ -508,7 +508,7 @@ switch. Niether of the lists/stacks change their order. 23 -.. code:: ipython2 +.. code:: python J('[23 9 7] 1 select') # select is basically getitem, should retire it? @@ -518,7 +518,7 @@ switch. Niether of the lists/stacks change their order. 9 -.. code:: ipython2 +.. code:: python J('[23 9 7] 0 select') @@ -531,7 +531,7 @@ switch. Niether of the lists/stacks change their order. ``zip`` ~~~~~~~ -.. code:: ipython2 +.. code:: python J('[1 2 3] [6 5 4] zip') @@ -541,7 +541,7 @@ switch. Niether of the lists/stacks change their order. [[6 1] [5 2] [4 3]] -.. code:: ipython2 +.. code:: python J('[1 2 3] [6 5 4] zip [sum] map') @@ -557,7 +557,7 @@ Math words ``+`` ``add`` ~~~~~~~~~~~~~ -.. code:: ipython2 +.. code:: python J('23 9 +') @@ -570,7 +570,7 @@ Math words ``-`` ``sub`` ~~~~~~~~~~~~~ -.. code:: ipython2 +.. code:: python J('23 9 -') @@ -583,7 +583,7 @@ Math words ``*`` ``mul`` ~~~~~~~~~~~~~ -.. code:: ipython2 +.. code:: python J('23 9 *') @@ -596,7 +596,7 @@ Math words ``/`` ``div`` ``floordiv`` ``truediv`` ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -.. code:: ipython2 +.. code:: python J('23 9 /') @@ -606,7 +606,7 @@ Math words 2.5555555555555554 -.. code:: ipython2 +.. code:: python J('23 -9 truediv') @@ -616,7 +616,7 @@ Math words -2.5555555555555554 -.. code:: ipython2 +.. code:: python J('23 9 div') @@ -626,7 +626,7 @@ Math words 2 -.. code:: ipython2 +.. code:: python J('23 9 floordiv') @@ -636,7 +636,7 @@ Math words 2 -.. code:: ipython2 +.. code:: python J('23 -9 div') @@ -646,7 +646,7 @@ Math words -3 -.. code:: ipython2 +.. code:: python J('23 -9 floordiv') @@ -659,7 +659,7 @@ Math words ``%`` ``mod`` ``modulus`` ``rem`` ``remainder`` ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -.. code:: ipython2 +.. code:: python J('23 9 %') @@ -672,7 +672,7 @@ Math words ``neg`` ~~~~~~~ -.. code:: ipython2 +.. code:: python J('23 neg -5 neg') @@ -685,7 +685,7 @@ Math words ``pow`` ~~~~~~~ -.. code:: ipython2 +.. code:: python J('2 10 pow') @@ -698,7 +698,7 @@ Math words ``sqr`` ``sqrt`` ~~~~~~~~~~~~~~~~ -.. code:: ipython2 +.. code:: python J('23 sqr') @@ -708,7 +708,7 @@ Math words 529 -.. code:: ipython2 +.. code:: python J('23 sqrt') @@ -721,7 +721,7 @@ Math words ``++`` ``succ`` ``--`` ``pred`` ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -.. code:: ipython2 +.. code:: python J('1 ++') @@ -731,7 +731,7 @@ Math words 2 -.. code:: ipython2 +.. code:: python J('1 --') @@ -744,7 +744,7 @@ Math words ``<<`` ``lshift`` ``>>`` ``rshift`` ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -.. code:: ipython2 +.. code:: python J('8 1 <<') @@ -754,7 +754,7 @@ Math words 16 -.. code:: ipython2 +.. code:: python J('8 1 >>') @@ -767,7 +767,7 @@ Math words ``average`` ~~~~~~~~~~~ -.. code:: ipython2 +.. code:: python J('[1 2 3 5] average') @@ -780,7 +780,7 @@ Math words ``range`` ``range_to_zero`` ``down_to_zero`` ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -.. code:: ipython2 +.. code:: python J('5 range') @@ -790,7 +790,7 @@ Math words [4 3 2 1 0] -.. code:: ipython2 +.. code:: python J('5 range_to_zero') @@ -800,7 +800,7 @@ Math words [0 1 2 3 4 5] -.. code:: ipython2 +.. code:: python J('5 down_to_zero') @@ -813,7 +813,7 @@ Math words ``product`` ~~~~~~~~~~~ -.. code:: ipython2 +.. code:: python J('[1 2 3 5] product') @@ -826,7 +826,7 @@ Math words ``sum`` ~~~~~~~ -.. code:: ipython2 +.. code:: python J('[1 2 3 5] sum') @@ -839,7 +839,7 @@ Math words ``min`` ~~~~~~~ -.. code:: ipython2 +.. code:: python J('[1 2 3 5] min') @@ -852,7 +852,7 @@ Math words ``gcd`` ~~~~~~~ -.. code:: ipython2 +.. code:: python J('45 30 gcd') @@ -868,7 +868,7 @@ Math words If we represent fractions as a quoted pair of integers [q d] this word reduces them to their ... least common factors or whatever. -.. code:: ipython2 +.. code:: python J('[45 30] least_fraction') @@ -878,7 +878,7 @@ reduces them to their ... least common factors or whatever. [3 2] -.. code:: ipython2 +.. code:: python J('[23 12] least_fraction') @@ -896,7 +896,7 @@ Logic and Comparison Get the Boolean value of the item on the top of the stack. -.. code:: ipython2 +.. code:: python J('23 truthy') @@ -906,7 +906,7 @@ Get the Boolean value of the item on the top of the stack. True -.. code:: ipython2 +.. code:: python J('[] truthy') # Python semantics. @@ -916,7 +916,7 @@ Get the Boolean value of the item on the top of the stack. False -.. code:: ipython2 +.. code:: python J('0 truthy') @@ -930,7 +930,7 @@ Get the Boolean value of the item on the top of the stack. ? == dup truthy -.. code:: ipython2 +.. code:: python V('23 ?') @@ -944,7 +944,7 @@ Get the Boolean value of the item on the top of the stack. 23 True . -.. code:: ipython2 +.. code:: python J('[] ?') @@ -954,7 +954,7 @@ Get the Boolean value of the item on the top of the stack. [] False -.. code:: ipython2 +.. code:: python J('0 ?') @@ -967,7 +967,7 @@ Get the Boolean value of the item on the top of the stack. ``&`` ``and`` ~~~~~~~~~~~~~ -.. code:: ipython2 +.. code:: python J('23 9 &') @@ -980,7 +980,7 @@ Get the Boolean value of the item on the top of the stack. ``!=`` ``<>`` ``ne`` ~~~~~~~~~~~~~~~~~~~~ -.. code:: ipython2 +.. code:: python J('23 9 !=') @@ -996,7 +996,7 @@ Get the Boolean value of the item on the top of the stack. ``^`` ``xor`` ~~~~~~~~~~~~~ -.. code:: ipython2 +.. code:: python J('1 1 ^') @@ -1006,7 +1006,7 @@ Get the Boolean value of the item on the top of the stack. 0 -.. code:: ipython2 +.. code:: python J('1 0 ^') @@ -1022,7 +1022,7 @@ Miscellaneous ``help`` ~~~~~~~~ -.. code:: ipython2 +.. code:: python J('[help] help') @@ -1036,7 +1036,7 @@ Miscellaneous ``parse`` ~~~~~~~~~ -.. code:: ipython2 +.. code:: python J('[parse] help') @@ -1047,7 +1047,7 @@ Miscellaneous -.. code:: ipython2 +.. code:: python J('1 "2 [3] dup" parse') @@ -1062,7 +1062,7 @@ Miscellaneous Evaluate a quoted Joy sequence. -.. code:: ipython2 +.. code:: python J('[1 2 dup + +] run') @@ -1078,7 +1078,7 @@ Combinators ``app1`` ``app2`` ``app3`` ~~~~~~~~~~~~~~~~~~~~~~~~~~ -.. code:: ipython2 +.. code:: python J('[app1] help') @@ -1095,7 +1095,7 @@ Combinators -.. code:: ipython2 +.. code:: python J('10 4 [sqr *] app1') @@ -1105,7 +1105,7 @@ Combinators 10 160 -.. code:: ipython2 +.. code:: python J('10 3 4 [sqr *] app2') @@ -1115,7 +1115,7 @@ Combinators 10 90 160 -.. code:: ipython2 +.. code:: python J('[app2] help') @@ -1131,7 +1131,7 @@ Combinators -.. code:: ipython2 +.. code:: python J('10 2 3 4 [sqr *] app3') @@ -1159,7 +1159,7 @@ Example, ``range``: range == [0 <=] [1 - dup] anamorphism -.. code:: ipython2 +.. code:: python J('3 [0 <=] [1 - dup] anamorphism') @@ -1172,7 +1172,7 @@ Example, ``range``: ``branch`` ~~~~~~~~~~ -.. code:: ipython2 +.. code:: python J('3 4 1 [+] [*] branch') @@ -1182,7 +1182,7 @@ Example, ``range``: 12 -.. code:: ipython2 +.. code:: python J('3 4 0 [+] [*] branch') @@ -1217,7 +1217,7 @@ in terms of ``app2``: cleave == [i] app2 [popd] dip -.. code:: ipython2 +.. code:: python J('10 2 [+] [-] cleave') @@ -1230,7 +1230,7 @@ in terms of ``app2``: ``dip`` ``dipd`` ``dipdd`` ~~~~~~~~~~~~~~~~~~~~~~~~~~ -.. code:: ipython2 +.. code:: python J('1 2 3 4 5 [+] dip') @@ -1240,7 +1240,7 @@ in terms of ``app2``: 1 2 7 5 -.. code:: ipython2 +.. code:: python J('1 2 3 4 5 [+] dipd') @@ -1250,7 +1250,7 @@ in terms of ``app2``: 1 5 4 5 -.. code:: ipython2 +.. code:: python J('1 2 3 4 5 [+] dipdd') @@ -1270,7 +1270,7 @@ Expects a quoted program ``[Q]`` on the stack and some item under it, n [Q] dupdip == n Q n -.. code:: ipython2 +.. code:: python V('23 [++] dupdip *') # N(N + 1) @@ -1289,7 +1289,7 @@ Expects a quoted program ``[Q]`` on the stack and some item under it, ``genrec`` ``primrec`` ~~~~~~~~~~~~~~~~~~~~~~ -.. code:: ipython2 +.. code:: python J('[genrec] help') @@ -1343,7 +1343,7 @@ Expects a quoted program ``[Q]`` on the stack and some item under it, -.. code:: ipython2 +.. code:: python J('3 [1 <=] [] [dup --] [i *] genrec') @@ -1356,7 +1356,7 @@ Expects a quoted program ``[Q]`` on the stack and some item under it, ``i`` ~~~~~ -.. code:: ipython2 +.. code:: python V('1 2 3 [+ +] i') @@ -1380,7 +1380,7 @@ Expects a quoted program ``[Q]`` on the stack and some item under it, [predicate] [then] [else] ifte -.. code:: ipython2 +.. code:: python J('1 2 [1] [+] [*] ifte') @@ -1390,7 +1390,7 @@ Expects a quoted program ``[Q]`` on the stack and some item under it, 3 -.. code:: ipython2 +.. code:: python J('1 2 [0] [+] [*] ifte') @@ -1403,7 +1403,7 @@ Expects a quoted program ``[Q]`` on the stack and some item under it, ``infra`` ~~~~~~~~~ -.. code:: ipython2 +.. code:: python V('1 2 3 [4 5 6] [* +] infra') @@ -1426,7 +1426,7 @@ Expects a quoted program ``[Q]`` on the stack and some item under it, ``loop`` ~~~~~~~~ -.. code:: ipython2 +.. code:: python J('[loop] help') @@ -1445,7 +1445,7 @@ Expects a quoted program ``[Q]`` on the stack and some item under it, -.. code:: ipython2 +.. code:: python V('3 dup [1 - dup] loop') @@ -1477,7 +1477,7 @@ Expects a quoted program ``[Q]`` on the stack and some item under it, ``map`` ``pam`` ~~~~~~~~~~~~~~~ -.. code:: ipython2 +.. code:: python J('10 [1 2 3] [*] map') @@ -1487,7 +1487,7 @@ Expects a quoted program ``[Q]`` on the stack and some item under it, 10 [10 20 30] -.. code:: ipython2 +.. code:: python J('10 5 [[*][/][+][-]] pam') @@ -1503,7 +1503,7 @@ Expects a quoted program ``[Q]`` on the stack and some item under it, Run a quoted program enforcing `arity `__. -.. code:: ipython2 +.. code:: python J('1 2 3 4 5 [+] nullary') @@ -1513,7 +1513,7 @@ Run a quoted program enforcing 1 2 3 4 5 9 -.. code:: ipython2 +.. code:: python J('1 2 3 4 5 [+] unary') @@ -1523,7 +1523,7 @@ Run a quoted program enforcing 1 2 3 4 9 -.. code:: ipython2 +.. code:: python J('1 2 3 4 5 [+] binary') # + has arity 2 so this is technically pointless... @@ -1533,7 +1533,7 @@ Run a quoted program enforcing 1 2 3 9 -.. code:: ipython2 +.. code:: python J('1 2 3 4 5 [+] ternary') @@ -1546,7 +1546,7 @@ Run a quoted program enforcing ``step`` ~~~~~~~~ -.. code:: ipython2 +.. code:: python J('[step] help') @@ -1574,7 +1574,7 @@ Run a quoted program enforcing -.. code:: ipython2 +.. code:: python V('0 [1 2 3] [+] step') @@ -1603,7 +1603,7 @@ Run a quoted program enforcing ``times`` ~~~~~~~~~ -.. code:: ipython2 +.. code:: python V('3 2 1 2 [+] times') @@ -1627,7 +1627,7 @@ Run a quoted program enforcing ``b`` ~~~~~ -.. code:: ipython2 +.. code:: python J('[b] help') @@ -1641,7 +1641,7 @@ Run a quoted program enforcing -.. code:: ipython2 +.. code:: python V('1 2 [3] [4] b') @@ -1665,7 +1665,7 @@ Run a quoted program enforcing [predicate] [body] while -.. code:: ipython2 +.. code:: python J('3 [0 >] [dup --] while') @@ -1678,7 +1678,7 @@ Run a quoted program enforcing ``x`` ~~~~~ -.. code:: ipython2 +.. code:: python J('[x] help') @@ -1693,7 +1693,7 @@ Run a quoted program enforcing -.. code:: ipython2 +.. code:: python V('1 [2] [i 3] x') # Kind of a pointless example. @@ -1720,7 +1720,7 @@ Implements `**Laws of Form** over quote-only datastructures (that is, datastructures that consist soley of containers, without strings or numbers or anything else.) -.. code:: ipython2 +.. code:: python J('[] void') @@ -1730,7 +1730,7 @@ soley of containers, without strings or numbers or anything else.) False -.. code:: ipython2 +.. code:: python J('[[]] void') @@ -1740,7 +1740,7 @@ soley of containers, without strings or numbers or anything else.) True -.. code:: ipython2 +.. code:: python J('[[][[]]] void') @@ -1750,7 +1750,7 @@ soley of containers, without strings or numbers or anything else.) True -.. code:: ipython2 +.. code:: python J('[[[]][[][]]] void') diff --git a/docs/sphinx_docs/_build/html/_sources/notebooks/Derivatives_of_Regular_Expressions.rst.txt b/docs/sphinx_docs/_build/html/_sources/notebooks/Derivatives_of_Regular_Expressions.rst.txt index 29dc9fb..bbcbb73 100644 --- a/docs/sphinx_docs/_build/html/_sources/notebooks/Derivatives_of_Regular_Expressions.rst.txt +++ b/docs/sphinx_docs/_build/html/_sources/notebooks/Derivatives_of_Regular_Expressions.rst.txt @@ -76,7 +76,7 @@ E.g.: Implementation -------------- -.. code:: ipython2 +.. code:: python from functools import partial as curry from itertools import product @@ -86,7 +86,7 @@ Implementation The empty set and the set of just the empty string. -.. code:: ipython2 +.. code:: python phi = frozenset() # ϕ y = frozenset({''}) # λ @@ -101,7 +101,7 @@ alphabet with two symbols (if you had to.) I chose the names ``O`` and ``l`` (uppercase “o” and lowercase “L”) to look like ``0`` and ``1`` (zero and one) respectively. -.. code:: ipython2 +.. code:: python syms = O, l = frozenset({'0'}), frozenset({'1'}) @@ -123,7 +123,7 @@ expression* is one of: Where ``R`` and ``S`` stand for *regular expressions*. -.. code:: ipython2 +.. code:: python AND, CONS, KSTAR, NOT, OR = 'and cons * not or'.split() # Tags are just strings. @@ -133,7 +133,7 @@ only, these datastructures are immutable. String Representation of RE Datastructures ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -.. code:: ipython2 +.. code:: python def stringy(re): ''' @@ -175,11 +175,11 @@ Match anything. Often spelled “.” I = (0|1)* -.. code:: ipython2 +.. code:: python I = (KSTAR, (OR, O, l)) -.. code:: ipython2 +.. code:: python print stringy(I) @@ -201,14 +201,14 @@ The example expression from Brzozowski: Note that it contains one of everything. -.. code:: ipython2 +.. code:: python a = (CONS, I, (CONS, l, (CONS, l, (CONS, l, I)))) b = (CONS, I, (CONS, O, l)) c = (CONS, l, (KSTAR, l)) it = (AND, a, (NOT, (OR, b, c))) -.. code:: ipython2 +.. code:: python print stringy(it) @@ -223,7 +223,7 @@ Note that it contains one of everything. Let’s get that auxiliary predicate function ``δ`` out of the way. -.. code:: ipython2 +.. code:: python def nully(R): ''' @@ -263,7 +263,7 @@ This is the straightforward version with no “compaction”. It works fine, but does waaaay too much work because the expressions grow each derivation. -.. code:: ipython2 +.. code:: python def D(symbol): @@ -308,7 +308,7 @@ derivation. Compaction Rules ~~~~~~~~~~~~~~~~ -.. code:: ipython2 +.. code:: python def _compaction_rule(relation, one, zero, a, b): return ( @@ -320,7 +320,7 @@ Compaction Rules An elegant symmetry. -.. code:: ipython2 +.. code:: python # R ∧ I = I ∧ R = R # R ∧ ϕ = ϕ ∧ R = ϕ @@ -341,7 +341,7 @@ We can save re-processing by remembering results we have already computed. RE datastructures are immutable and the ``derv()`` functions are *pure* so this is fine. -.. code:: ipython2 +.. code:: python class Memo(object): @@ -365,7 +365,7 @@ With “Compaction” This version uses the rules above to perform compaction. It keeps the expressions from growing too large. -.. code:: ipython2 +.. code:: python def D_compaction(symbol): @@ -414,7 +414,7 @@ Let’s try it out… (FIXME: redo.) -.. code:: ipython2 +.. code:: python o, z = D_compaction('0'), D_compaction('1') REs = set() @@ -605,20 +605,20 @@ You can see the one-way nature of the ``g`` state and the ``hij`` “trap” in the way that the ``.111.`` on the left-hand side of the ``&`` disappears once it has been matched. -.. code:: ipython2 +.. code:: python from collections import defaultdict from pprint import pprint from string import ascii_lowercase -.. code:: ipython2 +.. code:: python d0, d1 = D_compaction('0'), D_compaction('1') ``explore()`` ~~~~~~~~~~~~~ -.. code:: ipython2 +.. code:: python def explore(re): @@ -645,7 +645,7 @@ disappears once it has been matched. return table, accepting -.. code:: ipython2 +.. code:: python table, accepting = explore(it) table @@ -678,7 +678,7 @@ disappears once it has been matched. -.. code:: ipython2 +.. code:: python accepting @@ -697,7 +697,7 @@ Generate Diagram Once we have the FSM table and the set of accepting states we can generate the diagram above. -.. code:: ipython2 +.. code:: python _template = '''\ digraph finite_state_machine { @@ -722,7 +722,7 @@ generate the diagram above. ) ) -.. code:: ipython2 +.. code:: python print make_graph(table, accepting) @@ -776,7 +776,7 @@ Trampoline Function Python has no GOTO statement but we can fake it with a “trampoline” function. -.. code:: ipython2 +.. code:: python def trampoline(input_, jump_from, accepting): I = iter(input_) @@ -793,7 +793,7 @@ Stream Functions Little helpers to process the iterator of our data (a “stream” of “1” and “0” characters, not bits.) -.. code:: ipython2 +.. code:: python getch = lambda I: int(next(I)) @@ -816,7 +816,7 @@ code. (You have to imagine that these are GOTO statements in C or branches in assembly and that the state names are branch destination labels.) -.. code:: ipython2 +.. code:: python a = lambda I: c if getch(I) else b b = lambda I: _0(I) or d @@ -833,12 +833,12 @@ Note that the implementations of ``h`` and ``g`` are identical ergo ``h = g`` and we could eliminate one in the code but ``h`` is an accepting state and ``g`` isn’t. -.. code:: ipython2 +.. code:: python def acceptable(input_): return trampoline(input_, a, {h, i}) -.. code:: ipython2 +.. code:: python for n in range(2**5): s = bin(n)[2:] diff --git a/docs/sphinx_docs/_build/html/_sources/notebooks/Developing.rst.txt b/docs/sphinx_docs/_build/html/_sources/notebooks/Developing.rst.txt index 5b9314b..556225a 100644 --- a/docs/sphinx_docs/_build/html/_sources/notebooks/Developing.rst.txt +++ b/docs/sphinx_docs/_build/html/_sources/notebooks/Developing.rst.txt @@ -12,7 +12,7 @@ As an example of developing a program in Joy let's take the first problem from t Find the sum of all the multiples of 3 or 5 below 1000. -.. code:: ipython2 +.. code:: python from notebook_preamble import J, V, define @@ -22,11 +22,11 @@ Sum a range filtered by a predicate Let's create a predicate that returns ``True`` if a number is a multiple of 3 or 5 and ``False`` otherwise. -.. code:: ipython2 +.. code:: python define('P == [3 % not] dupdip 5 % not or') -.. code:: ipython2 +.. code:: python V('80 P') @@ -108,11 +108,11 @@ the counter to the running sum. This function will do that: PE1.1 == + [+] dupdip -.. code:: ipython2 +.. code:: python define('PE1.1 == + [+] dupdip') -.. code:: ipython2 +.. code:: python V('0 0 3 PE1.1') @@ -131,7 +131,7 @@ the counter to the running sum. This function will do that: 3 3 . -.. code:: ipython2 +.. code:: python V('0 0 [3 2 1 3 1 2 3] [PE1.1] step') @@ -219,7 +219,7 @@ total to 60. How many multiples to sum? ^^^^^^^^^^^^^^^^^^^^^^^^^^ -.. code:: ipython2 +.. code:: python 1000 / 15 @@ -232,7 +232,7 @@ How many multiples to sum? -.. code:: ipython2 +.. code:: python 66 * 15 @@ -245,7 +245,7 @@ How many multiples to sum? -.. code:: ipython2 +.. code:: python 1000 - 990 @@ -260,7 +260,7 @@ How many multiples to sum? We only want the terms *less than* 1000. -.. code:: ipython2 +.. code:: python 999 - 990 @@ -276,11 +276,11 @@ We only want the terms *less than* 1000. That means we want to run the full list of numbers sixty-six times to get to 990 and then the first four numbers 3 2 1 3 to get to 999. -.. code:: ipython2 +.. code:: python define('PE1 == 0 0 66 [[3 2 1 3 1 2 3] [PE1.1] step] times [3 2 1 3] [PE1.1] step pop') -.. code:: ipython2 +.. code:: python J('PE1') @@ -305,7 +305,7 @@ integer terms from the list. 3 2 1 3 1 2 3 0b 11 10 01 11 01 10 11 == 14811 -.. code:: ipython2 +.. code:: python 0b11100111011011 @@ -318,11 +318,11 @@ integer terms from the list. -.. code:: ipython2 +.. code:: python define('PE1.2 == [3 & PE1.1] dupdip 2 >>') -.. code:: ipython2 +.. code:: python V('0 0 14811 PE1.2') @@ -349,7 +349,7 @@ integer terms from the list. 3 3 3702 . -.. code:: ipython2 +.. code:: python V('3 3 3702 PE1.2') @@ -376,7 +376,7 @@ integer terms from the list. 8 5 925 . -.. code:: ipython2 +.. code:: python V('0 0 14811 7 [PE1.2] times pop') @@ -518,11 +518,11 @@ integer terms from the list. And so we have at last: -.. code:: ipython2 +.. code:: python define('PE1 == 0 0 66 [14811 7 [PE1.2] times pop] times 14811 4 [PE1.2] times popop') -.. code:: ipython2 +.. code:: python J('PE1') @@ -542,17 +542,17 @@ Let's refactor 14811 n [PE1.2] times pop n 14811 swap [PE1.2] times pop -.. code:: ipython2 +.. code:: python define('PE1.3 == 14811 swap [PE1.2] times pop') Now we can simplify the definition above: -.. code:: ipython2 +.. code:: python define('PE1 == 0 0 66 [7 PE1.3] times 4 PE1.3 pop') -.. code:: ipython2 +.. code:: python J('PE1') @@ -581,11 +581,11 @@ then four more. In the *Generator Programs* notebook we derive a generator that can be repeatedly driven by the ``x`` combinator to produce a stream of the seven numbers repeating over and over again. -.. code:: ipython2 +.. code:: python define('PE1.terms == [0 swap [dup [pop 14811] [] branch [3 &] dupdip 2 >>] dip rest cons]') -.. code:: ipython2 +.. code:: python J('PE1.terms 21 [x] times') @@ -598,7 +598,7 @@ produce a stream of the seven numbers repeating over and over again. We know from above that we need sixty-six times seven then four more terms to reach up to but not over one thousand. -.. code:: ipython2 +.. code:: python J('7 66 * 4 +') @@ -611,7 +611,7 @@ terms to reach up to but not over one thousand. Here they are... ~~~~~~~~~~~~~~~~ -.. code:: ipython2 +.. code:: python J('PE1.terms 466 [x] times pop') @@ -624,7 +624,7 @@ Here they are... ...and they do sum to 999. ~~~~~~~~~~~~~~~~~~~~~~~~~~ -.. code:: ipython2 +.. code:: python J('[PE1.terms 466 [x] times pop] run sum') @@ -638,7 +638,7 @@ Now we can use ``PE1.1`` to accumulate the terms as we go, and then ``pop`` the generator and the counter from the stack when we're done, leaving just the sum. -.. code:: ipython2 +.. code:: python J('0 0 PE1.terms 466 [x [PE1.1] dip] times popop') @@ -654,7 +654,7 @@ A little further analysis renders iteration unnecessary. Consider finding the sum of the positive integers less than or equal to ten. -.. code:: ipython2 +.. code:: python J('[10 9 8 7 6 5 4 3 2 1] sum') @@ -686,11 +686,11 @@ positive integers is: (The formula also works for odd values of N, I'll leave that to you if you want to work it out or you can take my word for it.) -.. code:: ipython2 +.. code:: python define('F == dup ++ * 2 floordiv') -.. code:: ipython2 +.. code:: python V('10 F') @@ -727,7 +727,7 @@ And ending with: If we reverse one of these two blocks and sum pairs... -.. code:: ipython2 +.. code:: python J('[3 5 6 9 10 12 15] reverse [978 980 981 984 985 987 990] zip') @@ -737,7 +737,7 @@ If we reverse one of these two blocks and sum pairs... [[978 15] [980 12] [981 10] [984 9] [985 6] [987 5] [990 3]] -.. code:: ipython2 +.. code:: python J('[3 5 6 9 10 12 15] reverse [978 980 981 984 985 987 990] zip [sum] map') @@ -750,7 +750,7 @@ If we reverse one of these two blocks and sum pairs... (Interesting that the sequence of seven numbers appears again in the rightmost digit of each term.) -.. code:: ipython2 +.. code:: python J('[ 3 5 6 9 10 12 15] reverse [978 980 981 984 985 987 990] zip [sum] map sum') @@ -771,7 +771,7 @@ additional unpaired terms between 990 and 1000: So we can give the "sum of all the multiples of 3 or 5 below 1000" like so: -.. code:: ipython2 +.. code:: python J('6945 33 * [993 995 996 999] cons sum') diff --git a/docs/sphinx_docs/_build/html/_sources/notebooks/Generator_Programs.rst.txt b/docs/sphinx_docs/_build/html/_sources/notebooks/Generator_Programs.rst.txt index 55e1679..a59df18 100644 --- a/docs/sphinx_docs/_build/html/_sources/notebooks/Generator_Programs.rst.txt +++ b/docs/sphinx_docs/_build/html/_sources/notebooks/Generator_Programs.rst.txt @@ -3,7 +3,7 @@ Using ``x`` to Generate Values Cf. jp-reprod.html -.. code:: ipython2 +.. code:: python from notebook_preamble import J, V, define @@ -57,7 +57,7 @@ We can make a generator for the Natural numbers (0, 1, 2, …) by using Let’s try it: -.. code:: ipython2 +.. code:: python V('[0 swap [dup ++] dip rest cons] x') @@ -81,7 +81,7 @@ Let’s try it: After one application of ``x`` the quoted program contains ``1`` and ``0`` is below it on the stack. -.. code:: ipython2 +.. code:: python J('[0 swap [dup ++] dip rest cons] x x x x x pop') @@ -94,11 +94,11 @@ After one application of ``x`` the quoted program contains ``1`` and ``direco`` ---------- -.. code:: ipython2 +.. code:: python define('direco == dip rest cons') -.. code:: ipython2 +.. code:: python V('[0 swap [dup ++] direco] x') @@ -149,13 +149,13 @@ Reading from the bottom up: G == [direco] cons [swap] swap concat cons G == [direco] cons [swap] swoncat cons -.. code:: ipython2 +.. code:: python define('G == [direco] cons [swap] swoncat cons') Let’s try it out: -.. code:: ipython2 +.. code:: python J('0 [dup ++] G') @@ -165,7 +165,7 @@ Let’s try it out: [0 swap [dup ++] direco] -.. code:: ipython2 +.. code:: python J('0 [dup ++] G x x x pop') @@ -178,7 +178,7 @@ Let’s try it out: Powers of 2 ~~~~~~~~~~~ -.. code:: ipython2 +.. code:: python J('1 [dup 1 <<] G x x x x x x x x x pop') @@ -194,7 +194,7 @@ Powers of 2 If we have one of these quoted programs we can drive it using ``times`` with the ``x`` combinator. -.. code:: ipython2 +.. code:: python J('23 [dup ++] G 5 [x] times') @@ -226,11 +226,11 @@ int: And pick them off by masking with 3 (binary 11) and then shifting the int right two bits. -.. code:: ipython2 +.. code:: python define('PE1.1 == dup [3 &] dip 2 >>') -.. code:: ipython2 +.. code:: python V('14811 PE1.1') @@ -252,7 +252,7 @@ int right two bits. If we plug ``14811`` and ``[PE1.1]`` into our generator form… -.. code:: ipython2 +.. code:: python J('14811 [PE1.1] G') @@ -264,7 +264,7 @@ If we plug ``14811`` and ``[PE1.1]`` into our generator form… …we get a generator that works for seven cycles before it reaches zero: -.. code:: ipython2 +.. code:: python J('[14811 swap [PE1.1] direco] 7 [x] times') @@ -280,11 +280,11 @@ Reset at Zero We need a function that checks if the int has reached zero and resets it if so. -.. code:: ipython2 +.. code:: python define('PE1.1.check == dup [pop 14811] [] branch') -.. code:: ipython2 +.. code:: python J('14811 [PE1.1.check PE1.1] G') @@ -294,7 +294,7 @@ if so. [14811 swap [PE1.1.check PE1.1] direco] -.. code:: ipython2 +.. code:: python J('[14811 swap [PE1.1.check PE1.1] direco] 21 [x] times') @@ -316,7 +316,7 @@ In the PE1 problem we are asked to sum all the multiples of three and five less than 1000. It’s worked out that we need to use all seven numbers sixty-six times and then four more. -.. code:: ipython2 +.. code:: python J('7 66 * 4 +') @@ -328,7 +328,7 @@ numbers sixty-six times and then four more. If we drive our generator 466 times and sum the stack we get 999. -.. code:: ipython2 +.. code:: python J('[14811 swap [PE1.1.check PE1.1] direco] 466 [x] times') @@ -338,7 +338,7 @@ If we drive our generator 466 times and sum the stack we get 999. 3 2 1 3 1 2 3 3 2 1 3 1 2 3 3 2 1 3 1 2 3 3 2 1 3 1 2 3 3 2 1 3 1 2 3 3 2 1 3 1 2 3 3 2 1 3 1 2 3 3 2 1 3 1 2 3 3 2 1 3 1 2 3 3 2 1 3 1 2 3 3 2 1 3 1 2 3 3 2 1 3 1 2 3 3 2 1 3 1 2 3 3 2 1 3 1 2 3 3 2 1 3 1 2 3 3 2 1 3 1 2 3 3 2 1 3 1 2 3 3 2 1 3 1 2 3 3 2 1 3 1 2 3 3 2 1 3 1 2 3 3 2 1 3 1 2 3 3 2 1 3 1 2 3 3 2 1 3 1 2 3 3 2 1 3 1 2 3 3 2 1 3 1 2 3 3 2 1 3 1 2 3 3 2 1 3 1 2 3 3 2 1 3 1 2 3 3 2 1 3 1 2 3 3 2 1 3 1 2 3 3 2 1 3 1 2 3 3 2 1 3 1 2 3 3 2 1 3 1 2 3 3 2 1 3 1 2 3 3 2 1 3 1 2 3 3 2 1 3 1 2 3 3 2 1 3 1 2 3 3 2 1 3 1 2 3 3 2 1 3 1 2 3 3 2 1 3 1 2 3 3 2 1 3 1 2 3 3 2 1 3 1 2 3 3 2 1 3 1 2 3 3 2 1 3 1 2 3 3 2 1 3 1 2 3 3 2 1 3 1 2 3 3 2 1 3 1 2 3 3 2 1 3 1 2 3 3 2 1 3 1 2 3 3 2 1 3 1 2 3 3 2 1 3 1 2 3 3 2 1 3 1 2 3 3 2 1 3 1 2 3 3 2 1 3 1 2 3 3 2 1 3 1 2 3 3 2 1 3 1 2 3 3 2 1 3 1 2 3 3 2 1 3 1 2 3 3 2 1 3 1 2 3 3 2 1 3 1 2 3 3 2 1 3 1 2 3 3 2 1 3 1 2 3 3 2 1 3 1 2 3 3 2 1 3 1 2 3 3 2 1 3 1 2 3 3 2 1 3 1 2 3 3 2 1 3 [57 swap [PE1.1.check PE1.1] direco] -.. code:: ipython2 +.. code:: python J('[14811 swap [PE1.1.check PE1.1] direco] 466 [x] times pop enstacken sum') @@ -351,13 +351,13 @@ If we drive our generator 466 times and sum the stack we get 999. Project Euler Problem One ------------------------- -.. code:: ipython2 +.. code:: python define('PE1.2 == + dup [+] dip') Now we can add ``PE1.2`` to the quoted program given to ``G``. -.. code:: ipython2 +.. code:: python J('0 0 0 [PE1.1.check PE1.1] G 466 [x [PE1.2] dip] times popop') @@ -445,15 +445,15 @@ Putting it all together: F == + [popdd over] cons infra uncons fib_gen == [1 1 F] -.. code:: ipython2 +.. code:: python define('fib == + [popdd over] cons infra uncons') -.. code:: ipython2 +.. code:: python define('fib_gen == [1 1 fib]') -.. code:: ipython2 +.. code:: python J('fib_gen 10 [x] times') @@ -473,14 +473,14 @@ Now that we have a generator for the Fibonacci sequence, we need a function that adds a term in the sequence to a sum if it is even, and ``pop``\ s it otherwise. -.. code:: ipython2 +.. code:: python define('PE2.1 == dup 2 % [+] [pop] branch') And a predicate function that detects when the terms in the series “exceed four million”. -.. code:: ipython2 +.. code:: python define('>4M == 4000000 >') @@ -488,11 +488,11 @@ Now it’s straightforward to define ``PE2`` as a recursive function that generates terms in the Fibonacci sequence until they exceed four million and sums the even ones. -.. code:: ipython2 +.. code:: python define('PE2 == 0 fib_gen x [pop >4M] [popop] [[PE2.1] dip x] primrec') -.. code:: ipython2 +.. code:: python J('PE2') @@ -535,7 +535,7 @@ So the Fibonacci sequence considered in terms of just parity would be: Every third term is even. -.. code:: ipython2 +.. code:: python J('[1 0 fib] x x x') # To start the sequence with 1 1 2 3 instead of 1 2 3. @@ -547,7 +547,7 @@ Every third term is even. Drive the generator three times and ``popop`` the two odd terms. -.. code:: ipython2 +.. code:: python J('[1 0 fib] x x x [popop] dipd') @@ -557,11 +557,11 @@ Drive the generator three times and ``popop`` the two odd terms. 2 [3 2 fib] -.. code:: ipython2 +.. code:: python define('PE2.2 == x x x [popop] dipd') -.. code:: ipython2 +.. code:: python J('[1 0 fib] 10 [PE2.2] times') @@ -574,7 +574,7 @@ Drive the generator three times and ``popop`` the two odd terms. Replace ``x`` with our new driver function ``PE2.2`` and start our ``fib`` generator at ``1 0``. -.. code:: ipython2 +.. code:: python J('0 [1 0 fib] PE2.2 [pop >4M] [popop] [[PE2.1] dip PE2.2] primrec') @@ -593,11 +593,11 @@ modifications to the default ``x``? An Interesting Variation ------------------------ -.. code:: ipython2 +.. code:: python define('codireco == cons dip rest cons') -.. code:: ipython2 +.. code:: python V('[0 [dup ++] codireco] x') @@ -620,11 +620,11 @@ An Interesting Variation 0 [1 [dup ++] codireco] . -.. code:: ipython2 +.. code:: python define('G == [codireco] cons cons') -.. code:: ipython2 +.. code:: python J('230 [dup ++] G 5 [x] times pop') diff --git a/docs/sphinx_docs/_build/html/_sources/notebooks/Intro.rst.txt b/docs/sphinx_docs/_build/html/_sources/notebooks/Intro.rst.txt index b832048..73704cf 100644 --- a/docs/sphinx_docs/_build/html/_sources/notebooks/Intro.rst.txt +++ b/docs/sphinx_docs/_build/html/_sources/notebooks/Intro.rst.txt @@ -150,7 +150,7 @@ TBD (look in the :module: joy.parser module.) Examples ~~~~~~~~~~~ -.. code:: ipython2 +.. code:: python joy.parser.text_to_expression('1 2 3 4 5') # A simple sequence. @@ -160,7 +160,7 @@ Examples (1, (2, (3, (4, (5, ()))))) -.. code:: ipython2 +.. code:: python joy.parser.text_to_expression('[1 2 3] 4 5') # Three items, the first is a list with three items @@ -170,7 +170,7 @@ Examples ((1, (2, (3, ()))), (4, (5, ()))) -.. code:: ipython2 +.. code:: python joy.parser.text_to_expression('1 23 ["four" [-5.0] cons] 8888') # A mixed bag. cons is # a Symbol, no lookup at @@ -184,7 +184,7 @@ Examples -.. code:: ipython2 +.. code:: python joy.parser.text_to_expression('[][][][][]') # Five empty lists. @@ -197,7 +197,7 @@ Examples -.. code:: ipython2 +.. code:: python joy.parser.text_to_expression('[[[[[]]]]]') # Five nested lists. @@ -221,7 +221,7 @@ provide control-flow and higher-order operations. Many of the functions are defined in Python, like ``dip``: -.. code:: ipython2 +.. code:: python print inspect.getsource(joy.library.dip) @@ -239,7 +239,7 @@ 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. -.. code:: ipython2 +.. code:: python print joy.library.definitions diff --git a/docs/sphinx_docs/_build/html/_sources/notebooks/Ordered_Binary_Trees.rst.txt b/docs/sphinx_docs/_build/html/_sources/notebooks/Ordered_Binary_Trees.rst.txt index 569d665..a625ac3 100644 --- a/docs/sphinx_docs/_build/html/_sources/notebooks/Ordered_Binary_Trees.rst.txt +++ b/docs/sphinx_docs/_build/html/_sources/notebooks/Ordered_Binary_Trees.rst.txt @@ -36,7 +36,7 @@ implementation under the hood. (Where does the “type” come from? It has a contingent existence predicated on the disciplined use of these functions on otherwise undistinguished Joy datastructures.) -.. code:: ipython2 +.. code:: python from notebook_preamble import D, J, V, define, DefinitionWrapper @@ -87,11 +87,11 @@ Definition: Tree-new == swap [[] []] cons cons -.. code:: ipython2 +.. code:: python define('Tree-new == swap [[] []] cons cons') -.. code:: ipython2 +.. code:: python J('"v" "k" Tree-new') @@ -163,11 +163,11 @@ comparison operator: P < == pop roll> pop first < P == pop roll> pop first -.. code:: ipython2 +.. code:: python define('P == pop roll> pop first') -.. code:: ipython2 +.. code:: python J('["old_key" 23 [] []] 17 "new_key" ["..."] P') @@ -242,11 +242,11 @@ And so ``T`` is just: T == cons cons [dipdd] cons infra -.. code:: ipython2 +.. code:: python define('T == cons cons [dipdd] cons infra') -.. code:: ipython2 +.. code:: python J('["old_k" "old_value" "left" "right"] "new_value" "new_key" ["Tree-add"] T') @@ -266,7 +266,7 @@ This is very very similar to the above: [key_n value_n left right] value key [Tree-add] E [key_n value_n left right] value key [Tree-add] [P <] [Te] [Ee] ifte -.. code:: ipython2 +.. code:: python define('E == [P <] [Te] [Ee] ifte') @@ -278,11 +278,11 @@ instead of the right, so the only difference is that it must use Te == cons cons [dipd] cons infra -.. code:: ipython2 +.. code:: python define('Te == cons cons [dipd] cons infra') -.. code:: ipython2 +.. code:: python J('["old_k" "old_value" "left" "right"] "new_value" "new_key" ["Tree-add"] Te') @@ -320,11 +320,11 @@ Example: key new_value [ left right] cons cons [key new_value left right] -.. code:: ipython2 +.. code:: python define('Ee == pop swap roll< rest rest cons cons') -.. code:: ipython2 +.. code:: python J('["k" "old_value" "left" "right"] "new_value" "k" ["Tree-add"] Ee') @@ -355,14 +355,14 @@ Putting it all together: Tree-add == [popop not] [[pop] dipd Tree-new] [] [R] genrec -.. code:: ipython2 +.. code:: python define('Tree-add == [popop not] [[pop] dipd Tree-new] [] [[P >] [T] [E] ifte] genrec') Examples ~~~~~~~~ -.. code:: ipython2 +.. code:: python J('[] 23 "b" Tree-add') # Initial @@ -372,7 +372,7 @@ Examples ['b' 23 [] []] -.. code:: ipython2 +.. code:: python J('["b" 23 [] []] 88 "c" Tree-add') # Greater than @@ -382,7 +382,7 @@ Examples ['b' 23 [] ['c' 88 [] []]] -.. code:: ipython2 +.. code:: python J('["b" 23 [] []] 88 "a" Tree-add') # Less than @@ -392,7 +392,7 @@ Examples ['b' 23 ['a' 88 [] []] []] -.. code:: ipython2 +.. code:: python J('["b" 23 [] []] 88 "b" Tree-add') # Equal to @@ -402,7 +402,7 @@ Examples ['b' 88 [] []] -.. code:: ipython2 +.. code:: python J('[] 23 "b" Tree-add 88 "a" Tree-add 44 "c" Tree-add') # Series. @@ -412,7 +412,7 @@ Examples ['b' 23 ['a' 88 [] []] ['c' 44 [] []]] -.. code:: ipython2 +.. code:: python J('[] [[23 "b"] [88 "a"] [44 "c"]] [i Tree-add] step') @@ -444,7 +444,7 @@ values: ------------------------- a < b L -.. code:: ipython2 +.. code:: python J("1 0 ['G'] ['E'] ['L'] cmp") @@ -454,7 +454,7 @@ values: 'G' -.. code:: ipython2 +.. code:: python J("1 1 ['G'] ['E'] ['L'] cmp") @@ -464,7 +464,7 @@ values: 'E' -.. code:: ipython2 +.. code:: python J("0 1 ['G'] ['E'] ['L'] cmp") @@ -514,7 +514,7 @@ Or just: P == over [popop popop first] nullary -.. code:: ipython2 +.. code:: python define('P == over [popop popop first] nullary') @@ -541,11 +541,11 @@ to understand: Tree-add == [popop not] [[pop] dipd Tree-new] [] [P [T] [Ee] [Te] cmp] genrec -.. code:: ipython2 +.. code:: python define('Tree-add == [popop not] [[pop] dipd Tree-new] [] [P [T] [Ee] [Te] cmp] genrec') -.. code:: ipython2 +.. code:: python J('[] 23 "b" Tree-add 88 "a" Tree-add 44 "c" Tree-add') # Still works. @@ -685,14 +685,14 @@ Working backward: Tree-iter == [not] [pop] roll< [dupdip rest rest] cons [step] genrec -.. code:: ipython2 +.. code:: python define('Tree-iter == [not] [pop] roll< [dupdip rest rest] cons [step] genrec') Examples ~~~~~~~~ -.. code:: ipython2 +.. code:: python J('[] [foo] Tree-iter') # It doesn't matter what F is as it won't be used. @@ -702,7 +702,7 @@ Examples -.. code:: ipython2 +.. code:: python J("['b' 23 ['a' 88 [] []] ['c' 44 [] []]] [first] Tree-iter") @@ -712,7 +712,7 @@ Examples 'b' 'a' 'c' -.. code:: ipython2 +.. code:: python J("['b' 23 ['a' 88 [] []] ['c' 44 [] []]] [second] Tree-iter") @@ -731,7 +731,7 @@ to it will only occur once within it, and we can query it in `:math:`O(\log_2 N)` `__ time. -.. code:: ipython2 +.. code:: python J('[] [3 9 5 2 8 6 7 8 4] [0 swap Tree-add] step') @@ -741,11 +741,11 @@ time. [3 0 [2 0 [] []] [9 0 [5 0 [4 0 [] []] [8 0 [6 0 [] [7 0 [] []]] []]] []]] -.. code:: ipython2 +.. code:: python define('to_set == [] swap [0 swap Tree-add] step') -.. code:: ipython2 +.. code:: python J('[3 9 5 2 8 6 7 8 4] to_set') @@ -758,11 +758,11 @@ time. And with that we can write a little program ``unique`` to remove duplicate items from a list. -.. code:: ipython2 +.. code:: python define('unique == [to_set [first] Tree-iter] cons run') -.. code:: ipython2 +.. code:: python J('[3 9 3 5 2 9 8 8 8 6 2 7 8 4 3] unique') # Filter duplicate items. @@ -872,7 +872,7 @@ Let’s do a little semantic factoring: Now we can sort sequences. -.. code:: ipython2 +.. code:: python #define('Tree-iter-order == [not] [pop] [dup third] [[cons dip] dupdip [[first] dupdip] dip [rest rest rest first] dip i] genrec') @@ -892,7 +892,7 @@ Now we can sort sequences. -.. code:: ipython2 +.. code:: python J('[3 9 5 2 8 6 7 8 4] to_set Tree-iter-order') @@ -1070,7 +1070,7 @@ So: Tree-get == [pop not] swap [] [P [T>] [E] [T<] cmp] genrec -.. code:: ipython2 +.. code:: python # I don't want to deal with name conflicts with the above so I'm inlining everything here. # The original Joy system has "hide" which is a meta-command which allows you to use named @@ -1088,7 +1088,7 @@ So: ] genrec ''') -.. code:: ipython2 +.. code:: python J('["gary" 23 [] []] "mike" [popd " not in tree" +] Tree-get') @@ -1098,7 +1098,7 @@ So: 'mike not in tree' -.. code:: ipython2 +.. code:: python J('["gary" 23 [] []] "gary" [popop "err"] Tree-get') @@ -1108,7 +1108,7 @@ So: 23 -.. code:: ipython2 +.. code:: python J(''' @@ -1124,7 +1124,7 @@ So: 2 -.. code:: ipython2 +.. code:: python J(''' @@ -1500,7 +1500,7 @@ Refactoring By the standards of the code I’ve written so far, this is a *huge* Joy program. -.. code:: ipython2 +.. code:: python DefinitionWrapper.add_definitions(''' first_two == uncons uncons pop @@ -1519,7 +1519,7 @@ program. Tree-Delete == [pop not] [pop] [R0] [R1] genrec ''', D) -.. code:: ipython2 +.. code:: python J("['a' 23 [] ['b' 88 [] ['c' 44 [] []]]] 'c' Tree-Delete ") @@ -1529,7 +1529,7 @@ program. ['a' 23 [] ['b' 88 [] []]] -.. code:: ipython2 +.. code:: python J("['a' 23 [] ['b' 88 [] ['c' 44 [] []]]] 'b' Tree-Delete ") @@ -1539,7 +1539,7 @@ program. ['a' 23 [] ['c' 44 [] []]] -.. code:: ipython2 +.. code:: python J("['a' 23 [] ['b' 88 [] ['c' 44 [] []]]] 'a' Tree-Delete ") @@ -1549,7 +1549,7 @@ program. ['b' 88 [] ['c' 44 [] []]] -.. code:: ipython2 +.. code:: python J("['a' 23 [] ['b' 88 [] ['c' 44 [] []]]] 'der' Tree-Delete ") @@ -1559,7 +1559,7 @@ program. ['a' 23 [] ['b' 88 [] ['c' 44 [] []]]] -.. code:: ipython2 +.. code:: python J('[] [4 2 3 1 6 7 5 ] [0 swap Tree-add] step') @@ -1569,7 +1569,7 @@ program. [4 0 [2 0 [1 0 [] []] [3 0 [] []]] [6 0 [5 0 [] []] [7 0 [] []]]] -.. code:: ipython2 +.. code:: python J("[4 0 [2 0 [1 0 [] []] [3 0 [] []]] [6 0 [5 0 [] []] [7 0 [] []]]] 3 Tree-Delete ") @@ -1579,7 +1579,7 @@ program. [4 0 [2 0 [1 0 [] []] []] [6 0 [5 0 [] []] [7 0 [] []]]] -.. code:: ipython2 +.. code:: python J("[4 0 [2 0 [1 0 [] []] [3 0 [] []]] [6 0 [5 0 [] []] [7 0 [] []]]] 4 Tree-Delete ") diff --git a/docs/sphinx_docs/_build/html/_sources/notebooks/Quadratic.rst.txt b/docs/sphinx_docs/_build/html/_sources/notebooks/Quadratic.rst.txt index 3262e84..5afb8e2 100644 --- a/docs/sphinx_docs/_build/html/_sources/notebooks/Quadratic.rst.txt +++ b/docs/sphinx_docs/_build/html/_sources/notebooks/Quadratic.rst.txt @@ -1,4 +1,4 @@ -.. code:: ipython2 +.. code:: python from notebook_preamble import J, V, define @@ -81,13 +81,13 @@ the variables: The three arguments are to the left, so we can “chop off” everything to the right and say it’s the definition of the ``quadratic`` function: -.. code:: ipython2 +.. code:: python define('quadratic == over [[[neg] dupdip sqr 4] dipd * * - sqrt pm] dip 2 * [/] cons app2') Let’s try it out: -.. code:: ipython2 +.. code:: python J('3 1 1 quadratic') @@ -102,7 +102,7 @@ lines are the ``dip`` and ``dipd`` combinators building the main program by incorporating the values on the stack. Then that program runs and you get the results. This is pretty typical of Joy code. -.. code:: ipython2 +.. code:: python V('-5 1 4 quadratic') diff --git a/docs/sphinx_docs/_build/html/_sources/notebooks/Recursion_Combinators.rst.txt b/docs/sphinx_docs/_build/html/_sources/notebooks/Recursion_Combinators.rst.txt index 9159882..65c4480 100644 --- a/docs/sphinx_docs/_build/html/_sources/notebooks/Recursion_Combinators.rst.txt +++ b/docs/sphinx_docs/_build/html/_sources/notebooks/Recursion_Combinators.rst.txt @@ -1,4 +1,4 @@ -.. code:: ipython2 +.. code:: python from notebook_preamble import D, DefinitionWrapper, J, V, define @@ -80,7 +80,7 @@ is a recursive function ``H :: A -> C`` that converts a value of type It may be helpful to see this function implemented in imperative Python code. -.. code:: ipython2 +.. code:: python def hylomorphism(c, F, P, G): '''Return a hylomorphism function H.''' @@ -185,7 +185,7 @@ the left so we have a definition for ``hylomorphism``: hylomorphism == [unit [pop] swoncat] dipd [dip] swoncat genrec -.. code:: ipython2 +.. code:: python define('hylomorphism == [unit [pop] swoncat] dipd [dip] swoncat genrec') @@ -203,13 +203,13 @@ To sum a range of integers from 0 to *n* - 1: - ``[G]`` is ``[-- dup]`` - ``[F]`` is ``[+]`` -.. code:: ipython2 +.. code:: python define('triangular_number == [1 <=] 0 [-- dup] [+] hylomorphism') Let’s try it: -.. code:: ipython2 +.. code:: python J('5 triangular_number') @@ -219,7 +219,7 @@ Let’s try it: 10 -.. code:: ipython2 +.. code:: python J('[0 1 2 3 4 5 6] [triangular_number] map') @@ -405,11 +405,11 @@ Each of the above variations can be used to make four slightly different H1 == [P] [pop c] [G] [dip F] genrec == [0 <=] [pop []] [-- dup] [dip swons] genrec -.. code:: ipython2 +.. code:: python define('range == [0 <=] [] [-- dup] [swons] hylomorphism') -.. code:: ipython2 +.. code:: python J('5 range') @@ -427,11 +427,11 @@ Each of the above variations can be used to make four slightly different H2 == c swap [P] [pop] [G [F] dip] primrec == [] swap [0 <=] [pop] [-- dup [swons] dip] primrec -.. code:: ipython2 +.. code:: python define('range_reverse == [] swap [0 <=] [pop] [-- dup [swons] dip] primrec') -.. code:: ipython2 +.. code:: python J('5 range_reverse') @@ -449,11 +449,11 @@ Each of the above variations can be used to make four slightly different H3 == [P] [pop c] [[G] dupdip] [dip F] genrec == [0 <=] [pop []] [[--] dupdip] [dip swons] genrec -.. code:: ipython2 +.. code:: python define('ranger == [0 <=] [pop []] [[--] dupdip] [dip swons] genrec') -.. code:: ipython2 +.. code:: python J('5 ranger') @@ -471,11 +471,11 @@ Each of the above variations can be used to make four slightly different H4 == c swap [P] [pop] [[F] dupdip G ] primrec == [] swap [0 <=] [pop] [[swons] dupdip --] primrec -.. code:: ipython2 +.. code:: python define('ranger_reverse == [] swap [0 <=] [pop] [[swons] dupdip --] primrec') -.. code:: ipython2 +.. code:: python J('5 ranger_reverse') @@ -501,7 +501,7 @@ and makes some new value. C == [not] c [uncons swap] [F] hylomorphism -.. code:: ipython2 +.. code:: python define('swuncons == uncons swap') # Awkward name. @@ -511,11 +511,11 @@ An example of a catamorphism is the sum function. sum == [not] 0 [swuncons] [+] hylomorphism -.. code:: ipython2 +.. code:: python define('sum == [not] 0 [swuncons] [+] hylomorphism') -.. code:: ipython2 +.. code:: python J('[5 4 3 2 1] sum') @@ -531,7 +531,7 @@ The ``step`` combinator The ``step`` combinator will usually be better to use than ``catamorphism``. -.. code:: ipython2 +.. code:: python J('[step] help') @@ -560,11 +560,11 @@ The ``step`` combinator will usually be better to use than -.. code:: ipython2 +.. code:: python define('sum == 0 swap [+] step') -.. code:: ipython2 +.. code:: python J('[5 4 3 2 1] sum') @@ -592,11 +592,11 @@ With: G == -- P == 1 <= -.. code:: ipython2 +.. code:: python define('factorial == 1 swap [1 <=] [pop] [[*] dupdip --] primrec') -.. code:: ipython2 +.. code:: python J('5 factorial') @@ -635,11 +635,11 @@ We would use: G == rest dup P == not -.. code:: ipython2 +.. code:: python define('tails == [] swap [not] [pop] [rest dup [swons] dip] primrec') -.. code:: ipython2 +.. code:: python J('[1 2 3] tails') diff --git a/docs/sphinx_docs/_build/html/_sources/notebooks/Replacing.rst.txt b/docs/sphinx_docs/_build/html/_sources/notebooks/Replacing.rst.txt index 0f90445..02ecb3b 100644 --- a/docs/sphinx_docs/_build/html/_sources/notebooks/Replacing.rst.txt +++ b/docs/sphinx_docs/_build/html/_sources/notebooks/Replacing.rst.txt @@ -9,14 +9,14 @@ dictionary. However, there’s no function that does that. Adding a new function to the dictionary is a meta-interpreter action, you have to do it in Python, not Joy. -.. code:: ipython2 +.. code:: python from notebook_preamble import D, J, V A long trace ------------ -.. code:: ipython2 +.. code:: python V('[23 18] average') @@ -81,7 +81,7 @@ An efficient ``sum`` function is already in the library. But for ``size`` we can use a “compiled” version hand-written in Python to speed up evaluation and make the trace more readable. -.. code:: ipython2 +.. code:: python from joy.library import SimpleFunctionWrapper from joy.utils.stack import iter_stack @@ -99,7 +99,7 @@ up evaluation and make the trace more readable. Now we replace the old version in the dictionary with the new version, and re-evaluate the expression. -.. code:: ipython2 +.. code:: python D['size'] = size @@ -108,7 +108,7 @@ A shorter trace You can see that ``size`` now executes in a single step. -.. code:: ipython2 +.. code:: python V('[23 18] average') diff --git a/docs/sphinx_docs/_build/html/_sources/notebooks/Treestep.rst.txt b/docs/sphinx_docs/_build/html/_sources/notebooks/Treestep.rst.txt index 6b9081f..7f273d8 100644 --- a/docs/sphinx_docs/_build/html/_sources/notebooks/Treestep.rst.txt +++ b/docs/sphinx_docs/_build/html/_sources/notebooks/Treestep.rst.txt @@ -148,11 +148,11 @@ Working backwards: Define ``treestep`` ------------------- -.. code:: ipython2 +.. code:: python from notebook_preamble import D, J, V, define, DefinitionWrapper -.. code:: ipython2 +.. code:: python DefinitionWrapper.add_definitions(''' @@ -173,7 +173,7 @@ all nodes in a tree with this function: sumtree == [pop 0] [] [sum +] treestep -.. code:: ipython2 +.. code:: python define('sumtree == [pop 0] [] [sum +] treestep') @@ -185,7 +185,7 @@ Running this function on an empty tree value gives zero: ------------------------------------ 0 -.. code:: ipython2 +.. code:: python J('[] sumtree') # Empty tree. @@ -205,7 +205,7 @@ Running it on a non-empty node: n m + n+m -.. code:: ipython2 +.. code:: python J('[23] sumtree') # No child trees. @@ -215,7 +215,7 @@ Running it on a non-empty node: 23 -.. code:: ipython2 +.. code:: python J('[23 []] sumtree') # Child tree, empty. @@ -225,7 +225,7 @@ Running it on a non-empty node: 23 -.. code:: ipython2 +.. code:: python J('[23 [2 [4]] [3]] sumtree') # Non-empty child trees. @@ -235,7 +235,7 @@ Running it on a non-empty node: 32 -.. code:: ipython2 +.. code:: python J('[23 [2 [8] [9]] [3] [4 []]] sumtree') # Etc... @@ -245,7 +245,7 @@ Running it on a non-empty node: 49 -.. code:: ipython2 +.. code:: python J('[23 [2 [8] [9]] [3] [4 []]] [pop 0] [] [cons sum] treestep') # Alternate "spelling". @@ -255,7 +255,7 @@ Running it on a non-empty node: 49 -.. code:: ipython2 +.. code:: python J('[23 [2 [8] [9]] [3] [4 []]] [] [pop 23] [cons] treestep') # Replace each node. @@ -265,7 +265,7 @@ Running it on a non-empty node: [23 [23 [23] [23]] [23] [23 []]] -.. code:: ipython2 +.. code:: python J('[23 [2 [8] [9]] [3] [4 []]] [] [pop 1] [cons] treestep') @@ -275,7 +275,7 @@ Running it on a non-empty node: [1 [1 [1] [1]] [1] [1 []]] -.. code:: ipython2 +.. code:: python J('[23 [2 [8] [9]] [3] [4 []]] [] [pop 1] [cons] treestep sumtree') @@ -285,7 +285,7 @@ Running it on a non-empty node: 6 -.. code:: ipython2 +.. code:: python J('[23 [2 [8] [9]] [3] [4 []]] [pop 0] [pop 1] [sum +] treestep') # Combine replace and sum into one function. @@ -295,7 +295,7 @@ Running it on a non-empty node: 6 -.. code:: ipython2 +.. code:: python J('[4 [3 [] [7]]] [pop 0] [pop 1] [sum +] treestep') # Combine replace and sum into one function. @@ -339,7 +339,7 @@ Traversal This doesn’t quite work: -.. code:: ipython2 +.. code:: python J('[[3 0] [[2 0] [][]] [[9 0] [[5 0] [[4 0] [][]] [[8 0] [[6 0] [] [[7 0] [][]]][]]][]]] ["B"] [first] [i] treestep') @@ -369,7 +369,7 @@ So: [] [first] [flatten cons] treestep -.. code:: ipython2 +.. code:: python J('[[3 0] [[2 0] [] []] [[9 0] [[5 0] [[4 0] [] []] [[8 0] [[6 0] [] [[7 0] [] []]] []]] []]] [] [first] [flatten cons] treestep') @@ -401,7 +401,7 @@ So: [] [i roll< swons concat] [first] treestep -.. code:: ipython2 +.. code:: python J('[[3 0] [[2 0] [] []] [[9 0] [[5 0] [[4 0] [] []] [[8 0] [[6 0] [] [[7 0] [] []]] []]] []]] [] [uncons pop] [i roll< swons concat] treestep') @@ -429,7 +429,7 @@ Plugging in our BTree structure: [key value] N [left right] [K] C -.. code:: ipython2 +.. code:: python J('[["key" "value"] ["left"] ["right"] ] ["B"] ["N"] ["C"] treegrind') @@ -444,7 +444,7 @@ Plugging in our BTree structure: Iteration through the nodes -.. code:: ipython2 +.. code:: python J('[[3 0] [[2 0] [] []] [[9 0] [[5 0] [[4 0] [] []] [[8 0] [[6 0] [] [[7 0] [] []]] []]] []]] [pop] ["N"] [step] treegrind') @@ -456,7 +456,7 @@ Iteration through the nodes Sum the nodes’ keys. -.. code:: ipython2 +.. code:: python J('0 [[3 0] [[2 0] [] []] [[9 0] [[5 0] [[4 0] [] []] [[8 0] [[6 0] [] [[7 0] [] []]] []]] []]] [pop] [first +] [step] treegrind') @@ -468,7 +468,7 @@ Sum the nodes’ keys. Rebuild the tree using ``map`` (imitating ``treestep``.) -.. code:: ipython2 +.. code:: python J('[[3 0] [[2 0] [] []] [[9 0] [[5 0] [[4 0] [] []] [[8 0] [[6 0] [] [[7 0] [] []]] []]] []]] [] [[100 +] infra] [map cons] treegrind') @@ -574,7 +574,7 @@ Putting it together To me, that seems simpler than the ``genrec`` version. -.. code:: ipython2 +.. code:: python DefinitionWrapper.add_definitions(''' @@ -587,7 +587,7 @@ To me, that seems simpler than the ``genrec`` version. ''', D) -.. code:: ipython2 +.. code:: python J('''\ @@ -603,7 +603,7 @@ To me, that seems simpler than the ``genrec`` version. 15 -.. code:: ipython2 +.. code:: python J('''\ diff --git a/docs/sphinx_docs/_build/html/_sources/notebooks/TypeChecking.rst.txt b/docs/sphinx_docs/_build/html/_sources/notebooks/TypeChecking.rst.txt index cd85c67..4e70a1a 100644 --- a/docs/sphinx_docs/_build/html/_sources/notebooks/TypeChecking.rst.txt +++ b/docs/sphinx_docs/_build/html/_sources/notebooks/TypeChecking.rst.txt @@ -1,7 +1,7 @@ Type Checking ============= -.. code:: ipython2 +.. code:: python import logging, sys @@ -11,7 +11,7 @@ Type Checking level=logging.INFO, ) -.. code:: ipython2 +.. code:: python from joy.utils.types import ( doc_from_stack_effect, @@ -22,7 +22,7 @@ Type Checking JoyTypeError, ) -.. code:: ipython2 +.. code:: python D = FUNCTIONS.copy() del D['product'] @@ -31,7 +31,7 @@ Type Checking An Example ---------- -.. code:: ipython2 +.. code:: python fi, fo = infer(pop, swap, rolldown, rrest, ccons)[0] @@ -46,7 +46,7 @@ An Example 40 ([a4 a5 ...1] a3 a2 a1 -- [a2 a3 ...1]) ∘ -.. code:: ipython2 +.. code:: python print doc_from_stack_effect(fi, fo) @@ -56,13 +56,13 @@ An Example ([a4 a5 ...1] a3 a2 a1 -- [a2 a3 ...1]) -.. code:: ipython2 +.. code:: python from joy.parser import text_to_expression from joy.utils.stack import stack_to_string -.. code:: ipython2 +.. code:: python e = text_to_expression('0 1 2 [3 4]') # reverse order print stack_to_string(e) @@ -73,7 +73,7 @@ An Example [3 4] 2 1 0 -.. code:: ipython2 +.. code:: python u = unify(e, fi)[0] u @@ -87,7 +87,7 @@ An Example -.. code:: ipython2 +.. code:: python g = reify(u, (fi, fo)) print doc_from_stack_effect(*g) @@ -101,11 +101,11 @@ An Example Unification Works “in Reverse” ------------------------------ -.. code:: ipython2 +.. code:: python e = text_to_expression('[2 3]') -.. code:: ipython2 +.. code:: python u = unify(e, fo)[0] # output side, not input side u @@ -119,7 +119,7 @@ Unification Works “in Reverse” -.. code:: ipython2 +.. code:: python g = reify(u, (fi, fo)) print doc_from_stack_effect(*g) @@ -133,7 +133,7 @@ Unification Works “in Reverse” Failing a Check --------------- -.. code:: ipython2 +.. code:: python fi, fo = infer(dup, mul)[0] @@ -146,7 +146,7 @@ Failing a Check 31 (i1 -- i2) ∘ -.. code:: ipython2 +.. code:: python e = text_to_expression('"two"') print stack_to_string(e) @@ -157,7 +157,7 @@ Failing a Check 'two' -.. code:: ipython2 +.. code:: python try: unify(e, fi) diff --git a/docs/sphinx_docs/_build/html/_sources/notebooks/Types.rst.txt b/docs/sphinx_docs/_build/html/_sources/notebooks/Types.rst.txt index 4c91600..8ca737d 100644 --- a/docs/sphinx_docs/_build/html/_sources/notebooks/Types.rst.txt +++ b/docs/sphinx_docs/_build/html/_sources/notebooks/Types.rst.txt @@ -184,7 +184,7 @@ Compiling ``pop∘swap∘roll<`` The simplest way to “compile” this function would be something like: -.. code:: ipython2 +.. code:: python def poswrd(s, e, d): return rolldown(*swap(*pop(s, e, d))) @@ -200,7 +200,7 @@ Looking ahead for a moment, from the stack effect comment: We should be able to directly write out a Python function like: -.. code:: ipython2 +.. code:: python def poswrd(stack): (_, (a, (b, (c, stack)))) = stack @@ -393,7 +393,7 @@ And there you have it, the stack effect for From this stack effect comment it should be possible to construct the following Python code: -.. code:: ipython2 +.. code:: python def F(stack): (_, (d, (c, ((a, (b, S0)), stack)))) = stack @@ -408,7 +408,7 @@ Representing Stack Effect Comments in Python I’m going to use pairs of tuples of type descriptors, which will be integers or tuples of type descriptors: -.. code:: ipython2 +.. code:: python roll_dn = (1, 2, 3), (2, 3, 1) @@ -419,7 +419,7 @@ integers or tuples of type descriptors: ``compose()`` ~~~~~~~~~~~~~ -.. code:: ipython2 +.. code:: python def compose(f, g): @@ -465,7 +465,7 @@ integers or tuples of type descriptors: ``unify()`` ~~~~~~~~~~~ -.. code:: ipython2 +.. code:: python def unify(u, v, s=None): if s is None: @@ -483,7 +483,7 @@ integers or tuples of type descriptors: ``update()`` ~~~~~~~~~~~~ -.. code:: ipython2 +.. code:: python def update(s, term): if not isinstance(term, tuple): @@ -493,7 +493,7 @@ integers or tuples of type descriptors: ``relabel()`` ~~~~~~~~~~~~~ -.. code:: ipython2 +.. code:: python def relabel(left, right): return left, _1000(right) @@ -517,7 +517,7 @@ integers or tuples of type descriptors: ``delabel()`` ~~~~~~~~~~~~~ -.. code:: ipython2 +.. code:: python def delabel(f): s = {u: i for i, u in enumerate(sorted(_unique(f)))} @@ -551,7 +551,7 @@ At last we put it all together in a function ``C()`` that accepts two stack effect comments and returns their composition (or raises and exception if they can’t be composed due to type conflicts.) -.. code:: ipython2 +.. code:: python def C(f, g): f, g = relabel(f, g) @@ -560,7 +560,7 @@ exception if they can’t be composed due to type conflicts.) Let’s try it out. -.. code:: ipython2 +.. code:: python C(pop, swap) @@ -573,7 +573,7 @@ Let’s try it out. -.. code:: ipython2 +.. code:: python C(C(pop, swap), roll_dn) @@ -586,7 +586,7 @@ Let’s try it out. -.. code:: ipython2 +.. code:: python C(swap, roll_dn) @@ -599,7 +599,7 @@ Let’s try it out. -.. code:: ipython2 +.. code:: python C(pop, C(swap, roll_dn)) @@ -612,7 +612,7 @@ Let’s try it out. -.. code:: ipython2 +.. code:: python poswrd = reduce(C, (pop, swap, roll_dn)) poswrd @@ -633,13 +633,13 @@ Here’s that trick to represent functions like ``rest`` and ``cons`` that manipulate stacks. We use a cons-list of tuples and give the tails their own numbers. Then everything above already works. -.. code:: ipython2 +.. code:: python rest = ((1, 2),), (2,) cons = (1, 2), ((1, 2),) -.. code:: ipython2 +.. code:: python C(poswrd, rest) @@ -671,7 +671,7 @@ The translation table, if you will, would be: 0: 0, } -.. code:: ipython2 +.. code:: python F = reduce(C, (pop, swap, roll_dn, rest, rest, cons, cons)) @@ -699,11 +699,11 @@ Dealing with ``cons`` and ``uncons`` However, if we try to compose e.g. ``cons`` and ``uncons`` it won’t work: -.. code:: ipython2 +.. code:: python uncons = ((1, 2),), (1, 2) -.. code:: ipython2 +.. code:: python try: C(cons, uncons) @@ -723,7 +723,7 @@ The problem is that the ``unify()`` function as written doesn’t handle the case when both terms are tuples. We just have to add a clause to deal with this recursively: -.. code:: ipython2 +.. code:: python def unify(u, v, s=None): if s is None: @@ -753,7 +753,7 @@ deal with this recursively: return s -.. code:: ipython2 +.. code:: python C(cons, uncons) @@ -771,7 +771,7 @@ Part III: Compiling Yin Functions Now consider the Python function we would like to derive: -.. code:: ipython2 +.. code:: python def F_python(stack): (_, (d, (c, ((a, (b, S0)), stack)))) = stack @@ -779,7 +779,7 @@ Now consider the Python function we would like to derive: And compare it to the input stack effect comment tuple we just computed: -.. code:: ipython2 +.. code:: python F[0] @@ -816,7 +816,7 @@ Eh? And the return tuple -.. code:: ipython2 +.. code:: python F[1] @@ -848,7 +848,7 @@ Python Identifiers We want to substitute Python identifiers for the integers. I’m going to repurpose ``joy.parser.Symbol`` class for this: -.. code:: ipython2 +.. code:: python from collections import defaultdict from joy.parser import Symbol @@ -874,7 +874,7 @@ effect comment tuples to reasonable text format. There are some details in how this code works that related to stuff later in the notebook, so you should skip it for now and read it later if you’re interested. -.. code:: ipython2 +.. code:: python def doc_from_stack_effect(inputs, outputs): return '(%s--%s)' % ( @@ -914,7 +914,7 @@ Now we can write a compiler function to emit Python source code. (The underscore suffix distiguishes it from the built-in ``compile()`` function.) -.. code:: ipython2 +.. code:: python def compile_(name, f, doc=None): if doc is None: @@ -932,7 +932,7 @@ function.) Here it is in action: -.. code:: ipython2 +.. code:: python source = compile_('F', F) @@ -949,7 +949,7 @@ Here it is in action: Compare: -.. code:: ipython2 +.. code:: python def F_python(stack): (_, (d, (c, ((a, (b, S0)), stack)))) = stack @@ -957,7 +957,7 @@ Compare: Next steps: -.. code:: ipython2 +.. code:: python L = {} @@ -976,16 +976,16 @@ Next steps: Let’s try it out: -.. code:: ipython2 +.. code:: python from notebook_preamble import D, J, V from joy.library import SimpleFunctionWrapper -.. code:: ipython2 +.. code:: python D['F'] = SimpleFunctionWrapper(L['F']) -.. code:: ipython2 +.. code:: python J('[4 5 ...] 2 3 1 F') @@ -1012,7 +1012,7 @@ Compiling Library Functions We can use ``compile_()`` to generate many primitives in the library from their stack effect comments: -.. code:: ipython2 +.. code:: python def defs(): @@ -1036,7 +1036,7 @@ from their stack effect comments: return locals() -.. code:: ipython2 +.. code:: python for name, stack_effect_comment in sorted(defs().items()): print @@ -1205,7 +1205,7 @@ Python class hierarchy of Joy types and use the ``issubclass()`` method to establish domain ordering, as well as other handy behaviour that will make it fairly easy to reuse most of the code above. -.. code:: ipython2 +.. code:: python class AnyJoyType(object): @@ -1251,14 +1251,14 @@ make it fairly easy to reuse most of the code above. Mess with it a little: -.. code:: ipython2 +.. code:: python from itertools import permutations “Any” types can be specialized to numbers and stacks, but not vice versa: -.. code:: ipython2 +.. code:: python for a, b in permutations((A[0], N[0], S[0]), 2): print a, '>=', b, '->', a >= b @@ -1278,7 +1278,7 @@ Our crude `Numerical Tower `__ of *numbers* > *floats* > *integers* works as well (but we’re not going to use it yet): -.. code:: ipython2 +.. code:: python for a, b in permutations((A[0], N[0], FloatJoyType(0), IntJoyType(0)), 2): print a, '>=', b, '->', a >= b @@ -1303,13 +1303,13 @@ Tower `__ of *numbers* > Typing ``sqr`` ~~~~~~~~~~~~~~ -.. code:: ipython2 +.. code:: python dup = (A[1],), (A[1], A[1]) mul = (N[1], N[2]), (N[3],) -.. code:: ipython2 +.. code:: python dup @@ -1322,7 +1322,7 @@ Typing ``sqr`` -.. code:: ipython2 +.. code:: python mul @@ -1340,7 +1340,7 @@ Modifying the Inferencer Re-labeling still works fine: -.. code:: ipython2 +.. code:: python foo = relabel(dup, mul) @@ -1361,7 +1361,7 @@ Re-labeling still works fine: The ``delabel()`` function needs an overhaul. It now has to keep track of how many labels of each domain it has “seen”. -.. code:: ipython2 +.. code:: python from collections import Counter @@ -1383,7 +1383,7 @@ of how many labels of each domain it has “seen”. return tuple(delabel(inner, seen, c) for inner in f) -.. code:: ipython2 +.. code:: python delabel(foo) @@ -1399,7 +1399,7 @@ of how many labels of each domain it has “seen”. ``unify()`` version 3 ^^^^^^^^^^^^^^^^^^^^^ -.. code:: ipython2 +.. code:: python def unify(u, v, s=None): if s is None: @@ -1449,7 +1449,7 @@ of how many labels of each domain it has “seen”. Rewrite the stack effect comments: -.. code:: ipython2 +.. code:: python def defs(): @@ -1503,11 +1503,11 @@ Rewrite the stack effect comments: return locals() -.. code:: ipython2 +.. code:: python DEFS = defs() -.. code:: ipython2 +.. code:: python for name, stack_effect_comment in sorted(DEFS.items()): print name, '=', doc_from_stack_effect(*stack_effect_comment) @@ -1543,14 +1543,14 @@ Rewrite the stack effect comments: uncons = ([a1 .1.] -- a1 [.1.]) -.. code:: ipython2 +.. code:: python globals().update(DEFS) Compose ``dup`` and ``mul`` ^^^^^^^^^^^^^^^^^^^^^^^^^^^ -.. code:: ipython2 +.. code:: python C(dup, mul) @@ -1565,7 +1565,7 @@ Compose ``dup`` and ``mul`` Revisit the ``F`` function, works fine. -.. code:: ipython2 +.. code:: python F = reduce(C, (pop, swap, rolldown, rest, rest, cons, cons)) F @@ -1579,7 +1579,7 @@ Revisit the ``F`` function, works fine. -.. code:: ipython2 +.. code:: python print doc_from_stack_effect(*F) @@ -1592,12 +1592,12 @@ Revisit the ``F`` function, works fine. Some otherwise inefficient functions are no longer to be feared. We can also get the effect of combinators in some limited cases. -.. code:: ipython2 +.. code:: python def neato(*funcs): print doc_from_stack_effect(*reduce(C, funcs)) -.. code:: ipython2 +.. code:: python # e.g. [swap] dip neato(rollup, swap, rolldown) @@ -1608,7 +1608,7 @@ also get the effect of combinators in some limited cases. (a1 a2 a3 -- a2 a1 a3) -.. code:: ipython2 +.. code:: python # e.g. [popop] dipd neato(popdd, rolldown, pop) @@ -1619,7 +1619,7 @@ also get the effect of combinators in some limited cases. (a1 a2 a3 a4 -- a3 a4) -.. code:: ipython2 +.. code:: python # Reverse the order of the top three items. neato(rollup, swap) @@ -1636,7 +1636,7 @@ also get the effect of combinators in some limited cases. Because the type labels represent themselves as valid Python identifiers the ``compile_()`` function doesn’t need to generate them anymore: -.. code:: ipython2 +.. code:: python def compile_(name, f, doc=None): inputs, outputs = f @@ -1652,7 +1652,7 @@ the ``compile_()`` function doesn’t need to generate them anymore: %s = stack return %s''' % (name, doc, i, o) -.. code:: ipython2 +.. code:: python print compile_('F', F) @@ -1668,7 +1668,7 @@ the ``compile_()`` function doesn’t need to generate them anymore: But it cannot magically create new functions that involve e.g. math and such. Note that this is *not* a ``sqr`` function implementation: -.. code:: ipython2 +.. code:: python print compile_('sqr', C(dup, mul)) @@ -1696,7 +1696,7 @@ The functions that *can* be compiled are the ones that have only ``AnyJoyType`` and ``StackJoyType`` labels in their stack effect comments. We can write a function to check that: -.. code:: ipython2 +.. code:: python from itertools import imap @@ -1704,7 +1704,7 @@ comments. We can write a function to check that: def compilable(f): return isinstance(f, tuple) and all(imap(compilable, f)) or stacky(f) -.. code:: ipython2 +.. code:: python for name, stack_effect_comment in sorted(defs().items()): if compilable(stack_effect_comment): @@ -1828,7 +1828,7 @@ the “truthiness” of ``StackJoyType`` to false to let e.g. ``joy.utils.stack.concat`` work with our stack effect comment cons-list tuples.) -.. code:: ipython2 +.. code:: python def compose(f, g): (f_in, f_out), (g_in, g_out) = f, g @@ -1840,7 +1840,7 @@ tuples.) I don’t want to rewrite all the defs myself, so I’ll write a little conversion function instead. This is programmer’s laziness. -.. code:: ipython2 +.. code:: python def sequence_to_stack(seq, stack=StackJoyType(23)): for item in seq: stack = item, stack @@ -1854,7 +1854,7 @@ conversion function instead. This is programmer’s laziness. NEW_DEFS['swaack'] = (S[1], S[0]), (S[0], S[1]) globals().update(NEW_DEFS) -.. code:: ipython2 +.. code:: python C(stack, uncons) @@ -1867,7 +1867,7 @@ conversion function instead. This is programmer’s laziness. -.. code:: ipython2 +.. code:: python reduce(C, (stack, uncons, uncons)) @@ -1887,7 +1887,7 @@ The display function should be changed too. Clunky junk, but it will suffice for now. -.. code:: ipython2 +.. code:: python def doc_from_stack_effect(inputs, outputs): switch = [False] # Do we need to display the '...' for the rest of the main stack? @@ -1935,7 +1935,7 @@ Clunky junk, but it will suffice for now. a.append(end) return '[%s]' % ' '.join(a) -.. code:: ipython2 +.. code:: python for name, stack_effect_comment in sorted(NEW_DEFS.items()): print name, '=', doc_from_stack_effect(*stack_effect_comment) @@ -1973,7 +1973,7 @@ Clunky junk, but it will suffice for now. uncons = ([a1 .1.] -- a1 [.1.]) -.. code:: ipython2 +.. code:: python print ; print doc_from_stack_effect(*stack) print ; print doc_from_stack_effect(*C(stack, uncons)) @@ -1993,7 +1993,7 @@ Clunky junk, but it will suffice for now. (... a1 -- ... a1 [a1 ...]) -.. code:: ipython2 +.. code:: python print doc_from_stack_effect(*C(ccons, stack)) @@ -2003,7 +2003,7 @@ Clunky junk, but it will suffice for now. (... a2 a1 [.1.] -- ... [a2 a1 .1.] [[a2 a1 .1.] ...]) -.. code:: ipython2 +.. code:: python Q = C(ccons, stack) @@ -2024,7 +2024,7 @@ Clunky junk, but it will suffice for now. This makes the ``compile_()`` function pretty simple as the stack effect comments are now already in the form needed for the Python code: -.. code:: ipython2 +.. code:: python def compile_(name, f, doc=None): i, o = f @@ -2035,7 +2035,7 @@ comments are now already in the form needed for the Python code: %s = stack return %s''' % (name, doc, i, o) -.. code:: ipython2 +.. code:: python print compile_('Q', Q) @@ -2053,12 +2053,12 @@ comments are now already in the form needed for the Python code: -.. code:: ipython2 +.. code:: python unstack = (S[1], S[0]), S[1] enstacken = S[0], (S[0], S[1]) -.. code:: ipython2 +.. code:: python print doc_from_stack_effect(*unstack) @@ -2068,7 +2068,7 @@ comments are now already in the form needed for the Python code: ([.1.] --) -.. code:: ipython2 +.. code:: python print doc_from_stack_effect(*enstacken) @@ -2078,7 +2078,7 @@ comments are now already in the form needed for the Python code: (-- [.0.]) -.. code:: ipython2 +.. code:: python print doc_from_stack_effect(*C(cons, unstack)) @@ -2088,7 +2088,7 @@ comments are now already in the form needed for the Python code: (a1 [.1.] -- a1) -.. code:: ipython2 +.. code:: python print doc_from_stack_effect(*C(cons, enstacken)) @@ -2098,7 +2098,7 @@ comments are now already in the form needed for the Python code: (a1 [.1.] -- [[a1 .1.] .2.]) -.. code:: ipython2 +.. code:: python C(cons, unstack) @@ -2117,7 +2117,7 @@ Part VI: Multiple Stack Effects … -.. code:: ipython2 +.. code:: python class IntJoyType(NumberJoyType): prefix = 'i' @@ -2125,7 +2125,7 @@ Part VI: Multiple Stack Effects F = map(FloatJoyType, _R) I = map(IntJoyType, _R) -.. code:: ipython2 +.. code:: python muls = [ ((I[2], (I[1], S[0])), (I[3], S[0])), @@ -2134,7 +2134,7 @@ Part VI: Multiple Stack Effects ((F[2], (F[1], S[0])), (F[3], S[0])), ] -.. code:: ipython2 +.. code:: python for f in muls: print doc_from_stack_effect(*f) @@ -2148,7 +2148,7 @@ Part VI: Multiple Stack Effects (f1 f2 -- f3) -.. code:: ipython2 +.. code:: python for f in muls: try: @@ -2164,7 +2164,7 @@ Part VI: Multiple Stack Effects (a1 -- a1 a1) (f1 f2 -- f3) (f1 -- f2) -.. code:: ipython2 +.. code:: python from itertools import product @@ -2180,7 +2180,7 @@ Part VI: Multiple Stack Effects def MC(F, G): return sorted(set(meta_compose(F, G))) -.. code:: ipython2 +.. code:: python for f in MC([dup], [mul]): print doc_from_stack_effect(*f) @@ -2191,7 +2191,7 @@ Part VI: Multiple Stack Effects (n1 -- n2) -.. code:: ipython2 +.. code:: python for f in MC([dup], muls): print doc_from_stack_effect(*f) @@ -2264,7 +2264,7 @@ Giving us two unifiers: {c: a, d: b, .1.: .0.} {c: a, d: e, .1.: A* b .0.} -.. code:: ipython2 +.. code:: python class KleeneStar(object): @@ -2314,7 +2314,7 @@ Giving us two unifiers: Can now return multiple results… -.. code:: ipython2 +.. code:: python def unify(u, v, s=None): if s is None: @@ -2386,7 +2386,7 @@ Can now return multiple results… def stacky(thing): return thing.__class__ in {AnyJoyType, StackJoyType} -.. code:: ipython2 +.. code:: python a = (As[1], S[1]) a @@ -2400,7 +2400,7 @@ Can now return multiple results… -.. code:: ipython2 +.. code:: python b = (A[1], S[2]) b @@ -2414,7 +2414,7 @@ Can now return multiple results… -.. code:: ipython2 +.. code:: python for result in unify(b, a): print result, '->', update(result, a), update(result, b) @@ -2426,7 +2426,7 @@ Can now return multiple results… {a1: a10001, s2: (a1*, s1)} -> (a1*, s1) (a10001, (a1*, s1)) -.. code:: ipython2 +.. code:: python for result in unify(a, b): print result, '->', update(result, a), update(result, b) @@ -2446,7 +2446,7 @@ Can now return multiple results… (a1*, s1) [a1*] (a2, (a1*, s1)) [a2 a1*] -.. code:: ipython2 +.. code:: python sum_ = ((Ns[1], S[1]), S[0]), (N[0], S[0]) @@ -2458,7 +2458,7 @@ Can now return multiple results… ([n1* .1.] -- n0) -.. code:: ipython2 +.. code:: python f = (N[1], (N[2], (N[3], S[1]))), S[0] @@ -2470,7 +2470,7 @@ Can now return multiple results… (-- [n1 n2 n3 .1.]) -.. code:: ipython2 +.. code:: python for result in unify(sum_[0], f): print result, '->', update(result, sum_[1]) @@ -2489,7 +2489,7 @@ Can now return multiple results… This function has to be modified to yield multiple results. -.. code:: ipython2 +.. code:: python def compose(f, g): (f_in, f_out), (g_in, g_out) = f, g @@ -2501,7 +2501,7 @@ This function has to be modified to yield multiple results. -.. code:: ipython2 +.. code:: python def meta_compose(F, G): for f, g in product(F, G): @@ -2517,7 +2517,7 @@ This function has to be modified to yield multiple results. for fg in compose(f, g): yield delabel(fg) -.. code:: ipython2 +.. code:: python for f in MC([dup], muls): print doc_from_stack_effect(*f) @@ -2529,7 +2529,7 @@ This function has to be modified to yield multiple results. (i1 -- i2) -.. code:: ipython2 +.. code:: python @@ -2542,7 +2542,7 @@ This function has to be modified to yield multiple results. ([n1* .1.] -- [n1* .1.] n1) -.. code:: ipython2 +.. code:: python @@ -2556,7 +2556,7 @@ This function has to be modified to yield multiple results. (n1 [n1* .1.] -- n2) -.. code:: ipython2 +.. code:: python sum_ = (((N[1], (Ns[1], S[1])), S[0]), (N[0], S[0])) print doc_from_stack_effect(*cons), @@ -2571,7 +2571,7 @@ This function has to be modified to yield multiple results. (a1 [.1.] -- [a1 .1.]) ([n1 n1* .1.] -- n0) (n1 [n1* .1.] -- n2) -.. code:: ipython2 +.. code:: python a = (A[4], (As[1], (A[3], S[1]))) a @@ -2585,7 +2585,7 @@ This function has to be modified to yield multiple results. -.. code:: ipython2 +.. code:: python b = (A[1], (A[2], S[2])) b @@ -2599,7 +2599,7 @@ This function has to be modified to yield multiple results. -.. code:: ipython2 +.. code:: python for result in unify(b, a): print result @@ -2611,7 +2611,7 @@ This function has to be modified to yield multiple results. {a1: a4, s2: (a1*, (a3, s1)), a2: a10003} -.. code:: ipython2 +.. code:: python for result in unify(a, b): print result @@ -2681,7 +2681,7 @@ We need a type variable for Joy functions that can go in our expressions and be used by the hybrid inferencer/interpreter. They have to store a name and a list of stack effects. -.. code:: ipython2 +.. code:: python class FunctionJoyType(AnyJoyType): @@ -2703,14 +2703,14 @@ Specialized for Simple Functions and Combinators For non-combinator functions the stack effects list contains stack effect comments (represented by pairs of cons-lists as described above.) -.. code:: ipython2 +.. code:: python class SymbolJoyType(FunctionJoyType): prefix = 'F' For combinators the list contains Python functions. -.. code:: ipython2 +.. code:: python class CombinatorJoyType(FunctionJoyType): @@ -2731,7 +2731,7 @@ For combinators the list contains Python functions. For simple combinators that have only one effect (like ``dip``) you only need one function and it can be the combinator itself. -.. code:: ipython2 +.. code:: python import joy.library @@ -2741,7 +2741,7 @@ For combinators that can have more than one effect (like ``branch``) you have to write functions that each implement the action of one of the effects. -.. code:: ipython2 +.. code:: python def branch_true(stack, expression, dictionary): (then, (else_, (flag, stack))) = stack @@ -2771,7 +2771,7 @@ updated along with the stack effects after doing unification or we risk losing useful information. This was a straightforward, if awkward, modification to the call structure of ``meta_compose()`` et. al. -.. code:: ipython2 +.. code:: python ID = S[0], S[0] # Identity function. @@ -2833,7 +2833,7 @@ cruft to convert the definitions in ``DEFS`` to the new ``SymbolJoyType`` objects, and some combinators. Here is an example of output from the current code : -.. code:: ipython2 +.. code:: python 1/0 # (Don't try to run this cell! It's not going to work. This is "read only" code heh..) @@ -2956,7 +2956,7 @@ module. But if you’re interested in all that you should just use Prolog! Anyhow, type *checking* is a few easy steps away. -.. code:: ipython2 +.. code:: python def _ge(self, other): return (issubclass(other.__class__, self.__class__) diff --git a/docs/sphinx_docs/_build/html/_sources/notebooks/Zipper.rst.txt b/docs/sphinx_docs/_build/html/_sources/notebooks/Zipper.rst.txt index dc4f996..c44343a 100644 --- a/docs/sphinx_docs/_build/html/_sources/notebooks/Zipper.rst.txt +++ b/docs/sphinx_docs/_build/html/_sources/notebooks/Zipper.rst.txt @@ -10,7 +10,7 @@ Huet `__ out of sequences. -.. code:: ipython2 +.. code:: python J('[1 [2 [3 4 25 6] 7] 8]') @@ -54,14 +54,14 @@ show the trace so you can see how it works. If we were going to use these a lot it would make sense to write Python versions for efficiency, but see below. -.. code:: ipython2 +.. code:: python define('z-down == [] swap uncons swap') define('z-up == swons swap shunt') define('z-right == [swons] cons dip uncons swap') define('z-left == swons [uncons swap] dip swap') -.. code:: ipython2 +.. code:: python V('[1 [2 [3 4 25 6] 7] 8] z-down') @@ -77,7 +77,7 @@ but see below. [] [[2 [3 4 25 6] 7] 8] 1 . -.. code:: ipython2 +.. code:: python V('[] [[2 [3 4 25 6] 7] 8] 1 z-right') @@ -101,7 +101,7 @@ but see below. [1] [8] [2 [3 4 25 6] 7] . -.. code:: ipython2 +.. code:: python J('[1] [8] [2 [3 4 25 6] 7] z-down') @@ -111,7 +111,7 @@ but see below. [1] [8] [] [[3 4 25 6] 7] 2 -.. code:: ipython2 +.. code:: python J('[1] [8] [] [[3 4 25 6] 7] 2 z-right') @@ -121,7 +121,7 @@ but see below. [1] [8] [2] [7] [3 4 25 6] -.. code:: ipython2 +.. code:: python J('[1] [8] [2] [7] [3 4 25 6] z-down') @@ -131,7 +131,7 @@ but see below. [1] [8] [2] [7] [] [4 25 6] 3 -.. code:: ipython2 +.. code:: python J('[1] [8] [2] [7] [] [4 25 6] 3 z-right') @@ -141,7 +141,7 @@ but see below. [1] [8] [2] [7] [3] [25 6] 4 -.. code:: ipython2 +.. code:: python J('[1] [8] [2] [7] [3] [25 6] 4 z-right') @@ -151,7 +151,7 @@ but see below. [1] [8] [2] [7] [4 3] [6] 25 -.. code:: ipython2 +.. code:: python J('[1] [8] [2] [7] [4 3] [6] 25 sqr') @@ -161,7 +161,7 @@ but see below. [1] [8] [2] [7] [4 3] [6] 625 -.. code:: ipython2 +.. code:: python V('[1] [8] [2] [7] [4 3] [6] 625 z-up') @@ -184,7 +184,7 @@ but see below. [1] [8] [2] [7] [3 4 625 6] . -.. code:: ipython2 +.. code:: python J('[1] [8] [2] [7] [3 4 625 6] z-up') @@ -194,7 +194,7 @@ but see below. [1] [8] [2 [3 4 625 6] 7] -.. code:: ipython2 +.. code:: python J('[1] [8] [2 [3 4 625 6] 7] z-up') @@ -210,7 +210,7 @@ but see below. In Joy we have the ``dip`` and ``infra`` combinators which can “target” or “address” any particular item in a Joy tree structure. -.. code:: ipython2 +.. code:: python V('[1 [2 [3 4 25 6] 7] 8] [[[[[[sqr] dipd] infra] dip] infra] dip] infra') @@ -270,13 +270,13 @@ been embedded in a nested series of quoted programs, e.g.: The ``Z`` function isn’t hard to make. -.. code:: ipython2 +.. code:: python define('Z == [[] cons cons] step i') Here it is in action in a simplified scenario. -.. code:: ipython2 +.. code:: python V('1 [2 3 4] Z') @@ -314,7 +314,7 @@ Here it is in action in a simplified scenario. And here it is doing the main thing. -.. code:: ipython2 +.. code:: python J('[1 [2 [3 4 25 6] 7] 8] [sqr] [dip dip infra dip infra dip infra] Z') diff --git a/docs/sphinx_docs/_build/html/lib.html b/docs/sphinx_docs/_build/html/lib.html index 7783c89..03f9a10 100644 --- a/docs/sphinx_docs/_build/html/lib.html +++ b/docs/sphinx_docs/_build/html/lib.html @@ -35,7 +35,7 @@

Functions Grouped by, er, Function with Examples

-
from notebook_preamble import J, V
+
from notebook_preamble import J, V
 
@@ -48,7 +48,7 @@ static for the duration of the computation. This remains to be done but it’s “off the shelf” technology.)

clear

-
J('1 2 3 clear')
+
J('1 2 3 clear')
 
(nothing)
@@ -57,13 +57,13 @@ it’s “off the shelf” technology.)

dup dupd

-
J('1 2 3 dup')
+
J('1 2 3 dup')
 
1 2 3 3
 
-
J('1 2 3 dupd')
+
J('1 2 3 dupd')
 
1 2 2 3
@@ -74,27 +74,27 @@ it’s “off the shelf” technology.)

enstacken disenstacken stack unstack

(I may have these paired up wrong. I.e. disenstacken should be unstack and vice versa.)

-
J('1 2 3 enstacken') # Replace the stack with a quote of itself.
+
J('1 2 3 enstacken') # Replace the stack with a quote of itself.
 
[3 2 1]
 
-
J('4 5 6 [3 2 1] disenstacken')  # Unpack a list onto the stack.
+
J('4 5 6 [3 2 1] disenstacken')  # Unpack a list onto the stack.
 
4 5 6 3 2 1
 
-
J('1 2 3 stack')  # Get the stack on the stack.
+
J('1 2 3 stack')  # Get the stack on the stack.
 
1 2 3 [3 2 1]
 
-
J('1 2 3 [4 5 6] unstack')  # Replace the stack with the list on top.
-                            # The items appear reversed but they are not,
-                            # 4 is on the top of both the list and the stack.
+
J('1 2 3 [4 5 6] unstack')  # Replace the stack with the list on top.
+                            # The items appear reversed but they are not,
+                            # 4 is on the top of both the list and the stack.
 
6 5 4
@@ -103,19 +103,19 @@ it’s “off the shelf” technology.)

pop popd popop

-
J('1 2 3 pop')
+
J('1 2 3 pop')
 
1 2
 
-
J('1 2 3 popd')
+
J('1 2 3 popd')
 
1 3
 
-
J('1 2 3 popop')
+
J('1 2 3 popop')
 
1
@@ -126,13 +126,13 @@ it’s “off the shelf” technology.)

roll< rolldown roll> rollup

The “down” and “up” refer to the movement of two of the top three items (displacing the third.)

-
J('1 2 3 roll<')
+
J('1 2 3 roll<')
 
2 3 1
 
-
J('1 2 3 roll>')
+
J('1 2 3 roll>')
 
3 1 2
@@ -141,7 +141,7 @@ it’s “off the shelf” technology.)

swap

-
J('1 2 3 swap')
+
J('1 2 3 swap')
 
1 3 2
@@ -150,13 +150,13 @@ it’s “off the shelf” technology.)

tuck over

-
J('1 2 3 tuck')
+
J('1 2 3 tuck')
 
1 3 2 3
 
-
J('1 2 3 over')
+
J('1 2 3 over')
 
1 2 3 2
@@ -165,25 +165,25 @@ it’s “off the shelf” technology.)

unit quoted unquoted

-
J('1 2 3 unit')
+
J('1 2 3 unit')
 
1 2 [3]
 
-
J('1 2 3 quoted')
+
J('1 2 3 quoted')
 
1 [2] 3
 
-
J('1 [2] 3 unquoted')
+
J('1 [2] 3 unquoted')
 
1 2 3
 
-
V('1 [dup] 3 unquoted')  # Unquoting evaluates.  Be aware.
+
V('1 [dup] 3 unquoted')  # Unquoting evaluates.  Be aware.
 
              . 1 [dup] 3 unquoted
@@ -204,19 +204,19 @@ it’s “off the shelf” technology.)

List words

concat swoncat shunt

-
J('[1 2 3] [4 5 6] concat')
+
J('[1 2 3] [4 5 6] concat')
 
[1 2 3 4 5 6]
 
-
J('[1 2 3] [4 5 6] swoncat')
+
J('[1 2 3] [4 5 6] swoncat')
 
[4 5 6 1 2 3]
 
-
J('[1 2 3] [4 5 6] shunt')
+
J('[1 2 3] [4 5 6] shunt')
 
[6 5 4 1 2 3]
@@ -225,19 +225,19 @@ it’s “off the shelf” technology.)

cons swons uncons

-
J('1 [2 3] cons')
+
J('1 [2 3] cons')
 
[1 2 3]
 
-
J('[2 3] 1 swons')
+
J('[2 3] 1 swons')
 
[1 2 3]
 
-
J('[1 2 3] uncons')
+
J('[1 2 3] uncons')
 
1 [2 3]
@@ -246,25 +246,25 @@ it’s “off the shelf” technology.)

first second third rest

-
J('[1 2 3 4] first')
+
J('[1 2 3 4] first')
 
1
 
-
J('[1 2 3 4] second')
+
J('[1 2 3 4] second')
 
2
 
-
J('[1 2 3 4] third')
+
J('[1 2 3 4] third')
 
3
 
-
J('[1 2 3 4] rest')
+
J('[1 2 3 4] rest')
 
[2 3 4]
@@ -273,7 +273,7 @@ it’s “off the shelf” technology.)

flatten

-
J('[[1] [2 [3] 4] [5 6]] flatten')
+
J('[[1] [2 [3] 4] [5 6]] flatten')
 
[1 2 [3] 4 5 6]
@@ -283,31 +283,31 @@ it’s “off the shelf” technology.)

getitem at of drop take

at and getitem are the same function. of == swap at

-
J('[10 11 12 13 14] 2 getitem')
+
J('[10 11 12 13 14] 2 getitem')
 
12
 
-
J('[1 2 3 4] 0 at')
+
J('[1 2 3 4] 0 at')
 
1
 
-
J('2 [1 2 3 4] of')
+
J('2 [1 2 3 4] of')
 
3
 
-
J('[1 2 3 4] 2 drop')
+
J('[1 2 3 4] 2 drop')
 
[3 4]
 
-
J('[1 2 3 4] 2 take')  # reverses the order
+
J('[1 2 3 4] 2 take')  # reverses the order
 
[2 1]
@@ -317,7 +317,7 @@ it’s “off the shelf” technology.)

remove

-
J('[1 2 3 1 4] 1 remove')
+
J('[1 2 3 1 4] 1 remove')
 
[2 3 1 4]
@@ -326,7 +326,7 @@ it’s “off the shelf” technology.)

reverse

-
J('[1 2 3 4] reverse')
+
J('[1 2 3 4] reverse')
 
[4 3 2 1]
@@ -335,7 +335,7 @@ it’s “off the shelf” technology.)

size

-
J('[1 1 1 1] size')
+
J('[1 1 1 1] size')
 
4
@@ -347,7 +347,7 @@ it’s “off the shelf” technology.)

“Swap stack” swap the list on the top of the stack for the stack, and put the old stack on top of the new one. Think of it as a context switch. Niether of the lists/stacks change their order.

-
J('1 2 3 [4 5 6] swaack')
+
J('1 2 3 [4 5 6] swaack')
 
6 5 4 [3 2 1]
@@ -356,25 +356,25 @@ switch. Niether of the lists/stacks change their order.

choice select

-
J('23 9 1 choice')
+
J('23 9 1 choice')
 
9
 
-
J('23 9 0 choice')
+
J('23 9 0 choice')
 
23
 
-
J('[23 9 7] 1 select')  # select is basically getitem, should retire it?
+
J('[23 9 7] 1 select')  # select is basically getitem, should retire it?
 
9
 
-
J('[23 9 7] 0 select')
+
J('[23 9 7] 0 select')
 
23
@@ -383,13 +383,13 @@ switch. Niether of the lists/stacks change their order.

zip

-
J('[1 2 3] [6 5 4] zip')
+
J('[1 2 3] [6 5 4] zip')
 
[[6 1] [5 2] [4 3]]
 
-
J('[1 2 3] [6 5 4] zip [sum] map')
+
J('[1 2 3] [6 5 4] zip [sum] map')
 
[7 7 7]
@@ -401,7 +401,7 @@ switch. Niether of the lists/stacks change their order.

Math words

+ add

-
J('23 9 +')
+
J('23 9 +')
 
32
@@ -410,7 +410,7 @@ switch. Niether of the lists/stacks change their order.

- sub

-
J('23 9 -')
+
J('23 9 -')
 
14
@@ -419,7 +419,7 @@ switch. Niether of the lists/stacks change their order.

* mul

-
J('23 9 *')
+
J('23 9 *')
 
207
@@ -428,37 +428,37 @@ switch. Niether of the lists/stacks change their order.

/ div floordiv truediv

-
J('23 9 /')
+
J('23 9 /')
 
2.5555555555555554
 
-
J('23 -9 truediv')
+
J('23 -9 truediv')
 
-2.5555555555555554
 
-
J('23 9 div')
+
J('23 9 div')
 
2
 
-
J('23 9 floordiv')
+
J('23 9 floordiv')
 
2
 
-
J('23 -9 div')
+
J('23 -9 div')
 
-3
 
-
J('23 -9 floordiv')
+
J('23 -9 floordiv')
 
-3
@@ -467,7 +467,7 @@ switch. Niether of the lists/stacks change their order.

% mod modulus rem remainder

-
J('23 9 %')
+
J('23 9 %')
 
5
@@ -476,7 +476,7 @@ switch. Niether of the lists/stacks change their order.

neg

-
J('23 neg -5 neg')
+
J('23 neg -5 neg')
 
-23 5
@@ -485,7 +485,7 @@ switch. Niether of the lists/stacks change their order.

pow

-
J('2 10 pow')
+
J('2 10 pow')
 
1024
@@ -494,13 +494,13 @@ switch. Niether of the lists/stacks change their order.

sqr sqrt

-
J('23 sqr')
+
J('23 sqr')
 
529
 
-
J('23 sqrt')
+
J('23 sqrt')
 
4.795831523312719
@@ -509,13 +509,13 @@ switch. Niether of the lists/stacks change their order.

++ succ -- pred

-
J('1 ++')
+
J('1 ++')
 
2
 
-
J('1 --')
+
J('1 --')
 
0
@@ -524,13 +524,13 @@ switch. Niether of the lists/stacks change their order.

<< lshift >> rshift

-
J('8 1 <<')
+
J('8 1 <<')
 
16
 
-
J('8 1 >>')
+
J('8 1 >>')
 
4
@@ -539,7 +539,7 @@ switch. Niether of the lists/stacks change their order.

average

-
J('[1 2 3 5] average')
+
J('[1 2 3 5] average')
 
2.75
@@ -548,19 +548,19 @@ switch. Niether of the lists/stacks change their order.

range range_to_zero down_to_zero

-
J('5 range')
+
J('5 range')
 
[4 3 2 1 0]
 
-
J('5 range_to_zero')
+
J('5 range_to_zero')
 
[0 1 2 3 4 5]
 
-
J('5 down_to_zero')
+
J('5 down_to_zero')
 
5 4 3 2 1 0
@@ -569,7 +569,7 @@ switch. Niether of the lists/stacks change their order.

product

-
J('[1 2 3 5] product')
+
J('[1 2 3 5] product')
 
30
@@ -578,7 +578,7 @@ switch. Niether of the lists/stacks change their order.

sum

-
J('[1 2 3 5] sum')
+
J('[1 2 3 5] sum')
 
11
@@ -587,7 +587,7 @@ switch. Niether of the lists/stacks change their order.

min

-
J('[1 2 3 5] min')
+
J('[1 2 3 5] min')
 
1
@@ -596,7 +596,7 @@ switch. Niether of the lists/stacks change their order.

gcd

-
J('45 30 gcd')
+
J('45 30 gcd')
 
15
@@ -607,13 +607,13 @@ switch. Niether of the lists/stacks change their order.

least_fraction

If we represent fractions as a quoted pair of integers [q d] this word reduces them to their … least common factors or whatever.

-
J('[45 30] least_fraction')
+
J('[45 30] least_fraction')
 
[3 2]
 
-
J('[23 12] least_fraction')
+
J('[23 12] least_fraction')
 
[23 12]
@@ -626,19 +626,19 @@ reduces them to their … least common factors or whatever.

? truthy

Get the Boolean value of the item on the top of the stack.

-
J('23 truthy')
+
J('23 truthy')
 
True
 
-
J('[] truthy')  # Python semantics.
+
J('[] truthy')  # Python semantics.
 
False
 
-
J('0 truthy')
+
J('0 truthy')
 
False
@@ -647,7 +647,7 @@ reduces them to their … least common factors or whatever.

? == dup truthy
 
-
V('23 ?')
+
V('23 ?')
 
        . 23 ?
@@ -657,13 +657,13 @@ reduces them to their … least common factors or whatever.

23 True .
-
J('[] ?')
+
J('[] ?')
 
[] False
 
-
J('0 ?')
+
J('0 ?')
 
0 False
@@ -672,7 +672,7 @@ reduces them to their … least common factors or whatever.

& and

-
J('23 9 &')
+
J('23 9 &')
 
1
@@ -681,7 +681,7 @@ reduces them to their … least common factors or whatever.

!= <> ne

-
J('23 9 !=')
+
J('23 9 !=')
 
True
@@ -694,13 +694,13 @@ reduces them to their … least common factors or whatever.

^ xor

-
J('1 1 ^')
+
J('1 1 ^')
 
0
 
-
J('1 0 ^')
+
J('1 0 ^')
 
1
@@ -712,7 +712,7 @@ reduces them to their … least common factors or whatever.

Miscellaneous

help

-
J('[help] help')
+
J('[help] help')
 
Accepts a quoted symbol on the top of the stack and prints its docs.
@@ -721,13 +721,13 @@ reduces them to their … least common factors or whatever.

parse

-
J('[parse] help')
+
J('[parse] help')
 
Parse the string on the stack to a Joy expression.
 
-
J('1 "2 [3] dup" parse')
+
J('1 "2 [3] dup" parse')
 
1 [2 [3] dup]
@@ -737,7 +737,7 @@ reduces them to their … least common factors or whatever.

run

Evaluate a quoted Joy sequence.

-
J('[1 2 dup + +] run')
+
J('[1 2 dup + +] run')
 
[5]
@@ -749,7 +749,7 @@ reduces them to their … least common factors or whatever.

Combinators

app1 app2 app3

-
J('[app1] help')
+
J('[app1] help')
 
Given a quoted program on TOS and anything as the second stack item run
@@ -761,19 +761,19 @@ reduces them to their … least common factors or whatever.

... [x ...] [Q] . infra first
-
J('10 4 [sqr *] app1')
+
J('10 4 [sqr *] app1')
 
10 160
 
-
J('10 3 4 [sqr *] app2')
+
J('10 3 4 [sqr *] app2')
 
10 90 160
 
-
J('[app2] help')
+
J('[app2] help')
 
Like app1 with two items.
@@ -784,7 +784,7 @@ reduces them to their … least common factors or whatever.

[x ...] [Q] infra first
-
J('10 2 3 4 [sqr *] app3')
+
J('10 2 3 4 [sqr *] app3')
 
10 40 90 160
@@ -804,7 +804,7 @@ function [G]
 
range == [0 <=] [1 - dup] anamorphism
 
-
J('3 [0 <=] [1 - dup] anamorphism')
+
J('3 [0 <=] [1 - dup] anamorphism')
 
[2 1 0]
@@ -813,13 +813,13 @@ function [G]
 

branch

-
J('3 4 1 [+] [*] branch')
+
J('3 4 1 [+] [*] branch')
 
12
 
-
J('3 4 0 [+] [*] branch')
+
J('3 4 0 [+] [*] branch')
 
7
@@ -846,7 +846,7 @@ in terms of app2
cleave == [i] app2 [popd] dip
 
-
J('10 2 [+] [-] cleave')
+
J('10 2 [+] [-] cleave')
 
10 12 8
@@ -855,19 +855,19 @@ in terms of app2
 

dip dipd dipdd

-
J('1 2 3 4 5 [+] dip')
+
J('1 2 3 4 5 [+] dip')
 
1 2 7 5
 
-
J('1 2 3 4 5 [+] dipd')
+
J('1 2 3 4 5 [+] dipd')
 
1 5 4 5
 
-
J('1 2 3 4 5 [+] dipdd')
+
J('1 2 3 4 5 [+] dipdd')
 
3 3 4 5
@@ -881,7 +881,7 @@ in terms of app2
n [Q] dupdip == n Q n
 
-
V('23 [++] dupdip *')  # N(N + 1)
+
V('23 [++] dupdip *')  # N(N + 1)
 
        . 23 [++] dupdip *
@@ -896,7 +896,7 @@ in terms of app2
 

genrec primrec

-
J('[genrec] help')
+
J('[genrec] help')
 
General Recursion Combinator.
@@ -945,7 +945,7 @@ in terms of app2)
 
-
J('3 [1 <=] [] [dup --] [i *] genrec')
+
J('3 [1 <=] [] [dup --] [i *] genrec')
 
6
@@ -954,7 +954,7 @@ in terms of app2
 

i

-
V('1 2 3 [+ +] i')
+
V('1 2 3 [+ +] i')
 
            . 1 2 3 [+ +] i
@@ -973,13 +973,13 @@ in terms of app2
[predicate] [then] [else] ifte
 
-
J('1 2 [1] [+] [*] ifte')
+
J('1 2 [1] [+] [*] ifte')
 
3
 
-
J('1 2 [0] [+] [*] ifte')
+
J('1 2 [0] [+] [*] ifte')
 
2
@@ -988,7 +988,7 @@ in terms of app2
 

infra

-
V('1 2 3 [4 5 6] [* +] infra')
+
V('1 2 3 [4 5 6] [* +] infra')
 
                    . 1 2 3 [4 5 6] [* +] infra
@@ -1007,7 +1007,7 @@ in terms of app2
 

loop

-
J('[loop] help')
+
J('[loop] help')
 
Basic loop combinator.
@@ -1021,7 +1021,7 @@ in terms of app2...
 
-
V('3 dup [1 - dup] loop')
+
V('3 dup [1 - dup] loop')
 
              . 3 dup [1 - dup] loop
@@ -1049,13 +1049,13 @@ in terms of app2
 

map pam

-
J('10 [1 2 3] [*] map')
+
J('10 [1 2 3] [*] map')
 
10 [10 20 30]
 
-
J('10 5 [[*][/][+][-]] pam')
+
J('10 5 [[*][/][+][-]] pam')
 
10 5 [50 2.0 15 5]
@@ -1066,25 +1066,25 @@ in terms of app2nullary unary binary ternary
 

Run a quoted program enforcing arity.

-
J('1 2 3 4 5 [+] nullary')
+
J('1 2 3 4 5 [+] nullary')
 
1 2 3 4 5 9
 
-
J('1 2 3 4 5 [+] unary')
+
J('1 2 3 4 5 [+] unary')
 
1 2 3 4 9
 
-
J('1 2 3 4 5 [+] binary')  # + has arity 2 so this is technically pointless...
+
J('1 2 3 4 5 [+] binary')  # + has arity 2 so this is technically pointless...
 
1 2 3 9
 
-
J('1 2 3 4 5 [+] ternary')
+
J('1 2 3 4 5 [+] ternary')
 
1 2 9
@@ -1093,7 +1093,7 @@ in terms of app2
 

step

-
J('[step] help')
+
J('[step] help')
 
Run a quoted program on each item in a sequence.
@@ -1116,7 +1116,7 @@ in terms of app2on top of the stack.
 
-
V('0 [1 2 3] [+] step')
+
V('0 [1 2 3] [+] step')
 
              . 0 [1 2 3] [+] step
@@ -1141,7 +1141,7 @@ in terms of app2
 

times

-
V('3 2 1 2 [+] times')
+
V('3 2 1 2 [+] times')
 
            . 3 2 1 2 [+] times
@@ -1161,7 +1161,7 @@ in terms of app2
 

b

-
J('[b] help')
+
J('[b] help')
 
b == [i] dip i
@@ -1170,7 +1170,7 @@ in terms of app2... [P] [Q] b == ... P Q
 
-
V('1 2 [3] [4] b')
+
V('1 2 [3] [4] b')
 
            . 1 2 [3] [4] b
@@ -1189,7 +1189,7 @@ in terms of app2
[predicate] [body] while
 
-
J('3 [0 >] [dup --] while')
+
J('3 [0 >] [dup --] while')
 
3 2 1 0
@@ -1198,7 +1198,7 @@ in terms of app2
 

x

-
J('[x] help')
+
J('[x] help')
 
x == dup i
@@ -1208,7 +1208,7 @@ in terms of app2... [Q] x = ... [Q]  Q
 
-
V('1 [2] [i 3] x')  # Kind of a pointless example.
+
V('1 [2] [i 3] x')  # Kind of a pointless example.
 
            . 1 [2] [i 3] x
@@ -1231,25 +1231,25 @@ in terms of app2
 over quote-only datastructures (that is, datastructures that consist
 soley of containers, without strings or numbers or anything else.)

-
J('[] void')
+
J('[] void')
 
False
 
-
J('[[]] void')
+
J('[[]] void')
 
True
 
-
J('[[][[]]] void')
+
J('[[][[]]] void')
 
True
 
-
J('[[[]][[][]]] void')
+
J('[[[]][[][]]] void')
 
False
diff --git a/docs/sphinx_docs/_build/html/notebooks/Derivatives_of_Regular_Expressions.html b/docs/sphinx_docs/_build/html/notebooks/Derivatives_of_Regular_Expressions.html
index 9123462..8c2e135 100644
--- a/docs/sphinx_docs/_build/html/notebooks/Derivatives_of_Regular_Expressions.html
+++ b/docs/sphinx_docs/_build/html/notebooks/Derivatives_of_Regular_Expressions.html
@@ -96,15 +96,15 @@ R∘λ = λ∘R = R
 

Implementation

-
from functools import partial as curry
-from itertools import product
+
from functools import partial as curry
+from itertools import product
 

ϕ and λ

The empty set and the set of just the empty string.

-
phi = frozenset()   # ϕ
-y = frozenset({''}) # λ
+
phi = frozenset()   # ϕ
+y = frozenset({''}) # λ
 
@@ -115,7 +115,7 @@ illustrate the algorithm and because you can represent any other alphabet with two symbols (if you had to.)

I chose the names O and l (uppercase “o” and lowercase “L”) to look like 0 and 1 (zero and one) respectively.

-
syms = O, l = frozenset({'0'}), frozenset({'1'})
+
syms = O, l = frozenset({'0'}), frozenset({'1'})
 
@@ -133,7 +133,7 @@ expression is one of:

Where R and S stand for regular expressions.

-
AND, CONS, KSTAR, NOT, OR = 'and cons * not or'.split()  # Tags are just strings.
+
AND, CONS, KSTAR, NOT, OR = 'and cons * not or'.split()  # Tags are just strings.
 

Because they are formed of frozenset, tuple and str objects @@ -141,36 +141,36 @@ only, these datastructures are immutable.

String Representation of RE Datastructures

-
def stringy(re):
-    '''
-    Return a nice string repr for a regular expression datastructure.
-    '''
-    if re == I: return '.'
-    if re in syms: return next(iter(re))
-    if re == y: return '^'
-    if re == phi: return 'X'
+
def stringy(re):
+    '''
+    Return a nice string repr for a regular expression datastructure.
+    '''
+    if re == I: return '.'
+    if re in syms: return next(iter(re))
+    if re == y: return '^'
+    if re == phi: return 'X'
 
-    assert isinstance(re, tuple), repr(re)
-    tag = re[0]
+    assert isinstance(re, tuple), repr(re)
+    tag = re[0]
 
-    if tag == KSTAR:
-        body = stringy(re[1])
-        if not body: return body
-        if len(body) > 1: return '(' + body + ")*"
-        return body + '*'
+    if tag == KSTAR:
+        body = stringy(re[1])
+        if not body: return body
+        if len(body) > 1: return '(' + body + ")*"
+        return body + '*'
 
-    if tag == NOT:
-        body = stringy(re[1])
-        if not body: return body
-        if len(body) > 1: return '(' + body + ")'"
-        return body + "'"
+    if tag == NOT:
+        body = stringy(re[1])
+        if not body: return body
+        if len(body) > 1: return '(' + body + ")'"
+        return body + "'"
 
-    r, s = stringy(re[1]), stringy(re[2])
-    if tag == CONS: return r + s
-    if tag == OR:   return '%s | %s' % (r, s)
-    if tag == AND:  return '(%s) & (%s)' % (r, s)
+    r, s = stringy(re[1]), stringy(re[2])
+    if tag == CONS: return r + s
+    if tag == OR:   return '%s | %s' % (r, s)
+    if tag == AND:  return '(%s) & (%s)' % (r, s)
 
-    raise ValueError
+    raise ValueError
 
@@ -180,10 +180,10 @@ only, these datastructures are immutable.

I = (0|1)*
 
-
I = (KSTAR, (OR, O, l))
+
I = (KSTAR, (OR, O, l))
 
-
print stringy(I)
+
print stringy(I)
 
.
@@ -198,13 +198,13 @@ only, these datastructures are immutable.

Note that it contains one of everything.

-
a = (CONS, I, (CONS, l, (CONS, l, (CONS, l, I))))
-b = (CONS, I, (CONS, O, l))
-c = (CONS, l, (KSTAR, l))
-it = (AND, a, (NOT, (OR, b, c)))
+
a = (CONS, I, (CONS, l, (CONS, l, (CONS, l, I))))
+b = (CONS, I, (CONS, O, l))
+c = (CONS, l, (KSTAR, l))
+it = (AND, a, (NOT, (OR, b, c)))
 
-
print stringy(it)
+
print stringy(it)
 
(.111.) & ((.01 | 11*)')
@@ -214,36 +214,36 @@ it = (AND, a, (NOT, (OR, b, c)))
 

nully()

Let’s get that auxiliary predicate function δ out of the way.

-
def nully(R):
-    '''
-    δ - Return λ if λ ⊆ R otherwise ϕ.
-    '''
+
def nully(R):
+    '''
+    δ - Return λ if λ ⊆ R otherwise ϕ.
+    '''
 
-    # δ(a) → ϕ
-    # δ(ϕ) → ϕ
-    if R in syms or R == phi:
-        return phi
+    # δ(a) → ϕ
+    # δ(ϕ) → ϕ
+    if R in syms or R == phi:
+        return phi
 
-    # δ(λ) → λ
-    if R == y:
-        return y
+    # δ(λ) → λ
+    if R == y:
+        return y
 
-    tag = R[0]
+    tag = R[0]
 
-    # δ(R*) → λ
-    if tag == KSTAR:
-        return y
+    # δ(R*) → λ
+    if tag == KSTAR:
+        return y
 
-    # δ(¬R) δ(R)≟ϕ → λ
-    # δ(¬R) δ(R)≟λ → ϕ
-    if tag == NOT:
-        return phi if nully(R[1]) else y
+    # δ(¬R) δ(R)≟ϕ → λ
+    # δ(¬R) δ(R)≟λ → ϕ
+    if tag == NOT:
+        return phi if nully(R[1]) else y
 
-    # δ(R∘S) → δ(R) ∧ δ(S)
-    # δ(R ∧ S) → δ(R) ∧ δ(S)
-    # δ(R ∨ S) → δ(R) ∨ δ(S)
-    r, s = nully(R[1]), nully(R[2])
-    return r & s if tag in {AND, CONS} else r | s
+    # δ(R∘S) → δ(R) ∧ δ(S)
+    # δ(R ∧ S) → δ(R) ∧ δ(S)
+    # δ(R ∨ S) → δ(R) ∨ δ(S)
+    r, s = nully(R[1]), nully(R[2])
+    return r & s if tag in {AND, CONS} else r | s
 
@@ -252,71 +252,71 @@ it = (AND, a, (NOT, (OR, b, c)))

This is the straightforward version with no “compaction”. It works fine, but does waaaay too much work because the expressions grow each derivation.

-
def D(symbol):
+
def D(symbol):
 
-    def derv(R):
+    def derv(R):
 
-        # ∂a(a) → λ
-        if R == {symbol}:
-            return y
+        # ∂a(a) → λ
+        if R == {symbol}:
+            return y
 
-        # ∂a(λ) → ϕ
-        # ∂a(ϕ) → ϕ
-        # ∂a(¬a) → ϕ
-        if R == y or R == phi or R in syms:
-            return phi
+        # ∂a(λ) → ϕ
+        # ∂a(ϕ) → ϕ
+        # ∂a(¬a) → ϕ
+        if R == y or R == phi or R in syms:
+            return phi
 
-        tag = R[0]
+        tag = R[0]
 
-        # ∂a(R*) → ∂a(R)∘R*
-        if tag == KSTAR:
-            return (CONS, derv(R[1]), R)
+        # ∂a(R*) → ∂a(R)∘R*
+        if tag == KSTAR:
+            return (CONS, derv(R[1]), R)
 
-        # ∂a(¬R) → ¬∂a(R)
-        if tag == NOT:
-            return (NOT, derv(R[1]))
+        # ∂a(¬R) → ¬∂a(R)
+        if tag == NOT:
+            return (NOT, derv(R[1]))
 
-        r, s = R[1:]
+        r, s = R[1:]
 
-        # ∂a(R∘S) → ∂a(R)∘S ∨ δ(R)∘∂a(S)
-        if tag == CONS:
-            A = (CONS, derv(r), s)  # A = ∂a(R)∘S
-            # A ∨ δ(R) ∘ ∂a(S)
-            # A ∨  λ   ∘ ∂a(S) → A ∨ ∂a(S)
-            # A ∨  ϕ   ∘ ∂a(S) → A ∨ ϕ → A
-            return (OR, A, derv(s)) if nully(r) else A
+        # ∂a(R∘S) → ∂a(R)∘S ∨ δ(R)∘∂a(S)
+        if tag == CONS:
+            A = (CONS, derv(r), s)  # A = ∂a(R)∘S
+            # A ∨ δ(R) ∘ ∂a(S)
+            # A ∨  λ   ∘ ∂a(S) → A ∨ ∂a(S)
+            # A ∨  ϕ   ∘ ∂a(S) → A ∨ ϕ → A
+            return (OR, A, derv(s)) if nully(r) else A
 
-        # ∂a(R ∧ S) → ∂a(R) ∧ ∂a(S)
-        # ∂a(R ∨ S) → ∂a(R) ∨ ∂a(S)
-        return (tag, derv(r), derv(s))
+        # ∂a(R ∧ S) → ∂a(R) ∧ ∂a(S)
+        # ∂a(R ∨ S) → ∂a(R) ∨ ∂a(S)
+        return (tag, derv(r), derv(s))
 
-    return derv
+    return derv
 

Compaction Rules

-
def _compaction_rule(relation, one, zero, a, b):
-    return (
-        b if a == one else  # R*1 = 1*R = R
-        a if b == one else
-        zero if a == zero or b == zero else  # R*0 = 0*R = 0
-        (relation, a, b)
-        )
+
def _compaction_rule(relation, one, zero, a, b):
+    return (
+        b if a == one else  # R*1 = 1*R = R
+        a if b == one else
+        zero if a == zero or b == zero else  # R*0 = 0*R = 0
+        (relation, a, b)
+        )
 

An elegant symmetry.

-
# R ∧ I = I ∧ R = R
-# R ∧ ϕ = ϕ ∧ R = ϕ
-_and = curry(_compaction_rule, AND, I, phi)
+
# R ∧ I = I ∧ R = R
+# R ∧ ϕ = ϕ ∧ R = ϕ
+_and = curry(_compaction_rule, AND, I, phi)
 
-# R ∨ ϕ = ϕ ∨ R = R
-# R ∨ I = I ∨ R = I
-_or = curry(_compaction_rule, OR, phi, I)
+# R ∨ ϕ = ϕ ∨ R = R
+# R ∨ I = I ∨ R = I
+_or = curry(_compaction_rule, OR, phi, I)
 
-# R∘λ = λ∘R = R
-# R∘ϕ = ϕ∘R = ϕ
-_cons = curry(_compaction_rule, CONS, y, phi)
+# R∘λ = λ∘R = R
+# R∘ϕ = ϕ∘R = ϕ
+_cons = curry(_compaction_rule, CONS, y, phi)
 
@@ -325,21 +325,21 @@ _cons = curry(_compaction_rule, CONS, y, phi)

We can save re-processing by remembering results we have already computed. RE datastructures are immutable and the derv() functions are pure so this is fine.

-
class Memo(object):
+
class Memo(object):
 
-    def __init__(self, f):
-        self.f = f
-        self.calls = self.hits = 0
-        self.mem = {}
+    def __init__(self, f):
+        self.f = f
+        self.calls = self.hits = 0
+        self.mem = {}
 
-    def __call__(self, key):
-        self.calls += 1
-        try:
-            result = self.mem[key]
-            self.hits += 1
-        except KeyError:
-            result = self.mem[key] = self.f(key)
-        return result
+    def __call__(self, key):
+        self.calls += 1
+        try:
+            result = self.mem[key]
+            self.hits += 1
+        except KeyError:
+            result = self.mem[key] = self.f(key)
+        return result
 
@@ -347,47 +347,47 @@ are pure so this is fine.

With “Compaction”

This version uses the rules above to perform compaction. It keeps the expressions from growing too large.

-
def D_compaction(symbol):
+
def D_compaction(symbol):
 
-    @Memo
-    def derv(R):
+    @Memo
+    def derv(R):
 
-        # ∂a(a) → λ
-        if R == {symbol}:
-            return y
+        # ∂a(a) → λ
+        if R == {symbol}:
+            return y
 
-        # ∂a(λ) → ϕ
-        # ∂a(ϕ) → ϕ
-        # ∂a(¬a) → ϕ
-        if R == y or R == phi or R in syms:
-            return phi
+        # ∂a(λ) → ϕ
+        # ∂a(ϕ) → ϕ
+        # ∂a(¬a) → ϕ
+        if R == y or R == phi or R in syms:
+            return phi
 
-        tag = R[0]
+        tag = R[0]
 
-        # ∂a(R*) → ∂a(R)∘R*
-        if tag == KSTAR:
-            return _cons(derv(R[1]), R)
+        # ∂a(R*) → ∂a(R)∘R*
+        if tag == KSTAR:
+            return _cons(derv(R[1]), R)
 
-        # ∂a(¬R) → ¬∂a(R)
-        if tag == NOT:
-            return (NOT, derv(R[1]))
+        # ∂a(¬R) → ¬∂a(R)
+        if tag == NOT:
+            return (NOT, derv(R[1]))
 
-        r, s = R[1:]
+        r, s = R[1:]
 
-        # ∂a(R∘S) → ∂a(R)∘S ∨ δ(R)∘∂a(S)
-        if tag == CONS:
-            A = _cons(derv(r), s)  # A = ∂a(r)∘s
-            # A ∨ δ(R) ∘ ∂a(S)
-            # A ∨  λ   ∘ ∂a(S) → A ∨ ∂a(S)
-            # A ∨  ϕ   ∘ ∂a(S) → A ∨ ϕ → A
-            return _or(A, derv(s)) if nully(r) else A
+        # ∂a(R∘S) → ∂a(R)∘S ∨ δ(R)∘∂a(S)
+        if tag == CONS:
+            A = _cons(derv(r), s)  # A = ∂a(r)∘s
+            # A ∨ δ(R) ∘ ∂a(S)
+            # A ∨  λ   ∘ ∂a(S) → A ∨ ∂a(S)
+            # A ∨  ϕ   ∘ ∂a(S) → A ∨ ϕ → A
+            return _or(A, derv(s)) if nully(r) else A
 
-        # ∂a(R ∧ S) → ∂a(R) ∧ ∂a(S)
-        # ∂a(R ∨ S) → ∂a(R) ∨ ∂a(S)
-        dr, ds = derv(r), derv(s)
-        return _and(dr, ds) if tag == AND else _or(dr, ds)
+        # ∂a(R ∧ S) → ∂a(R) ∧ ∂a(S)
+        # ∂a(R ∨ S) → ∂a(R) ∨ ∂a(S)
+        dr, ds = derv(r), derv(s)
+        return _and(dr, ds) if tag == AND else _or(dr, ds)
 
-    return derv
+    return derv
 
@@ -395,26 +395,26 @@ expressions from growing too large.

Let’s try it out…

(FIXME: redo.)

-
o, z = D_compaction('0'), D_compaction('1')
-REs = set()
-N = 5
-names = list(product(*(N * [(0, 1)])))
-dervs = list(product(*(N * [(o, z)])))
-for name, ds in zip(names, dervs):
-    R = it
-    ds = list(ds)
-    while ds:
-        R = ds.pop()(R)
-        if R == phi or R == I:
-            break
-        REs.add(R)
+
o, z = D_compaction('0'), D_compaction('1')
+REs = set()
+N = 5
+names = list(product(*(N * [(0, 1)])))
+dervs = list(product(*(N * [(o, z)])))
+for name, ds in zip(names, dervs):
+    R = it
+    ds = list(ds)
+    while ds:
+        R = ds.pop()(R)
+        if R == phi or R == I:
+            break
+        REs.add(R)
 
-print stringy(it) ; print
-print o.hits, '/', o.calls
-print z.hits, '/', z.calls
-print
-for s in sorted(map(stringy, REs), key=lambda n: (len(n), n)):
-    print s
+print stringy(it) ; print
+print o.hits, '/', o.calls
+print z.hits, '/', z.calls
+print
+for s in sorted(map(stringy, REs), key=lambda n: (len(n), n)):
+    print s
 
(.111.) & ((.01 | 11*)')
@@ -555,45 +555,45 @@ a --1--> ∂1(a)
 

You can see the one-way nature of the g state and the hij “trap” in the way that the .111. on the left-hand side of the & disappears once it has been matched.

-
from collections import defaultdict
-from pprint import pprint
-from string import ascii_lowercase
+
from collections import defaultdict
+from pprint import pprint
+from string import ascii_lowercase
 
-
d0, d1 = D_compaction('0'), D_compaction('1')
+
d0, d1 = D_compaction('0'), D_compaction('1')
 

explore()

-
def explore(re):
+
def explore(re):
 
-    # Don't have more than 26 states...
-    names = defaultdict(iter(ascii_lowercase).next)
+    # Don't have more than 26 states...
+    names = defaultdict(iter(ascii_lowercase).next)
 
-    table, accepting = dict(), set()
+    table, accepting = dict(), set()
 
-    to_check = {re}
-    while to_check:
+    to_check = {re}
+    while to_check:
 
-        re = to_check.pop()
-        state_name = names[re]
+        re = to_check.pop()
+        state_name = names[re]
 
-        if (state_name, 0) in table:
-            continue
+        if (state_name, 0) in table:
+            continue
 
-        if nully(re):
-            accepting.add(state_name)
+        if nully(re):
+            accepting.add(state_name)
 
-        o, i = d0(re), d1(re)
-        table[state_name, 0] = names[o] ; to_check.add(o)
-        table[state_name, 1] = names[i] ; to_check.add(i)
+        o, i = d0(re), d1(re)
+        table[state_name, 0] = names[o] ; to_check.add(o)
+        table[state_name, 1] = names[i] ; to_check.add(i)
 
-    return table, accepting
+    return table, accepting
 
-
table, accepting = explore(it)
-table
+
table, accepting = explore(it)
+table
 
{('a', 0): 'b',
@@ -618,7 +618,7 @@ table
  ('j', 1): 'h'}
 
-
accepting
+
accepting
 
{'h', 'i'}
@@ -629,31 +629,31 @@ table
 

Generate Diagram

Once we have the FSM table and the set of accepting states we can generate the diagram above.

-
_template = '''\
-digraph finite_state_machine {
-  rankdir=LR;
-  size="8,5"
-  node [shape = doublecircle]; %s;
-  node [shape = circle];
-%s
-}
-'''
+
_template = '''\
+digraph finite_state_machine {
+  rankdir=LR;
+  size="8,5"
+  node [shape = doublecircle]; %s;
+  node [shape = circle];
+%s
+}
+'''
 
-def link(fr, nm, label):
-    return '  %s -> %s [ label = "%s" ];' % (fr, nm, label)
+def link(fr, nm, label):
+    return '  %s -> %s [ label = "%s" ];' % (fr, nm, label)
 
 
-def make_graph(table, accepting):
-    return _template % (
-        ' '.join(accepting),
-        '\n'.join(
-          link(from_, to, char)
-          for (from_, char), (to) in sorted(table.iteritems())
-          )
-        )
+def make_graph(table, accepting):
+    return _template % (
+        ' '.join(accepting),
+        '\n'.join(
+          link(from_, to, char)
+          for (from_, char), (to) in sorted(table.iteritems())
+          )
+        )
 
-
print make_graph(table, accepting)
+
print make_graph(table, accepting)
 
digraph finite_state_machine {
@@ -699,14 +699,14 @@ hard-code the information in the table into a little patch of branches.

Trampoline Function

Python has no GOTO statement but we can fake it with a “trampoline” function.

-
def trampoline(input_, jump_from, accepting):
-    I = iter(input_)
-    while True:
-        try:
-            bounce_to = jump_from(I)
-        except StopIteration:
-            return jump_from in accepting
-        jump_from = bounce_to
+
def trampoline(input_, jump_from, accepting):
+    I = iter(input_)
+    while True:
+        try:
+            bounce_to = jump_from(I)
+        except StopIteration:
+            return jump_from in accepting
+        jump_from = bounce_to
 
@@ -714,17 +714,17 @@ function.

Stream Functions

Little helpers to process the iterator of our data (a “stream” of “1” and “0” characters, not bits.)

-
getch = lambda I: int(next(I))
+
getch = lambda I: int(next(I))
 
 
-def _1(I):
-    '''Loop on ones.'''
-    while getch(I): pass
+def _1(I):
+    '''Loop on ones.'''
+    while getch(I): pass
 
 
-def _0(I):
-    '''Loop on zeros.'''
-    while not getch(I): pass
+def _0(I):
+    '''Loop on zeros.'''
+    while not getch(I): pass
 
@@ -735,28 +735,28 @@ def _0(I): code. (You have to imagine that these are GOTO statements in C or branches in assembly and that the state names are branch destination labels.)

-
a = lambda I: c if getch(I) else b
-b = lambda I: _0(I) or d
-c = lambda I: e if getch(I) else b
-d = lambda I: f if getch(I) else b
-e = lambda I: g if getch(I) else b
-f = lambda I: h if getch(I) else b
-g = lambda I: _1(I) or i
-h = lambda I: _1(I) or i
-i = lambda I: _0(I) or j
-j = lambda I: h if getch(I) else i
+
a = lambda I: c if getch(I) else b
+b = lambda I: _0(I) or d
+c = lambda I: e if getch(I) else b
+d = lambda I: f if getch(I) else b
+e = lambda I: g if getch(I) else b
+f = lambda I: h if getch(I) else b
+g = lambda I: _1(I) or i
+h = lambda I: _1(I) or i
+i = lambda I: _0(I) or j
+j = lambda I: h if getch(I) else i
 

Note that the implementations of h and g are identical ergo h = g and we could eliminate one in the code but h is an accepting state and g isn’t.

-
def acceptable(input_):
-    return trampoline(input_, a, {h, i})
+
def acceptable(input_):
+    return trampoline(input_, a, {h, i})
 
-
for n in range(2**5):
-    s = bin(n)[2:]
-    print '%05s' % s, acceptable(s)
+
for n in range(2**5):
+    s = bin(n)[2:]
+    print '%05s' % s, acceptable(s)
 
    0 False
diff --git a/docs/sphinx_docs/_build/html/notebooks/Developing.html b/docs/sphinx_docs/_build/html/notebooks/Developing.html
index b670664..164db0d 100644
--- a/docs/sphinx_docs/_build/html/notebooks/Developing.html
+++ b/docs/sphinx_docs/_build/html/notebooks/Developing.html
@@ -43,17 +43,17 @@
 

If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23.

Find the sum of all the multiples of 3 or 5 below 1000.

-
from notebook_preamble import J, V, define
+
from notebook_preamble import J, V, define
 

Sum a range filtered by a predicate

Let’s create a predicate that returns True if a number is a multiple of 3 or 5 and False otherwise.

-
define('P == [3 % not] dupdip 5 % not or')
+
define('P == [3 % not] dupdip 5 % not or')
 
-
V('80 P')
+
V('80 P')
 
             . 80 P
@@ -116,10 +116,10 @@ the counter to the running sum. This function will do that:

PE1.1 == + [+] dupdip
 
-
define('PE1.1 == + [+] dupdip')
+
define('PE1.1 == + [+] dupdip')
 
-
V('0 0 3 PE1.1')
+
V('0 0 3 PE1.1')
 
        . 0 0 3 PE1.1
@@ -134,7 +134,7 @@ the counter to the running sum. This function will do that:

3 3 .
-
V('0 0 [3 2 1 3 1 2 3] [PE1.1] step')
+
V('0 0 [3 2 1 3 1 2 3] [PE1.1] step')
 
                            . 0 0 [3 2 1 3 1 2 3] [PE1.1] step
@@ -217,26 +217,26 @@ total to 60.

How many multiples to sum?

-
1000 / 15
+
1000 / 15
 
66
 
-
66 * 15
+
66 * 15
 
990
 
-
1000 - 990
+
1000 - 990
 
10
 

We only want the terms less than 1000.

-
999 - 990
+
999 - 990
 
9
@@ -244,10 +244,10 @@ total to 60.

That means we want to run the full list of numbers sixty-six times to get to 990 and then the first four numbers 3 2 1 3 to get to 999.

-
define('PE1 == 0 0 66 [[3 2 1 3 1 2 3] [PE1.1] step] times [3 2 1 3] [PE1.1] step pop')
+
define('PE1 == 0 0 66 [[3 2 1 3 1 2 3] [PE1.1] step] times [3 2 1 3] [PE1.1] step pop')
 
-
J('PE1')
+
J('PE1')
 
233168
@@ -267,16 +267,16 @@ integer terms from the list.

0b 11 10 01 11 01 10 11 == 14811
-
0b11100111011011
+
0b11100111011011
 
14811
 
-
define('PE1.2 == [3 & PE1.1] dupdip 2 >>')
+
define('PE1.2 == [3 & PE1.1] dupdip 2 >>')
 
-
V('0 0 14811 PE1.2')
+
V('0 0 14811 PE1.2')
 
                      . 0 0 14811 PE1.2
@@ -299,7 +299,7 @@ integer terms from the list.

3 3 3702 .
-
V('3 3 3702 PE1.2')
+
V('3 3 3702 PE1.2')
 
                     . 3 3 3702 PE1.2
@@ -322,7 +322,7 @@ integer terms from the list.

8 5 925 .
-
V('0 0 14811 7 [PE1.2] times pop')
+
V('0 0 14811 7 [PE1.2] times pop')
 
                      . 0 0 14811 7 [PE1.2] times pop
@@ -459,10 +459,10 @@ integer terms from the list.

And so we have at last:

-
define('PE1 == 0 0 66 [14811 7 [PE1.2] times pop] times 14811 4 [PE1.2] times popop')
+
define('PE1 == 0 0 66 [14811 7 [PE1.2] times pop] times 14811 4 [PE1.2] times popop')
 
-
J('PE1')
+
J('PE1')
 
233168
@@ -477,14 +477,14 @@ integer terms from the list.

n 14811 swap [PE1.2] times pop
-
define('PE1.3 == 14811 swap [PE1.2] times pop')
+
define('PE1.3 == 14811 swap [PE1.2] times pop')
 

Now we can simplify the definition above:

-
define('PE1 == 0 0 66 [7 PE1.3] times 4 PE1.3 pop')
+
define('PE1 == 0 0 66 [7 PE1.3] times 4 PE1.3 pop')
 
-
J('PE1')
+
J('PE1')
 
233168
@@ -507,10 +507,10 @@ I hope it’s clear.

then four more. In the Generator Programs notebook we derive a generator that can be repeatedly driven by the x combinator to produce a stream of the seven numbers repeating over and over again.

-
define('PE1.terms == [0 swap [dup [pop 14811] [] branch [3 &] dupdip 2 >>] dip rest cons]')
+
define('PE1.terms == [0 swap [dup [pop 14811] [] branch [3 &] dupdip 2 >>] dip rest cons]')
 
-
J('PE1.terms 21 [x] times')
+
J('PE1.terms 21 [x] times')
 
3 2 1 3 1 2 3 3 2 1 3 1 2 3 3 2 1 3 1 2 3 [0 swap [dup [pop 14811] [] branch [3 &] dupdip 2 >>] dip rest cons]
@@ -518,19 +518,19 @@ produce a stream of the seven numbers repeating over and over again.

We know from above that we need sixty-six times seven then four more terms to reach up to but not over one thousand.

-
J('7 66 * 4 +')
+
J('7 66 * 4 +')
 
466
 
-
J('PE1.terms 466 [x] times pop')
+
J('PE1.terms 466 [x] times pop')
 
3 2 1 3 1 2 3 3 2 1 3 1 2 3 3 2 1 3 1 2 3 3 2 1 3 1 2 3 3 2 1 3 1 2 3 3 2 1 3 1 2 3 3 2 1 3 1 2 3 3 2 1 3 1 2 3 3 2 1 3 1 2 3 3 2 1 3 1 2 3 3 2 1 3 1 2 3 3 2 1 3 1 2 3 3 2 1 3 1 2 3 3 2 1 3 1 2 3 3 2 1 3 1 2 3 3 2 1 3 1 2 3 3 2 1 3 1 2 3 3 2 1 3 1 2 3 3 2 1 3 1 2 3 3 2 1 3 1 2 3 3 2 1 3 1 2 3 3 2 1 3 1 2 3 3 2 1 3 1 2 3 3 2 1 3 1 2 3 3 2 1 3 1 2 3 3 2 1 3 1 2 3 3 2 1 3 1 2 3 3 2 1 3 1 2 3 3 2 1 3 1 2 3 3 2 1 3 1 2 3 3 2 1 3 1 2 3 3 2 1 3 1 2 3 3 2 1 3 1 2 3 3 2 1 3 1 2 3 3 2 1 3 1 2 3 3 2 1 3 1 2 3 3 2 1 3 1 2 3 3 2 1 3 1 2 3 3 2 1 3 1 2 3 3 2 1 3 1 2 3 3 2 1 3 1 2 3 3 2 1 3 1 2 3 3 2 1 3 1 2 3 3 2 1 3 1 2 3 3 2 1 3 1 2 3 3 2 1 3 1 2 3 3 2 1 3 1 2 3 3 2 1 3 1 2 3 3 2 1 3 1 2 3 3 2 1 3 1 2 3 3 2 1 3 1 2 3 3 2 1 3 1 2 3 3 2 1 3 1 2 3 3 2 1 3 1 2 3 3 2 1 3 1 2 3 3 2 1 3 1 2 3 3 2 1 3 1 2 3 3 2 1 3 1 2 3 3 2 1 3 1 2 3 3 2 1 3 1 2 3 3 2 1 3 1 2 3 3 2 1 3 1 2 3 3 2 1 3 1 2 3 3 2 1 3 1 2 3 3 2 1 3 1 2 3 3 2 1 3 1 2 3 3 2 1 3
 
-
J('[PE1.terms 466 [x] times pop] run sum')
+
J('[PE1.terms 466 [x] times pop] run sum')
 
999
@@ -539,7 +539,7 @@ terms to reach up to but not over one thousand.

Now we can use PE1.1 to accumulate the terms as we go, and then pop the generator and the counter from the stack when we’re done, leaving just the sum.

-
J('0 0 PE1.terms 466 [x [PE1.1] dip] times popop')
+
J('0 0 PE1.terms 466 [x [PE1.1] dip] times popop')
 
233168
@@ -550,7 +550,7 @@ leaving just the sum.

A little further analysis renders iteration unnecessary.

Consider finding the sum of the positive integers less than or equal to ten.

-
J('[10 9 8 7 6 5 4 3 2 1] sum')
+
J('[10 9 8 7 6 5 4 3 2 1] sum')
 
55
@@ -573,10 +573,10 @@ positive integers is:

(The formula also works for odd values of N, I’ll leave that to you if you want to work it out or you can take my word for it.)

-
define('F == dup ++ * 2 floordiv')
+
define('F == dup ++ * 2 floordiv')
 
-
V('10 F')
+
V('10 F')
 
      . 10 F
@@ -600,13 +600,13 @@ each, starting with:

If we reverse one of these two blocks and sum pairs…

-
J('[3 5 6 9 10 12 15] reverse [978 980 981 984 985 987 990] zip')
+
J('[3 5 6 9 10 12 15] reverse [978 980 981 984 985 987 990] zip')
 
[[978 15] [980 12] [981 10] [984 9] [985 6] [987 5] [990 3]]
 
-
J('[3 5 6 9 10 12 15] reverse [978 980 981 984 985 987 990] zip [sum] map')
+
J('[3 5 6 9 10 12 15] reverse [978 980 981 984 985 987 990] zip [sum] map')
 
[993 992 991 993 991 992 993]
@@ -614,7 +614,7 @@ each, starting with:

(Interesting that the sequence of seven numbers appears again in the rightmost digit of each term.)

-
J('[ 3 5 6 9 10 12 15] reverse [978 980 981 984 985 987 990] zip [sum] map sum')
+
J('[ 3 5 6 9 10 12 15] reverse [978 980 981 984 985 987 990] zip [sum] map sum')
 
6945
@@ -628,7 +628,7 @@ additional unpaired terms between 990 and 1000:

So we can give the “sum of all the multiples of 3 or 5 below 1000” like so:

-
J('6945 33 * [993 995 996 999] cons sum')
+
J('6945 33 * [993 995 996 999] cons sum')
 
233168
diff --git a/docs/sphinx_docs/_build/html/notebooks/Generator_Programs.html b/docs/sphinx_docs/_build/html/notebooks/Generator_Programs.html
index fe9f8b9..19aa59b 100644
--- a/docs/sphinx_docs/_build/html/notebooks/Generator_Programs.html
+++ b/docs/sphinx_docs/_build/html/notebooks/Generator_Programs.html
@@ -36,7 +36,7 @@
   

Using x to Generate Values

Cf. jp-reprod.html

-
from notebook_preamble import J, V, define
+
from notebook_preamble import J, V, define
 

Consider the x combinator:

@@ -76,7 +76,7 @@ function C

Let’s try it:

-
V('[0 swap [dup ++] dip rest cons] x')
+
V('[0 swap [dup ++] dip rest cons] x')
 
                                           . [0 swap [dup ++] dip rest cons] x
@@ -95,7 +95,7 @@ function C
 

After one application of x the quoted program contains 1 and 0 is below it on the stack.

-
J('[0 swap [dup ++] dip rest cons] x x x x x pop')
+
J('[0 swap [dup ++] dip rest cons] x x x x x pop')
 
0 1 2 3 4
@@ -103,10 +103,10 @@ function C
 

direco

-
define('direco == dip rest cons')
+
define('direco == dip rest cons')
 
-
V('[0 swap [dup ++] direco] x')
+
V('[0 swap [dup ++] direco] x')
 
                                    . [0 swap [dup ++] direco] x
@@ -147,17 +147,17 @@ our quoted program:

G == [direco] cons [swap] swoncat cons
-
define('G == [direco] cons [swap] swoncat cons')
+
define('G == [direco] cons [swap] swoncat cons')
 

Let’s try it out:

-
J('0 [dup ++] G')
+
J('0 [dup ++] G')
 
[0 swap [dup ++] direco]
 
-
J('0 [dup ++] G x x x pop')
+
J('0 [dup ++] G x x x pop')
 
0 1 2
@@ -165,7 +165,7 @@ our quoted program:

Powers of 2

-
J('1 [dup 1 <<] G x x x x x x x x x pop')
+
J('1 [dup 1 <<] G x x x x x x x x x pop')
 
1 2 4 8 16 32 64 128 256
@@ -176,7 +176,7 @@ our quoted program:

[x] times

If we have one of these quoted programs we can drive it using times with the x combinator.

-
J('23 [dup ++] G 5 [x] times')
+
J('23 [dup ++] G 5 [x] times')
 
23 24 25 26 27 [28 swap [dup ++] direco]
@@ -200,10 +200,10 @@ int:

And pick them off by masking with 3 (binary 11) and then shifting the int right two bits.

-
define('PE1.1 == dup [3 &] dip 2 >>')
+
define('PE1.1 == dup [3 &] dip 2 >>')
 
-
V('14811 PE1.1')
+
V('14811 PE1.1')
 
                  . 14811 PE1.1
@@ -220,14 +220,14 @@ int right two bits.

If we plug 14811 and [PE1.1] into our generator form…

-
J('14811 [PE1.1] G')
+
J('14811 [PE1.1] G')
 
[14811 swap [PE1.1] direco]
 

…we get a generator that works for seven cycles before it reaches zero:

-
J('[14811 swap [PE1.1] direco] 7 [x] times')
+
J('[14811 swap [PE1.1] direco] 7 [x] times')
 
3 2 1 3 1 2 3 [0 swap [PE1.1] direco]
@@ -237,16 +237,16 @@ int right two bits.

Reset at Zero

We need a function that checks if the int has reached zero and resets it if so.

-
define('PE1.1.check == dup [pop 14811] [] branch')
+
define('PE1.1.check == dup [pop 14811] [] branch')
 
-
J('14811 [PE1.1.check PE1.1] G')
+
J('14811 [PE1.1.check PE1.1] G')
 
[14811 swap [PE1.1.check PE1.1] direco]
 
-
J('[14811 swap [PE1.1.check PE1.1] direco] 21 [x] times')
+
J('[14811 swap [PE1.1.check PE1.1] direco] 21 [x] times')
 
3 2 1 3 1 2 3 3 2 1 3 1 2 3 3 2 1 3 1 2 3 [0 swap [PE1.1.check PE1.1] direco]
@@ -262,20 +262,20 @@ say.)

In the PE1 problem we are asked to sum all the multiples of three and five less than 1000. It’s worked out that we need to use all seven numbers sixty-six times and then four more.

-
J('7 66 * 4 +')
+
J('7 66 * 4 +')
 
466
 

If we drive our generator 466 times and sum the stack we get 999.

-
J('[14811 swap [PE1.1.check PE1.1] direco] 466 [x] times')
+
J('[14811 swap [PE1.1.check PE1.1] direco] 466 [x] times')
 
3 2 1 3 1 2 3 3 2 1 3 1 2 3 3 2 1 3 1 2 3 3 2 1 3 1 2 3 3 2 1 3 1 2 3 3 2 1 3 1 2 3 3 2 1 3 1 2 3 3 2 1 3 1 2 3 3 2 1 3 1 2 3 3 2 1 3 1 2 3 3 2 1 3 1 2 3 3 2 1 3 1 2 3 3 2 1 3 1 2 3 3 2 1 3 1 2 3 3 2 1 3 1 2 3 3 2 1 3 1 2 3 3 2 1 3 1 2 3 3 2 1 3 1 2 3 3 2 1 3 1 2 3 3 2 1 3 1 2 3 3 2 1 3 1 2 3 3 2 1 3 1 2 3 3 2 1 3 1 2 3 3 2 1 3 1 2 3 3 2 1 3 1 2 3 3 2 1 3 1 2 3 3 2 1 3 1 2 3 3 2 1 3 1 2 3 3 2 1 3 1 2 3 3 2 1 3 1 2 3 3 2 1 3 1 2 3 3 2 1 3 1 2 3 3 2 1 3 1 2 3 3 2 1 3 1 2 3 3 2 1 3 1 2 3 3 2 1 3 1 2 3 3 2 1 3 1 2 3 3 2 1 3 1 2 3 3 2 1 3 1 2 3 3 2 1 3 1 2 3 3 2 1 3 1 2 3 3 2 1 3 1 2 3 3 2 1 3 1 2 3 3 2 1 3 1 2 3 3 2 1 3 1 2 3 3 2 1 3 1 2 3 3 2 1 3 1 2 3 3 2 1 3 1 2 3 3 2 1 3 1 2 3 3 2 1 3 1 2 3 3 2 1 3 1 2 3 3 2 1 3 1 2 3 3 2 1 3 1 2 3 3 2 1 3 1 2 3 3 2 1 3 1 2 3 3 2 1 3 1 2 3 3 2 1 3 1 2 3 3 2 1 3 1 2 3 3 2 1 3 1 2 3 3 2 1 3 1 2 3 3 2 1 3 1 2 3 3 2 1 3 1 2 3 3 2 1 3 1 2 3 3 2 1 3 1 2 3 3 2 1 3 1 2 3 3 2 1 3 1 2 3 3 2 1 3 [57 swap [PE1.1.check PE1.1] direco]
 
-
J('[14811 swap [PE1.1.check PE1.1] direco] 466 [x] times pop enstacken sum')
+
J('[14811 swap [PE1.1.check PE1.1] direco] 466 [x] times pop enstacken sum')
 
999
@@ -285,11 +285,11 @@ numbers sixty-six times and then four more.

Project Euler Problem One

-
define('PE1.2 == + dup [+] dip')
+
define('PE1.2 == + dup [+] dip')
 

Now we can add PE1.2 to the quoted program given to G.

-
J('0 0 0 [PE1.1.check PE1.1] G 466 [x [PE1.2] dip] times popop')
+
J('0 0 0 [PE1.1.check PE1.1] G 466 [x [PE1.2] dip] times popop')
 
233168
@@ -351,13 +351,13 @@ numbers sixty-six times and then four more.

fib_gen == [1 1 F]
-
define('fib == + [popdd over] cons infra uncons')
+
define('fib == + [popdd over] cons infra uncons')
 
-
define('fib_gen == [1 1 fib]')
+
define('fib_gen == [1 1 fib]')
 
-
J('fib_gen 10 [x] times')
+
J('fib_gen 10 [x] times')
 
1 2 3 5 8 13 21 34 55 89 [144 89 fib]
@@ -373,21 +373,21 @@ not exceed four million, find the sum of the even-valued terms.

Now that we have a generator for the Fibonacci sequence, we need a function that adds a term in the sequence to a sum if it is even, and pops it otherwise.

-
define('PE2.1 == dup 2 % [+] [pop] branch')
+
define('PE2.1 == dup 2 % [+] [pop] branch')
 

And a predicate function that detects when the terms in the series “exceed four million”.

-
define('>4M == 4000000 >')
+
define('>4M == 4000000 >')
 

Now it’s straightforward to define PE2 as a recursive function that generates terms in the Fibonacci sequence until they exceed four million and sums the even ones.

-
define('PE2 == 0 fib_gen x [pop >4M] [popop] [[PE2.1] dip x] primrec')
+
define('PE2 == 0 fib_gen x [pop >4M] [popop] [[PE2.1] dip x] primrec')
 
-
J('PE2')
+
J('PE2')
 
4613732
@@ -418,23 +418,23 @@ and sums the even ones.

Every third term is even.

-
J('[1 0 fib] x x x')  # To start the sequence with 1 1 2 3 instead of 1 2 3.
+
J('[1 0 fib] x x x')  # To start the sequence with 1 1 2 3 instead of 1 2 3.
 
1 1 2 [3 2 fib]
 

Drive the generator three times and popop the two odd terms.

-
J('[1 0 fib] x x x [popop] dipd')
+
J('[1 0 fib] x x x [popop] dipd')
 
2 [3 2 fib]
 
-
define('PE2.2 == x x x [popop] dipd')
+
define('PE2.2 == x x x [popop] dipd')
 
-
J('[1 0 fib] 10 [PE2.2] times')
+
J('[1 0 fib] 10 [PE2.2] times')
 
2 8 34 144 610 2584 10946 46368 196418 832040 [1346269 832040 fib]
@@ -442,7 +442,7 @@ and sums the even ones.

Replace x with our new driver function PE2.2 and start our fib generator at 1 0.

-
J('0 [1 0 fib] PE2.2 [pop >4M] [popop] [[PE2.1] dip PE2.2] primrec')
+
J('0 [1 0 fib] PE2.2 [pop >4M] [popop] [[PE2.1] dip PE2.2] primrec')
 
4613732
@@ -457,10 +457,10 @@ modifications to the default 
 

An Interesting Variation

-
define('codireco == cons dip rest cons')
+
define('codireco == cons dip rest cons')
 
-
V('[0 [dup ++] codireco] x')
+
V('[0 [dup ++] codireco] x')
 
                                 . [0 [dup ++] codireco] x
@@ -479,10 +479,10 @@ modifications to the default 0 [1 [dup ++] codireco] .
 
-
define('G == [codireco] cons cons')
+
define('G == [codireco] cons cons')
 
-
J('230 [dup ++] G 5 [x] times pop')
+
J('230 [dup ++] G 5 [x] times pop')
 
230 231 232 233 234
diff --git a/docs/sphinx_docs/_build/html/notebooks/Intro.html b/docs/sphinx_docs/_build/html/notebooks/Intro.html
index bf30d3b..658704d 100644
--- a/docs/sphinx_docs/_build/html/notebooks/Intro.html
+++ b/docs/sphinx_docs/_build/html/notebooks/Intro.html
@@ -157,33 +157,33 @@ like that.

Examples

-
joy.parser.text_to_expression('1 2 3 4 5')  # A simple sequence.
+
joy.parser.text_to_expression('1 2 3 4 5')  # A simple sequence.
 
(1, (2, (3, (4, (5, ())))))
 
-
joy.parser.text_to_expression('[1 2 3] 4 5')  # Three items, the first is a list with three items
+
joy.parser.text_to_expression('[1 2 3] 4 5')  # Three items, the first is a list with three items
 
((1, (2, (3, ()))), (4, (5, ())))
 
-
joy.parser.text_to_expression('1 23 ["four" [-5.0] cons] 8888')  # A mixed bag. cons is
-                                                                 # a Symbol, no lookup at
-                                                                 # parse-time.  Haiku docs.
+
joy.parser.text_to_expression('1 23 ["four" [-5.0] cons] 8888')  # A mixed bag. cons is
+                                                                 # a Symbol, no lookup at
+                                                                 # parse-time.  Haiku docs.
 
(1, (23, (('four', ((-5.0, ()), (cons, ()))), (8888, ()))))
 
-
joy.parser.text_to_expression('[][][][][]')  # Five empty lists.
+
joy.parser.text_to_expression('[][][][][]')  # Five empty lists.
 
((), ((), ((), ((), ((), ())))))
 
-
joy.parser.text_to_expression('[[[[[]]]]]')  # Five nested lists.
+
joy.parser.text_to_expression('[[[[[]]]]]')  # Five nested lists.
 
((((((), ()), ()), ()), ()), ())
@@ -199,7 +199,7 @@ the Joy system. There are simple functions such as addition +, the library module supports aliases), and combinators which
 provide control-flow and higher-order operations.

Many of the functions are defined in Python, like dip:

-
print inspect.getsource(joy.library.dip)
+
print inspect.getsource(joy.library.dip)
 
def dip(stack, expression, dictionary):
@@ -212,7 +212,7 @@ provide control-flow and higher-order operations.

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.

-
print joy.library.definitions
+
print joy.library.definitions
 
second == rest first
diff --git a/docs/sphinx_docs/_build/html/notebooks/Ordered_Binary_Trees.html b/docs/sphinx_docs/_build/html/notebooks/Ordered_Binary_Trees.html
index 6665db0..eabfaba 100644
--- a/docs/sphinx_docs/_build/html/notebooks/Ordered_Binary_Trees.html
+++ b/docs/sphinx_docs/_build/html/notebooks/Ordered_Binary_Trees.html
@@ -63,7 +63,7 @@ the Sufficiently Smart Compiler can be modified to use an optimized
 implementation under the hood. (Where does the “type” come from? It has
 a contingent existence predicated on the disciplined use of these
 functions on otherwise undistinguished Joy datastructures.)

-
from notebook_preamble import D, J, V, define, DefinitionWrapper
+
from notebook_preamble import D, J, V, define, DefinitionWrapper
 
@@ -100,10 +100,10 @@ functions on otherwise undistinguished Joy datastructures.)

Tree-new == swap [[] []] cons cons
 
-
define('Tree-new == swap [[] []] cons cons')
+
define('Tree-new == swap [[] []] cons cons')
 
-
J('"v" "k" Tree-new')
+
J('"v" "k" Tree-new')
 
['k' 'v' [] []]
@@ -159,10 +159,10 @@ comparison operator:

P == pop roll> pop first
-
define('P == pop roll> pop first')
+
define('P == pop roll> pop first')
 
-
J('["old_key" 23 [] []] 17 "new_key" ["..."] P')
+
J('["old_key" 23 [] []] 17 "new_key" ["..."] P')
 
'new_key' 'old_key'
@@ -217,10 +217,10 @@ stack:

T == cons cons [dipdd] cons infra
 
-
define('T == cons cons [dipdd] cons infra')
+
define('T == cons cons [dipdd] cons infra')
 
-
J('["old_k" "old_value" "left" "right"] "new_value" "new_key" ["Tree-add"] T')
+
J('["old_k" "old_value" "left" "right"] "new_value" "new_key" ["Tree-add"] T')
 
['old_k' 'old_value' 'left' 'Tree-add' 'new_key' 'new_value' 'right']
@@ -234,7 +234,7 @@ stack:

[key_n value_n left right] value key [Tree-add] [P <] [Te] [Ee] ifte
-
define('E == [P <] [Te] [Ee] ifte')
+
define('E == [P <] [Te] [Ee] ifte')
 

In this case Te works that same as T but on the left child tree @@ -243,10 +243,10 @@ instead of the right, so the only difference is that it must use

Te == cons cons [dipd] cons infra
 
-
define('Te == cons cons [dipd] cons infra')
+
define('Te == cons cons [dipd] cons infra')
 
-
J('["old_k" "old_value" "left" "right"] "new_value" "new_key" ["Tree-add"] Te')
+
J('["old_k" "old_value" "left" "right"] "new_value" "new_key" ["Tree-add"] Te')
 
['old_k' 'old_value' 'Tree-add' 'new_key' 'new_value' 'left' 'right']
@@ -274,10 +274,10 @@ instead of the right, so the only difference is that it must use
               [key new_value left right]
 
-
define('Ee == pop swap roll< rest rest cons cons')
+
define('Ee == pop swap roll< rest rest cons cons')
 
-
J('["k" "old_value" "left" "right"] "new_value" "k" ["Tree-add"] Ee')
+
J('["k" "old_value" "left" "right"] "new_value" "k" ["Tree-add"] Ee')
 
['k' 'new_value' 'left' 'right']
@@ -302,43 +302,43 @@ instead of the right, so the only difference is that it must use
 Tree-add == [popop not] [[pop] dipd Tree-new] [] [R] genrec
 
-
define('Tree-add == [popop not] [[pop] dipd Tree-new] [] [[P >] [T] [E] ifte] genrec')
+
define('Tree-add == [popop not] [[pop] dipd Tree-new] [] [[P >] [T] [E] ifte] genrec')
 

Examples

-
J('[] 23 "b" Tree-add')  # Initial
+
J('[] 23 "b" Tree-add')  # Initial
 
['b' 23 [] []]
 
-
J('["b" 23 [] []] 88 "c" Tree-add')  # Greater than
+
J('["b" 23 [] []] 88 "c" Tree-add')  # Greater than
 
['b' 23 [] ['c' 88 [] []]]
 
-
J('["b" 23 [] []] 88 "a" Tree-add')  # Less than
+
J('["b" 23 [] []] 88 "a" Tree-add')  # Less than
 
['b' 23 ['a' 88 [] []] []]
 
-
J('["b" 23 [] []] 88 "b" Tree-add')  # Equal to
+
J('["b" 23 [] []] 88 "b" Tree-add')  # Equal to
 
['b' 88 [] []]
 
-
J('[] 23 "b" Tree-add 88 "a" Tree-add 44 "c" Tree-add')  # Series.
+
J('[] 23 "b" Tree-add 88 "a" Tree-add 44 "c" Tree-add')  # Series.
 
['b' 23 ['a' 88 [] []] ['c' 44 [] []]]
 
-
J('[] [[23 "b"] [88 "a"] [44 "c"]] [i Tree-add] step')
+
J('[] [[23 "b"] [88 "a"] [44 "c"]] [i Tree-add] step')
 
['b' 23 ['a' 88 [] []] ['c' 44 [] []]]
@@ -365,19 +365,19 @@ values:

L
-
J("1 0 ['G'] ['E'] ['L'] cmp")
+
J("1 0 ['G'] ['E'] ['L'] cmp")
 
'G'
 
-
J("1 1 ['G'] ['E'] ['L'] cmp")
+
J("1 1 ['G'] ['E'] ['L'] cmp")
 
'E'
 
-
J("0 1 ['G'] ['E'] ['L'] cmp")
+
J("0 1 ['G'] ['E'] ['L'] cmp")
 
'L'
@@ -414,7 +414,7 @@ node key (by throwing everything else away):

P == over [popop popop first] nullary
 
-
define('P == over [popop popop first] nullary')
+
define('P == over [popop popop first] nullary')
 

Using cmp to simplify our code above at @@ -434,10 +434,10 @@ to understand:

Tree-add == [popop not] [[pop] dipd Tree-new] [] [P [T] [Ee] [Te] cmp] genrec
 
-
define('Tree-add == [popop not] [[pop] dipd Tree-new] [] [P [T] [Ee] [Te] cmp] genrec')
+
define('Tree-add == [popop not] [[pop] dipd Tree-new] [] [P [T] [Ee] [Te] cmp] genrec')
 
-
J('[] 23 "b" Tree-add 88 "a" Tree-add 44 "c" Tree-add')  # Still works.
+
J('[] 23 "b" Tree-add 88 "a" Tree-add 44 "c" Tree-add')  # Still works.
 
['b' 23 ['a' 88 [] []] ['c' 44 [] []]]
@@ -545,22 +545,22 @@ with an interesting situation:

Tree-iter == [not] [pop] roll< [dupdip rest rest] cons [step] genrec
 
-
define('Tree-iter == [not] [pop] roll< [dupdip rest rest] cons [step] genrec')
+
define('Tree-iter == [not] [pop] roll< [dupdip rest rest] cons [step] genrec')
 

Examples

-
J('[] [foo] Tree-iter')  #  It doesn't matter what F is as it won't be used.
+
J('[] [foo] Tree-iter')  #  It doesn't matter what F is as it won't be used.
 
-
J("['b' 23 ['a' 88 [] []] ['c' 44 [] []]] [first] Tree-iter")
+
J("['b' 23 ['a' 88 [] []] ['c' 44 [] []]] [first] Tree-iter")
 
'b' 'a' 'c'
 
-
J("['b' 23 ['a' 88 [] []] ['c' 44 [] []]] [second] Tree-iter")
+
J("['b' 23 ['a' 88 [] []] ['c' 44 [] []]] [second] Tree-iter")
 
23 88 44
@@ -575,16 +575,16 @@ to e.g. 0 and ignoring them. It’s set-like in that duplicate items added
 to it will only occur once within it, and we can query it in
 :math:`O(log_2 N) <https://en.wikipedia.org/wiki/Binary_search_tree#cite_note-2>`__
 time.

-
J('[] [3 9 5 2 8 6 7 8 4] [0 swap Tree-add] step')
+
J('[] [3 9 5 2 8 6 7 8 4] [0 swap Tree-add] step')
 
[3 0 [2 0 [] []] [9 0 [5 0 [4 0 [] []] [8 0 [6 0 [] [7 0 [] []]] []]] []]]
 
-
define('to_set == [] swap [0 swap Tree-add] step')
+
define('to_set == [] swap [0 swap Tree-add] step')
 
-
J('[3 9 5 2 8 6 7 8 4] to_set')
+
J('[3 9 5 2 8 6 7 8 4] to_set')
 
[3 0 [2 0 [] []] [9 0 [5 0 [4 0 [] []] [8 0 [6 0 [] [7 0 [] []]] []]] []]]
@@ -592,10 +592,10 @@ time.

And with that we can write a little program unique to remove duplicate items from a list.

-
define('unique == [to_set [first] Tree-iter] cons run')
+
define('unique == [to_set [first] Tree-iter] cons run')
 
-
J('[3 9 3 5 2 9 8 8 8 6 2 7 8 4 3] unique')  # Filter duplicate items.
+
J('[3 9 3 5 2 9 8 8 8 6 2 7 8 4 3] unique')  # Filter duplicate items.
 
[7 6 8 4 5 9 2 3]
@@ -679,23 +679,23 @@ right side:

Now we can sort sequences.

-
#define('Tree-iter-order == [not] [pop] [dup third] [[cons dip] dupdip [[first] dupdip] dip [rest rest rest first] dip i] genrec')
+
#define('Tree-iter-order == [not] [pop] [dup third] [[cons dip] dupdip [[first] dupdip] dip [rest rest rest first] dip i] genrec')
 
 
-DefinitionWrapper.add_definitions('''
+DefinitionWrapper.add_definitions('''
 
-fourth == rest rest rest first
+fourth == rest rest rest first
 
-proc_left == [cons dip] dupdip
-proc_current == [[first] dupdip] dip
-proc_right == [fourth] dip i
+proc_left == [cons dip] dupdip
+proc_current == [[first] dupdip] dip
+proc_right == [fourth] dip i
 
-Tree-iter-order == [not] [pop] [dup third] [proc_left proc_current proc_right] genrec
+Tree-iter-order == [not] [pop] [dup third] [proc_left proc_current proc_right] genrec
 
-''', D)
+''', D)
 
-
J('[3 9 5 2 8 6 7 8 4] to_set Tree-iter-order')
+
J('[3 9 5 2 8 6 7 8 4] to_set Tree-iter-order')
 
2 3 4 5 6 7 8 9
@@ -835,54 +835,54 @@ because there’s no value to discard.

Tree-get == [pop not] swap [] [P [T>] [E] [T<] cmp] genrec
-
# I don't want to deal with name conflicts with the above so I'm inlining everything here.
-# The original Joy system has "hide" which is a meta-command which allows you to use named
-# definitions that are only in scope for a given definition.  I don't want to implement
-# that (yet) so...
+
# I don't want to deal with name conflicts with the above so I'm inlining everything here.
+# The original Joy system has "hide" which is a meta-command which allows you to use named
+# definitions that are only in scope for a given definition.  I don't want to implement
+# that (yet) so...
 
 
-define('''
-Tree-get == [pop not] swap [] [
-  over [pop popop first] nullary
-  [[fourth] dipd i]
-  [popop second]
-  [[third] dipd i]
-  cmp
-  ] genrec
-''')
+define('''
+Tree-get == [pop not] swap [] [
+  over [pop popop first] nullary
+  [[fourth] dipd i]
+  [popop second]
+  [[third] dipd i]
+  cmp
+  ] genrec
+''')
 
-
J('["gary" 23 [] []] "mike" [popd " not in tree" +] Tree-get')
+
J('["gary" 23 [] []] "mike" [popd " not in tree" +] Tree-get')
 
'mike not in tree'
 
-
J('["gary" 23 [] []] "gary" [popop "err"] Tree-get')
+
J('["gary" 23 [] []] "gary" [popop "err"] Tree-get')
 
23
 
-
J('''
+
J('''
 
-    [] [[0 'a'] [1 'b'] [2 'c']] [i Tree-add] step
+    [] [[0 'a'] [1 'b'] [2 'c']] [i Tree-add] step
 
-    'c' [popop 'not found'] Tree-get
+    'c' [popop 'not found'] Tree-get
 
-''')
+''')
 
2
 
-
J('''
+
J('''
 
-    [] [[0 'a'] [1 'b'] [2 'c']] [i Tree-add] step
+    [] [[0 'a'] [1 'b'] [2 'c']] [i Tree-add] step
 
-    'd' [popop 'not found'] Tree-get
+    'd' [popop 'not found'] Tree-get
 
-''')
+''')
 
'not found'
@@ -1175,61 +1175,61 @@ E == [
 

By the standards of the code I’ve written so far, this is a huge Joy program.

-
DefinitionWrapper.add_definitions('''
-first_two == uncons uncons pop
-fourth == rest rest rest first
-?fourth == [] [fourth] [] ifte
-W.rightmost == [?fourth] [fourth] while
-E.clear_stuff == roll> popop rest
-E.delete == cons dipd
-W == dup W.rightmost first_two over
-E.0 == E.clear_stuff [W] dip E.delete swap
-E == [[[pop third not] pop fourth] [[pop fourth not] pop third] [[E.0] cons infra]] cond
-T> == [dipd] cons infra
-T< == [dipdd] cons infra
-R0 == over first swap dup
-R1 == cons roll> [T>] [E] [T<] cmp
-Tree-Delete == [pop not] [pop] [R0] [R1] genrec
-''', D)
+
DefinitionWrapper.add_definitions('''
+first_two == uncons uncons pop
+fourth == rest rest rest first
+?fourth == [] [fourth] [] ifte
+W.rightmost == [?fourth] [fourth] while
+E.clear_stuff == roll> popop rest
+E.delete == cons dipd
+W == dup W.rightmost first_two over
+E.0 == E.clear_stuff [W] dip E.delete swap
+E == [[[pop third not] pop fourth] [[pop fourth not] pop third] [[E.0] cons infra]] cond
+T> == [dipd] cons infra
+T< == [dipdd] cons infra
+R0 == over first swap dup
+R1 == cons roll> [T>] [E] [T<] cmp
+Tree-Delete == [pop not] [pop] [R0] [R1] genrec
+''', D)
 
-
J("['a' 23 [] ['b' 88 [] ['c' 44 [] []]]] 'c' Tree-Delete ")
+
J("['a' 23 [] ['b' 88 [] ['c' 44 [] []]]] 'c' Tree-Delete ")
 
['a' 23 [] ['b' 88 [] []]]
 
-
J("['a' 23 [] ['b' 88 [] ['c' 44 [] []]]] 'b' Tree-Delete ")
+
J("['a' 23 [] ['b' 88 [] ['c' 44 [] []]]] 'b' Tree-Delete ")
 
['a' 23 [] ['c' 44 [] []]]
 
-
J("['a' 23 [] ['b' 88 [] ['c' 44 [] []]]] 'a' Tree-Delete ")
+
J("['a' 23 [] ['b' 88 [] ['c' 44 [] []]]] 'a' Tree-Delete ")
 
['b' 88 [] ['c' 44 [] []]]
 
-
J("['a' 23 [] ['b' 88 [] ['c' 44 [] []]]] 'der' Tree-Delete ")
+
J("['a' 23 [] ['b' 88 [] ['c' 44 [] []]]] 'der' Tree-Delete ")
 
['a' 23 [] ['b' 88 [] ['c' 44 [] []]]]
 
-
J('[] [4 2 3 1 6 7 5 ] [0 swap Tree-add] step')
+
J('[] [4 2 3 1 6 7 5 ] [0 swap Tree-add] step')
 
[4 0 [2 0 [1 0 [] []] [3 0 [] []]] [6 0 [5 0 [] []] [7 0 [] []]]]
 
-
J("[4 0 [2 0 [1 0 [] []] [3 0 [] []]] [6 0 [5 0 [] []] [7 0 [] []]]] 3 Tree-Delete ")
+
J("[4 0 [2 0 [1 0 [] []] [3 0 [] []]] [6 0 [5 0 [] []] [7 0 [] []]]] 3 Tree-Delete ")
 
[4 0 [2 0 [1 0 [] []] []] [6 0 [5 0 [] []] [7 0 [] []]]]
 
-
J("[4 0 [2 0 [1 0 [] []] [3 0 [] []]] [6 0 [5 0 [] []] [7 0 [] []]]] 4 Tree-Delete ")
+
J("[4 0 [2 0 [1 0 [] []] [3 0 [] []]] [6 0 [5 0 [] []] [7 0 [] []]]] 4 Tree-Delete ")
 
[3 0 [2 0 [1 0 [] []] []] [6 0 [5 0 [] []] [7 0 [] []]]]
diff --git a/docs/sphinx_docs/_build/html/notebooks/Quadratic.html b/docs/sphinx_docs/_build/html/notebooks/Quadratic.html
index e617c60..40c3b6d 100644
--- a/docs/sphinx_docs/_build/html/notebooks/Quadratic.html
+++ b/docs/sphinx_docs/_build/html/notebooks/Quadratic.html
@@ -34,7 +34,7 @@
 
           
-
from notebook_preamble import J, V, define
+  
from notebook_preamble import J, V, define
 
@@ -100,11 +100,11 @@ the variables:

The three arguments are to the left, so we can “chop off” everything to the right and say it’s the definition of the quadratic function:

-
define('quadratic == over [[[neg] dupdip sqr 4] dipd * * - sqrt pm] dip 2 * [/] cons app2')
+
define('quadratic == over [[[neg] dupdip sqr 4] dipd * * - sqrt pm] dip 2 * [/] cons app2')
 

Let’s try it out:

-
J('3 1 1 quadratic')
+
J('3 1 1 quadratic')
 
-0.3819660112501051 -2.618033988749895
@@ -114,7 +114,7 @@ the right and say it’s the definition of the dip and dipd combinators building the main program
 by incorporating the values on the stack. Then that program runs and you
 get the results. This is pretty typical of Joy code.

-
V('-5 1 4 quadratic')
+
V('-5 1 4 quadratic')
 
                                                   . -5 1 4 quadratic
diff --git a/docs/sphinx_docs/_build/html/notebooks/Recursion_Combinators.html b/docs/sphinx_docs/_build/html/notebooks/Recursion_Combinators.html
index f6a7fb3..5500e18 100644
--- a/docs/sphinx_docs/_build/html/notebooks/Recursion_Combinators.html
+++ b/docs/sphinx_docs/_build/html/notebooks/Recursion_Combinators.html
@@ -33,7 +33,7 @@
 
           
-
from notebook_preamble import D, DefinitionWrapper, J, V, define
+  
from notebook_preamble import D, DefinitionWrapper, J, V, define
 
@@ -101,18 +101,18 @@ cons list”.

It may be helpful to see this function implemented in imperative Python code.

-
def hylomorphism(c, F, P, G):
-    '''Return a hylomorphism function H.'''
+
def hylomorphism(c, F, P, G):
+    '''Return a hylomorphism function H.'''
 
-    def H(a):
-        if P(a):
-            result = c
-        else:
-            b, aa = G(a)
-            result = F(b, H(aa))  # b is stored in the stack frame during recursive call to H().
-        return result
+    def H(a):
+        if P(a):
+            result = c
+        else:
+            b, aa = G(a)
+            result = F(b, H(aa))  # b is stored in the stack frame during recursive call to H().
+        return result
 
-    return H
+    return H
 

Cf. “Bananas, Lenses, & Barbed @@ -185,7 +185,7 @@ the left so we have a definition for

-
define('hylomorphism == [unit [pop] swoncat] dipd [dip] swoncat genrec')
+
define('hylomorphism == [unit [pop] swoncat] dipd [dip] swoncat genrec')
 
@@ -200,17 +200,17 @@ of all positive integers less than that one. (In this case the types
  • [G] is [-- dup]

  • [F] is [+]

  • -
    define('triangular_number == [1 <=] 0 [-- dup] [+] hylomorphism')
    +
    define('triangular_number == [1 <=] 0 [-- dup] [+] hylomorphism')
     

    Let’s try it:

    -
    J('5 triangular_number')
    +
    J('5 triangular_number')
     
    10
     
    -
    J('[0 1 2 3 4 5 6] [triangular_number] map')
    +
    J('[0 1 2 3 4 5 6] [triangular_number] map')
     
    [0 0 1 3 6 10 15]
    @@ -372,10 +372,10 @@ values.

    == [0 <=] [pop []] [-- dup] [dip swons] genrec
    -
    define('range == [0 <=] [] [-- dup] [swons] hylomorphism')
    +
    define('range == [0 <=] [] [-- dup] [swons] hylomorphism')
     
    -
    J('5 range')
    +
    J('5 range')
     
    [4 3 2 1 0]
    @@ -388,10 +388,10 @@ values.

    == [] swap [0 <=] [pop] [-- dup [swons] dip] primrec
    -
    define('range_reverse == [] swap [0 <=] [pop] [-- dup [swons] dip] primrec')
    +
    define('range_reverse == [] swap [0 <=] [pop] [-- dup [swons] dip] primrec')
     
    -
    J('5 range_reverse')
    +
    J('5 range_reverse')
     
    [0 1 2 3 4]
    @@ -404,10 +404,10 @@ values.

    == [0 <=] [pop []] [[--] dupdip] [dip swons] genrec
    -
    define('ranger == [0 <=] [pop []] [[--] dupdip] [dip swons] genrec')
    +
    define('ranger == [0 <=] [pop []] [[--] dupdip] [dip swons] genrec')
     
    -
    J('5 ranger')
    +
    J('5 ranger')
     
    [5 4 3 2 1]
    @@ -420,10 +420,10 @@ values.

    == [] swap [0 <=] [pop] [[swons] dupdip --] primrec
    -
    define('ranger_reverse == [] swap [0 <=] [pop] [[swons] dupdip --] primrec')
    +
    define('ranger_reverse == [] swap [0 <=] [pop] [[swons] dupdip --] primrec')
     
    -
    J('5 ranger_reverse')
    +
    J('5 ranger_reverse')
     
    [1 2 3 4 5]
    @@ -444,17 +444,17 @@ and makes some new value.

    C == [not] c [uncons swap] [F] hylomorphism
     
    -
    define('swuncons == uncons swap')  # Awkward name.
    +
    define('swuncons == uncons swap')  # Awkward name.
     

    An example of a catamorphism is the sum function.

    sum == [not] 0 [swuncons] [+] hylomorphism
     
    -
    define('sum == [not] 0 [swuncons] [+] hylomorphism')
    +
    define('sum == [not] 0 [swuncons] [+] hylomorphism')
     
    -
    J('[5 4 3 2 1] sum')
    +
    J('[5 4 3 2 1] sum')
     
    15
    @@ -464,7 +464,7 @@ and makes some new value.

    The step combinator

    The step combinator will usually be better to use than catamorphism.

    -
    J('[step] help')
    +
    J('[step] help')
     
    Run a quoted program on each item in a sequence.
    @@ -488,10 +488,10 @@ and makes some new value.

    on top of the stack.
    -
    define('sum == 0 swap [+] step')
    +
    define('sum == 0 swap [+] step')
     
    -
    J('[5 4 3 2 1] sum')
    +
    J('[5 4 3 2 1] sum')
     
    15
    @@ -512,10 +512,10 @@ and makes some new value.

    P == 1 <=
    -
    define('factorial == 1 swap [1 <=] [pop] [[*] dupdip --] primrec')
    +
    define('factorial == 1 swap [1 <=] [pop] [[*] dupdip --] primrec')
     
    -
    J('5 factorial')
    +
    J('5 factorial')
     
    120
    @@ -544,10 +544,10 @@ pattern H2P == not
     
    -
    define('tails == [] swap [not] [pop] [rest dup [swons] dip] primrec')
    +
    define('tails == [] swap [not] [pop] [rest dup [swons] dip] primrec')
     
    -
    J('[1 2 3] tails')
    +
    J('[1 2 3] tails')
     
    [[] [3] [2 3]]
    diff --git a/docs/sphinx_docs/_build/html/notebooks/Replacing.html b/docs/sphinx_docs/_build/html/notebooks/Replacing.html
    index f152c0e..6f1aaf6 100644
    --- a/docs/sphinx_docs/_build/html/notebooks/Replacing.html
    +++ b/docs/sphinx_docs/_build/html/notebooks/Replacing.html
    @@ -42,12 +42,12 @@ we can implement e.g. a function that adds new functions to the
     dictionary. However, there’s no function that does that. Adding a new
     function to the dictionary is a meta-interpreter action, you have to do
     it in Python, not Joy.

    -
    from notebook_preamble import D, J, V
    +
    from notebook_preamble import D, J, V
     

    A long trace

    -
    V('[23 18] average')
    +
    V('[23 18] average')
     
                                      . [23 18] average
    @@ -105,30 +105,30 @@ it in Python, not Joy.

    An efficient sum function is already in the library. But for size we can use a “compiled” version hand-written in Python to speed up evaluation and make the trace more readable.

    -
    from joy.library import SimpleFunctionWrapper
    -from joy.utils.stack import iter_stack
    +
    from joy.library import SimpleFunctionWrapper
    +from joy.utils.stack import iter_stack
     
     
    -@SimpleFunctionWrapper
    -def size(stack):
    -    '''Return the size of the sequence on the stack.'''
    -    sequence, stack = stack
    -    n = 0
    -    for _ in iter_stack(sequence):
    -        n += 1
    -    return n, stack
    +@SimpleFunctionWrapper
    +def size(stack):
    +    '''Return the size of the sequence on the stack.'''
    +    sequence, stack = stack
    +    n = 0
    +    for _ in iter_stack(sequence):
    +        n += 1
    +    return n, stack
     

    Now we replace the old version in the dictionary with the new version, and re-evaluate the expression.

    -
    D['size'] = size
    +
    D['size'] = size
     

    A shorter trace

    You can see that size now executes in a single step.

    -
    V('[23 18] average')
    +
    V('[23 18] average')
     
                                      . [23 18] average
    diff --git a/docs/sphinx_docs/_build/html/notebooks/Treestep.html b/docs/sphinx_docs/_build/html/notebooks/Treestep.html
    index a0903ee..91fea34 100644
    --- a/docs/sphinx_docs/_build/html/notebooks/Treestep.html
    +++ b/docs/sphinx_docs/_build/html/notebooks/Treestep.html
    @@ -148,17 +148,17 @@ the desired outcome.

    Define treestep

    -
    from notebook_preamble import D, J, V, define, DefinitionWrapper
    +
    from notebook_preamble import D, J, V, define, DefinitionWrapper
     
    -
    DefinitionWrapper.add_definitions('''
    +
    DefinitionWrapper.add_definitions('''
     
    -    _treestep_0 == [[not] swap] dip
    -    _treestep_1 == [dip] cons [uncons] swoncat
    -    treegrind == [_treestep_1 _treestep_0] dip genrec
    -    treestep == [map] swoncat treegrind
    +    _treestep_0 == [[not] swap] dip
    +    _treestep_1 == [dip] cons [uncons] swoncat
    +    treegrind == [_treestep_1 _treestep_0] dip genrec
    +    treestep == [map] swoncat treegrind
     
    -''', D)
    +''', D)
     
    @@ -169,7 +169,7 @@ all nodes in a tree with this function:

    sumtree == [pop 0] [] [sum +] treestep
     
    -
    define('sumtree == [pop 0] [] [sum +] treestep')
    +
    define('sumtree == [pop 0] [] [sum +] treestep')
     

    Running this function on an empty tree value gives zero:

    @@ -178,7 +178,7 @@ all nodes in a tree with this function:

    0
    -
    J('[] sumtree')  # Empty tree.
    +
    J('[] sumtree')  # Empty tree.
     
    0
    @@ -192,61 +192,61 @@ all nodes in a tree with this function:

    n+m
    -
    J('[23] sumtree')  # No child trees.
    +
    J('[23] sumtree')  # No child trees.
     
    23
     
    -
    J('[23 []] sumtree')  # Child tree, empty.
    +
    J('[23 []] sumtree')  # Child tree, empty.
     
    23
     
    -
    J('[23 [2 [4]] [3]] sumtree')  # Non-empty child trees.
    +
    J('[23 [2 [4]] [3]] sumtree')  # Non-empty child trees.
     
    32
     
    -
    J('[23 [2 [8] [9]] [3] [4 []]] sumtree')  # Etc...
    +
    J('[23 [2 [8] [9]] [3] [4 []]] sumtree')  # Etc...
     
    49
     
    -
    J('[23 [2 [8] [9]] [3] [4 []]] [pop 0] [] [cons sum] treestep')  # Alternate "spelling".
    +
    J('[23 [2 [8] [9]] [3] [4 []]] [pop 0] [] [cons sum] treestep')  # Alternate "spelling".
     
    49
     
    -
    J('[23 [2 [8] [9]] [3] [4 []]] [] [pop 23] [cons] treestep')  # Replace each node.
    +
    J('[23 [2 [8] [9]] [3] [4 []]] [] [pop 23] [cons] treestep')  # Replace each node.
     
    [23 [23 [23] [23]] [23] [23 []]]
     
    -
    J('[23 [2 [8] [9]] [3] [4 []]] [] [pop 1] [cons] treestep')
    +
    J('[23 [2 [8] [9]] [3] [4 []]] [] [pop 1] [cons] treestep')
     
    [1 [1 [1] [1]] [1] [1 []]]
     
    -
    J('[23 [2 [8] [9]] [3] [4 []]] [] [pop 1] [cons] treestep sumtree')
    +
    J('[23 [2 [8] [9]] [3] [4 []]] [] [pop 1] [cons] treestep sumtree')
     
    6
     
    -
    J('[23 [2 [8] [9]] [3] [4 []]] [pop 0] [pop 1] [sum +] treestep')  # Combine replace and sum into one function.
    +
    J('[23 [2 [8] [9]] [3] [4 []]] [pop 0] [pop 1] [sum +] treestep')  # Combine replace and sum into one function.
     
    6
     
    -
    J('[4 [3 [] [7]]] [pop 0] [pop 1] [sum +] treestep')  # Combine replace and sum into one function.
    +
    J('[4 [3 [] [7]]] [pop 0] [pop 1] [sum +] treestep')  # Combine replace and sum into one function.
     
    3
    @@ -277,7 +277,7 @@ all nodes in a tree with this function:

    This doesn’t quite work:

    -
    J('[[3 0] [[2 0] [][]] [[9 0] [[5 0] [[4 0] [][]] [[8 0] [[6 0] [] [[7 0] [][]]][]]][]]] ["B"] [first] [i] treestep')
    +
    J('[[3 0] [[2 0] [][]] [[9 0] [[5 0] [[4 0] [][]] [[8 0] [[6 0] [] [[7 0] [][]]][]]][]]] ["B"] [first] [i] treestep')
     
    3 'B' 'B'
    @@ -299,7 +299,7 @@ depositing our results directly on the stack.

    [] [first] [flatten cons] treestep
     
    -
    J('[[3 0] [[2 0] [] []] [[9 0] [[5 0] [[4 0] [] []] [[8 0] [[6 0] [] [[7 0] [] []]] []]] []]]   [] [first] [flatten cons] treestep')
    +
    J('[[3 0] [[2 0] [] []] [[9 0] [[5 0] [[4 0] [] []] [[8 0] [[6 0] [] [[7 0] [] []]] []]] []]]   [] [first] [flatten cons] treestep')
     
    [3 2 9 5 4 8 6 7]
    @@ -322,7 +322,7 @@ depositing our results directly on the stack.

    [] [i roll< swons concat] [first] treestep
     
    -
    J('[[3 0] [[2 0] [] []] [[9 0] [[5 0] [[4 0] [] []] [[8 0] [[6 0] [] [[7 0] [] []]] []]] []]]   [] [uncons pop] [i roll< swons concat] treestep')
    +
    J('[[3 0] [[2 0] [] []] [[9 0] [[5 0] [[4 0] [] []] [[8 0] [[6 0] [] [[7 0] [] []]] []]] []]]   [] [uncons pop] [i roll< swons concat] treestep')
     
    [2 3 4 5 6 7 8 9]
    @@ -343,7 +343,7 @@ non-empty node is:

    [key value] N [left right] [K] C
     
    -
    J('[["key" "value"] ["left"] ["right"] ] ["B"] ["N"] ["C"] treegrind')
    +
    J('[["key" "value"] ["left"] ["right"] ] ["B"] ["N"] ["C"] treegrind')
     
    ['key' 'value'] 'N' [['left'] ['right']] [[not] ['B'] [uncons ['N'] dip] ['C'] genrec] 'C'
    @@ -353,21 +353,21 @@ non-empty node is:

    treegrind with step

    Iteration through the nodes

    -
    J('[[3 0] [[2 0] [] []] [[9 0] [[5 0] [[4 0] [] []] [[8 0] [[6 0] [] [[7 0] [] []]] []]] []]]   [pop] ["N"] [step] treegrind')
    +
    J('[[3 0] [[2 0] [] []] [[9 0] [[5 0] [[4 0] [] []] [[8 0] [[6 0] [] [[7 0] [] []]] []]] []]]   [pop] ["N"] [step] treegrind')
     
    [3 0] 'N' [2 0] 'N' [9 0] 'N' [5 0] 'N' [4 0] 'N' [8 0] 'N' [6 0] 'N' [7 0] 'N'
     

    Sum the nodes’ keys.

    -
    J('0 [[3 0] [[2 0] [] []] [[9 0] [[5 0] [[4 0] [] []] [[8 0] [[6 0] [] [[7 0] [] []]] []]] []]]   [pop] [first +] [step] treegrind')
    +
    J('0 [[3 0] [[2 0] [] []] [[9 0] [[5 0] [[4 0] [] []] [[8 0] [[6 0] [] [[7 0] [] []]] []]] []]]   [pop] [first +] [step] treegrind')
     
    44
     

    Rebuild the tree using map (imitating treestep.)

    -
    J('[[3 0] [[2 0] [] []] [[9 0] [[5 0] [[4 0] [] []] [[8 0] [[6 0] [] [[7 0] [] []]] []]] []]]   [] [[100 +] infra] [map cons] treegrind')
    +
    J('[[3 0] [[2 0] [] []] [[9 0] [[5 0] [[4 0] [] []] [[8 0] [[6 0] [] [[7 0] [] []]] []]] []]]   [] [[100 +] infra] [map cons] treegrind')
     
    [[103 0] [[102 0] [] []] [[109 0] [[105 0] [[104 0] [] []] [[108 0] [[106 0] [] [[107 0] [] []]] []]] []]]
    @@ -449,37 +449,37 @@ equal):

    To me, that seems simpler than the genrec version.

    -
    DefinitionWrapper.add_definitions('''
    +
    DefinitionWrapper.add_definitions('''
     
    -    T> == pop [first] dip i
    -    T< == pop [second] dip i
    -    E == roll> popop first
    -    P == roll< [roll< uncons swap] dip
    +    T> == pop [first] dip i
    +    T< == pop [second] dip i
    +    E == roll> popop first
    +    P == roll< [roll< uncons swap] dip
     
    -    Tree-get == [P [T>] [E] [T<] cmp] treegrind
    +    Tree-get == [P [T>] [E] [T<] cmp] treegrind
     
    -''', D)
    +''', D)
     
    -
    J('''\
    +
    J('''\
     
    -[[3 13] [[2 12] [] []] [[9 19] [[5 15] [[4 14] [] []] [[8 18] [[6 16] [] [[7 17] [] []]] []]] []]]
    +[[3 13] [[2 12] [] []] [[9 19] [[5 15] [[4 14] [] []] [[8 18] [[6 16] [] [[7 17] [] []]] []]] []]]
     
    -[] [5] Tree-get
    +[] [5] Tree-get
     
    -''')
    +''')
     
    15
     
    -
    J('''\
    +
    J('''\
     
    -[[3 13] [[2 12] [] []] [[9 19] [[5 15] [[4 14] [] []] [[8 18] [[6 16] [] [[7 17] [] []]] []]] []]]
    +[[3 13] [[2 12] [] []] [[9 19] [[5 15] [[4 14] [] []] [[8 18] [[6 16] [] [[7 17] [] []]] []]] []]]
     
    -[pop "nope"] [25] Tree-get
    +[pop "nope"] [25] Tree-get
     
    -''')
    +''')
     
    'nope'
    diff --git a/docs/sphinx_docs/_build/html/notebooks/TypeChecking.html b/docs/sphinx_docs/_build/html/notebooks/TypeChecking.html
    index 9c4d5bb..6e5002d 100644
    --- a/docs/sphinx_docs/_build/html/notebooks/TypeChecking.html
    +++ b/docs/sphinx_docs/_build/html/notebooks/TypeChecking.html
    @@ -35,33 +35,33 @@
                 
       

    Type Checking

    -
    import logging, sys
    +
    import logging, sys
     
    -logging.basicConfig(
    -  format='%(message)s',
    -  stream=sys.stdout,
    -  level=logging.INFO,
    -  )
    +logging.basicConfig(
    +  format='%(message)s',
    +  stream=sys.stdout,
    +  level=logging.INFO,
    +  )
     
    -
    from joy.utils.types import (
    -    doc_from_stack_effect,
    -    infer,
    -    reify,
    -    unify,
    -    FUNCTIONS,
    -    JoyTypeError,
    -)
    +
    from joy.utils.types import (
    +    doc_from_stack_effect,
    +    infer,
    +    reify,
    +    unify,
    +    FUNCTIONS,
    +    JoyTypeError,
    +)
     
    -
    D = FUNCTIONS.copy()
    -del D['product']
    -globals().update(D)
    +
    D = FUNCTIONS.copy()
    +del D['product']
    +globals().update(D)
     

    An Example

    -
    fi, fo = infer(pop, swap, rolldown, rrest, ccons)[0]
    +
    fi, fo = infer(pop, swap, rolldown, rrest, ccons)[0]
     
    25 (--) ∘ pop swap rolldown rrest ccons
    @@ -72,32 +72,32 @@ globals().update(D)
     40 ([a4 a5 ...1] a3 a2 a1 -- [a2 a3 ...1]) ∘
     
    -
    print doc_from_stack_effect(fi, fo)
    +
    print doc_from_stack_effect(fi, fo)
     
    ([a4 a5 ...1] a3 a2 a1 -- [a2 a3 ...1])
     
    -
    from joy.parser import text_to_expression
    -from joy.utils.stack import stack_to_string
    +
    from joy.parser import text_to_expression
    +from joy.utils.stack import stack_to_string
     
    -
    e = text_to_expression('0 1 2 [3 4]')  # reverse order
    -print stack_to_string(e)
    +
    e = text_to_expression('0 1 2 [3 4]')  # reverse order
    +print stack_to_string(e)
     
    [3 4] 2 1 0
     
    -
    u = unify(e, fi)[0]
    -u
    +
    u = unify(e, fi)[0]
    +u
     
    {a1: 0, a2: 1, a3: 2, a4: 3, a5: 4, s2: (), s1: ()}
     
    -
    g = reify(u, (fi, fo))
    -print doc_from_stack_effect(*g)
    +
    g = reify(u, (fi, fo))
    +print doc_from_stack_effect(*g)
     
    (... [3 4 ] 2 1 0 -- ... [1 2 ])
    @@ -106,18 +106,18 @@ print doc_from_stack_effect(*g)
     

    Unification Works “in Reverse”

    -
    e = text_to_expression('[2 3]')
    +
    e = text_to_expression('[2 3]')
     
    -
    u = unify(e, fo)[0]  # output side, not input side
    -u
    +
    u = unify(e, fo)[0]  # output side, not input side
    +u
     
    {a2: 2, a3: 3, s2: (), s1: ()}
     
    -
    g = reify(u, (fi, fo))
    -print doc_from_stack_effect(*g)
    +
    g = reify(u, (fi, fo))
    +print doc_from_stack_effect(*g)
     
    (... [a4 a5 ] 3 2 a1 -- ... [2 3 ])
    @@ -126,7 +126,7 @@ print doc_from_stack_effect(*g)
     

    Failing a Check

    -
    fi, fo = infer(dup, mul)[0]
    +
    fi, fo = infer(dup, mul)[0]
     
    25 (--) ∘ dup mul
    @@ -135,17 +135,17 @@ print doc_from_stack_effect(*g)
     31 (i1 -- i2) ∘
     
    -
    e = text_to_expression('"two"')
    -print stack_to_string(e)
    +
    e = text_to_expression('"two"')
    +print stack_to_string(e)
     
    'two'
     
    -
    try:
    -    unify(e, fi)
    -except JoyTypeError, err:
    -    print err
    +
    try:
    +    unify(e, fi)
    +except JoyTypeError, err:
    +    print err
     
    Cannot unify 'two' and f1.
    diff --git a/docs/sphinx_docs/_build/html/notebooks/Types.html b/docs/sphinx_docs/_build/html/notebooks/Types.html
    index 695d853..92d9131 100644
    --- a/docs/sphinx_docs/_build/html/notebooks/Types.html
    +++ b/docs/sphinx_docs/_build/html/notebooks/Types.html
    @@ -182,8 +182,8 @@ terms in the forms:

    Compiling pop∘swap∘roll<

    The simplest way to “compile” this function would be something like:

    -
    def poswrd(s, e, d):
    -    return rolldown(*swap(*pop(s, e, d)))
    +
    def poswrd(s, e, d):
    +    return rolldown(*swap(*pop(s, e, d)))
     

    However, internally this function would still be allocating tuples @@ -193,9 +193,9 @@ terms in the forms:

    We should be able to directly write out a Python function like:

    -
    def poswrd(stack):
    -    (_, (a, (b, (c, stack)))) = stack
    -    return (c, (b, (a, stack)))
    +
    def poswrd(stack):
    +    (_, (a, (b, (c, stack)))) = stack
    +    return (c, (b, (a, stack)))
     

    This eliminates the internal work of the first version. Because this @@ -335,9 +335,9 @@ actually pretty easy. I’ll explain below.

    From this stack effect comment it should be possible to construct the following Python code:

    -
    def F(stack):
    -    (_, (d, (c, ((a, (b, S0)), stack)))) = stack
    -    return (d, (c, S0)), stack
    +
    def F(stack):
    +    (_, (d, (c, ((a, (b, S0)), stack)))) = stack
    +    return (d, (c, S0)), stack
     
    @@ -348,96 +348,96 @@ following Python code:

    Representing Stack Effect Comments in Python

    I’m going to use pairs of tuples of type descriptors, which will be integers or tuples of type descriptors:

    -
    roll_dn = (1, 2, 3), (2, 3, 1)
    +
    roll_dn = (1, 2, 3), (2, 3, 1)
     
    -pop = (1,), ()
    +pop = (1,), ()
     
    -swap = (1, 2), (2, 1)
    +swap = (1, 2), (2, 1)
     

    compose()

    -
    def compose(f, g):
    +
    def compose(f, g):
     
    -    (f_in, f_out), (g_in, g_out) = f, g
    +    (f_in, f_out), (g_in, g_out) = f, g
     
    -    # First rule.
    -    #
    -    #       (a -- b) (-- d)
    -    #    ---------------------
    -    #         (a -- b d)
    +    # First rule.
    +    #
    +    #       (a -- b) (-- d)
    +    #    ---------------------
    +    #         (a -- b d)
     
    -    if not g_in:
    +    if not g_in:
     
    -        fg_in, fg_out = f_in, f_out + g_out
    +        fg_in, fg_out = f_in, f_out + g_out
     
    -    # Second rule.
    -    #
    -    #       (a --) (c -- d)
    -    #    ---------------------
    -    #         (c a -- d)
    +    # Second rule.
    +    #
    +    #       (a --) (c -- d)
    +    #    ---------------------
    +    #         (c a -- d)
     
    -    elif not f_out:
    +    elif not f_out:
     
    -        fg_in, fg_out = g_in + f_in, g_out
    +        fg_in, fg_out = g_in + f_in, g_out
     
    -    else: # Unify, update, recur.
    +    else: # Unify, update, recur.
     
    -        fo, gi = f_out[-1], g_in[-1]
    +        fo, gi = f_out[-1], g_in[-1]
     
    -        s = unify(gi, fo)
    +        s = unify(gi, fo)
     
    -        if s == False:  # s can also be the empty dict, which is ok.
    -            raise TypeError('Cannot unify %r and %r.' % (fo, gi))
    +        if s == False:  # s can also be the empty dict, which is ok.
    +            raise TypeError('Cannot unify %r and %r.' % (fo, gi))
     
    -        f_g = (f_in, f_out[:-1]), (g_in[:-1], g_out)
    +        f_g = (f_in, f_out[:-1]), (g_in[:-1], g_out)
     
    -        if s: f_g = update(s, f_g)
    +        if s: f_g = update(s, f_g)
     
    -        fg_in, fg_out = compose(*f_g)
    +        fg_in, fg_out = compose(*f_g)
     
    -    return fg_in, fg_out
    +    return fg_in, fg_out
     

    unify()

    -
    def unify(u, v, s=None):
    -    if s is None:
    -        s = {}
    +
    def unify(u, v, s=None):
    +    if s is None:
    +        s = {}
     
    -    if isinstance(u, int):
    -        s[u] = v
    -    elif isinstance(v, int):
    -        s[v] = u
    -    else:
    -        s = False
    +    if isinstance(u, int):
    +        s[u] = v
    +    elif isinstance(v, int):
    +        s[v] = u
    +    else:
    +        s = False
     
    -    return s
    +    return s
     

    update()

    -
    def update(s, term):
    -    if not isinstance(term, tuple):
    -        return s.get(term, term)
    -    return tuple(update(s, inner) for inner in term)
    +
    def update(s, term):
    +    if not isinstance(term, tuple):
    +        return s.get(term, term)
    +    return tuple(update(s, inner) for inner in term)
     

    relabel()

    -
    def relabel(left, right):
    -    return left, _1000(right)
    +
    def relabel(left, right):
    +    return left, _1000(right)
     
    -def _1000(right):
    -    if not isinstance(right, tuple):
    -        return 1000 + right
    -    return tuple(_1000(n) for n in right)
    +def _1000(right):
    +    if not isinstance(right, tuple):
    +        return 1000 + right
    +    return tuple(_1000(n) for n in right)
     
    -relabel(pop, swap)
    +relabel(pop, swap)
     
    (((1,), ()), ((1001, 1002), (1002, 1001)))
    @@ -446,21 +446,21 @@ relabel(pop, swap)
     

    delabel()

    -
    def delabel(f):
    -    s = {u: i for i, u in enumerate(sorted(_unique(f)))}
    -    return update(s, f)
    +
    def delabel(f):
    +    s = {u: i for i, u in enumerate(sorted(_unique(f)))}
    +    return update(s, f)
     
    -def _unique(f, seen=None):
    -    if seen is None:
    -        seen = set()
    -    if not isinstance(f, tuple):
    -        seen.add(f)
    -    else:
    -        for inner in f:
    -            _unique(inner, seen)
    -    return seen
    +def _unique(f, seen=None):
    +    if seen is None:
    +        seen = set()
    +    if not isinstance(f, tuple):
    +        seen.add(f)
    +    else:
    +        for inner in f:
    +            _unique(inner, seen)
    +    return seen
     
    -delabel(relabel(pop, swap))
    +delabel(relabel(pop, swap))
     
    (((0,), ()), ((1, 2), (2, 1)))
    @@ -472,39 +472,39 @@ delabel(relabel(pop, swap))
     

    At last we put it all together in a function C() that accepts two stack effect comments and returns their composition (or raises and exception if they can’t be composed due to type conflicts.)

    -
    def C(f, g):
    -    f, g = relabel(f, g)
    -    fg = compose(f, g)
    -    return delabel(fg)
    +
    def C(f, g):
    +    f, g = relabel(f, g)
    +    fg = compose(f, g)
    +    return delabel(fg)
     

    Let’s try it out.

    -
    C(pop, swap)
    +
    C(pop, swap)
     
    ((1, 2, 0), (2, 1))
     
    -
    C(C(pop, swap), roll_dn)
    +
    C(C(pop, swap), roll_dn)
     
    ((3, 1, 2, 0), (2, 1, 3))
     
    -
    C(swap, roll_dn)
    +
    C(swap, roll_dn)
     
    ((2, 0, 1), (1, 0, 2))
     
    -
    C(pop, C(swap, roll_dn))
    +
    C(pop, C(swap, roll_dn))
     
    ((3, 1, 2, 0), (2, 1, 3))
     
    -
    poswrd = reduce(C, (pop, swap, roll_dn))
    -poswrd
    +
    poswrd = reduce(C, (pop, swap, roll_dn))
    +poswrd
     
    ((3, 1, 2, 0), (2, 1, 3))
    @@ -516,12 +516,12 @@ poswrd
     

    Here’s that trick to represent functions like rest and cons that manipulate stacks. We use a cons-list of tuples and give the tails their own numbers. Then everything above already works.

    -
    rest = ((1, 2),), (2,)
    +
    rest = ((1, 2),), (2,)
     
    -cons = (1, 2), ((1, 2),)
    +cons = (1, 2), ((1, 2),)
     
    -
    C(poswrd, rest)
    +
    C(poswrd, rest)
     
    (((3, 4), 1, 2, 0), (2, 1, 4))
    @@ -542,9 +542,9 @@ cons = (1, 2), ((1, 2),)
     }
     
    -
    F = reduce(C, (pop, swap, roll_dn, rest, rest, cons, cons))
    +
    F = reduce(C, (pop, swap, roll_dn, rest, rest, cons, cons))
     
    -F
    +F
     
    (((3, (4, 5)), 1, 2, 0), ((2, (1, 5)),))
    @@ -560,13 +560,13 @@ F
     

    Dealing with cons and uncons

    However, if we try to compose e.g. cons and uncons it won’t work:

    -
    uncons = ((1, 2),), (1, 2)
    +
    uncons = ((1, 2),), (1, 2)
     
    -
    try:
    -    C(cons, uncons)
    -except Exception, e:
    -    print e
    +
    try:
    +    C(cons, uncons)
    +except Exception, e:
    +    print e
     
    Cannot unify (1, 2) and (1001, 1002).
    @@ -577,36 +577,36 @@ except Exception, e:
     

    The problem is that the unify() function as written doesn’t handle the case when both terms are tuples. We just have to add a clause to deal with this recursively:

    -
    def unify(u, v, s=None):
    -    if s is None:
    -        s = {}
    -    elif s:
    -        u = update(s, u)
    -        v = update(s, v)
    +
    def unify(u, v, s=None):
    +    if s is None:
    +        s = {}
    +    elif s:
    +        u = update(s, u)
    +        v = update(s, v)
     
    -    if isinstance(u, int):
    -        s[u] = v
    +    if isinstance(u, int):
    +        s[u] = v
     
    -    elif isinstance(v, int):
    -        s[v] = u
    +    elif isinstance(v, int):
    +        s[v] = u
     
    -    elif isinstance(u, tuple) and isinstance(v, tuple):
    +    elif isinstance(u, tuple) and isinstance(v, tuple):
     
    -        if len(u) != 2 or len(v) != 2:
    -            # Not a type error, caller passed in a bad value.
    -            raise ValueError(repr((u, v)))  # FIXME this message sucks.
    +        if len(u) != 2 or len(v) != 2:
    +            # Not a type error, caller passed in a bad value.
    +            raise ValueError(repr((u, v)))  # FIXME this message sucks.
     
    -        (a, b), (c, d) = u, v
    -        s = unify(a, c, s)
    -        if s != False:
    -            s = unify(b, d, s)
    -    else:
    -        s = False
    +        (a, b), (c, d) = u, v
    +        s = unify(a, c, s)
    +        if s != False:
    +            s = unify(b, d, s)
    +    else:
    +        s = False
     
    -    return s
    +    return s
     
    -
    C(cons, uncons)
    +
    C(cons, uncons)
     
    ((0, 1), (0, 1))
    @@ -618,13 +618,13 @@ deal with this recursively:

    Part III: Compiling Yin Functions

    Now consider the Python function we would like to derive:

    -
    def F_python(stack):
    -    (_, (d, (c, ((a, (b, S0)), stack)))) = stack
    -    return (d, (c, S0)), stack
    +
    def F_python(stack):
    +    (_, (d, (c, ((a, (b, S0)), stack)))) = stack
    +    return (d, (c, S0)), stack
     

    And compare it to the input stack effect comment tuple we just computed:

    -
    F[0]
    +
    F[0]
     
    ((3, (4, 5)), 1, 2, 0)
    @@ -646,7 +646,7 @@ stack effect comment tuple, just in the reverse order:

    Eh?

    And the return tuple

    -
    F[1]
    +
    F[1]
     
    ((2, (1, 5)),)
    @@ -666,21 +666,21 @@ effect.)

    Python Identifiers

    We want to substitute Python identifiers for the integers. I’m going to repurpose joy.parser.Symbol class for this:

    -
    from collections import defaultdict
    -from joy.parser import Symbol
    +
    from collections import defaultdict
    +from joy.parser import Symbol
     
     
    -def _names_for():
    -    I = iter(xrange(1000))
    -    return lambda: Symbol('a%i' % next(I))
    +def _names_for():
    +    I = iter(xrange(1000))
    +    return lambda: Symbol('a%i' % next(I))
     
     
    -def identifiers(term, s=None):
    -    if s is None:
    -        s = defaultdict(_names_for())
    -    if isinstance(term, int):
    -        return s[term]
    -    return tuple(identifiers(inner, s) for inner in term)
    +def identifiers(term, s=None):
    +    if s is None:
    +        s = defaultdict(_names_for())
    +    if isinstance(term, int):
    +        return s[term]
    +    return tuple(identifiers(inner, s) for inner in term)
     
    @@ -690,36 +690,36 @@ def identifiers(term, s=None): effect comment tuples to reasonable text format. There are some details in how this code works that related to stuff later in the notebook, so you should skip it for now and read it later if you’re interested.

    -
    def doc_from_stack_effect(inputs, outputs):
    -    return '(%s--%s)' % (
    -        ' '.join(map(_to_str, inputs + ('',))),
    -        ' '.join(map(_to_str, ('',) + outputs))
    -    )
    +
    def doc_from_stack_effect(inputs, outputs):
    +    return '(%s--%s)' % (
    +        ' '.join(map(_to_str, inputs + ('',))),
    +        ' '.join(map(_to_str, ('',) + outputs))
    +    )
     
     
    -def _to_str(term):
    -    if not isinstance(term, tuple):
    -        try:
    -            t = term.prefix == 's'
    -        except AttributeError:
    -            return str(term)
    -        return '[.%i.]' % term.number if t else str(term)
    +def _to_str(term):
    +    if not isinstance(term, tuple):
    +        try:
    +            t = term.prefix == 's'
    +        except AttributeError:
    +            return str(term)
    +        return '[.%i.]' % term.number if t else str(term)
     
    -    a = []
    -    while term and isinstance(term, tuple):
    -        item, term = term
    -        a.append(_to_str(item))
    +    a = []
    +    while term and isinstance(term, tuple):
    +        item, term = term
    +        a.append(_to_str(item))
     
    -    try:
    -        n = term.number
    -    except AttributeError:
    -        n = term
    -    else:
    -        if term.prefix != 's':
    -            raise ValueError('Stack label: %s' % (term,))
    +    try:
    +        n = term.number
    +    except AttributeError:
    +        n = term
    +    else:
    +        if term.prefix != 's':
    +            raise ValueError('Stack label: %s' % (term,))
     
    -    a.append('.%s.' % (n,))
    -    return '[%s]' % ' '.join(a)
    +    a.append('.%s.' % (n,))
    +    return '[%s]' % ' '.join(a)
     
    @@ -728,25 +728,25 @@ def _to_str(term):

    Now we can write a compiler function to emit Python source code. (The underscore suffix distiguishes it from the built-in compile() function.)

    -
    def compile_(name, f, doc=None):
    -    if doc is None:
    -        doc = doc_from_stack_effect(*f)
    -    inputs, outputs = identifiers(f)
    -    i = o = Symbol('stack')
    -    for term in inputs:
    -        i = term, i
    -    for term in outputs:
    -        o = term, o
    -    return '''def %s(stack):
    -    """%s"""
    -    %s = stack
    -    return %s''' % (name, doc, i, o)
    +
    def compile_(name, f, doc=None):
    +    if doc is None:
    +        doc = doc_from_stack_effect(*f)
    +    inputs, outputs = identifiers(f)
    +    i = o = Symbol('stack')
    +    for term in inputs:
    +        i = term, i
    +    for term in outputs:
    +        o = term, o
    +    return '''def %s(stack):
    +    """%s"""
    +    %s = stack
    +    return %s''' % (name, doc, i, o)
     

    Here it is in action:

    -
    source = compile_('F', F)
    +
    source = compile_('F', F)
     
    -print source
    +print source
     
    def F(stack):
    @@ -756,31 +756,31 @@ print source
     

    Compare:

    -
    def F_python(stack):
    -    (_, (d, (c, ((a, (b, S0)), stack)))) = stack
    -    return ((d, (c, S0)), stack)
    +
    def F_python(stack):
    +    (_, (d, (c, ((a, (b, S0)), stack)))) = stack
    +    return ((d, (c, S0)), stack)
     

    Next steps:

    -
    L = {}
    +
    L = {}
     
    -eval(compile(source, '__main__', 'single'), {}, L)
    +eval(compile(source, '__main__', 'single'), {}, L)
     
    -L['F']
    +L['F']
     
    <function F>
     

    Let’s try it out:

    -
    from notebook_preamble import D, J, V
    -from joy.library import SimpleFunctionWrapper
    +
    from notebook_preamble import D, J, V
    +from joy.library import SimpleFunctionWrapper
     
    -
    D['F'] = SimpleFunctionWrapper(L['F'])
    +
    D['F'] = SimpleFunctionWrapper(L['F'])
     
    -
    J('[4 5 ...] 2 3 1 F')
    +
    J('[4 5 ...] 2 3 1 F')
     
    [3 2 ...]
    @@ -800,33 +800,33 @@ this might be less helpful.

    Compiling Library Functions

    We can use compile_() to generate many primitives in the library from their stack effect comments:

    -
    def defs():
    +
    def defs():
     
    -    rolldown = (1, 2, 3), (2, 3, 1)
    +    rolldown = (1, 2, 3), (2, 3, 1)
     
    -    rollup = (1, 2, 3), (3, 1, 2)
    +    rollup = (1, 2, 3), (3, 1, 2)
     
    -    pop = (1,), ()
    +    pop = (1,), ()
     
    -    swap = (1, 2), (2, 1)
    +    swap = (1, 2), (2, 1)
     
    -    rest = ((1, 2),), (2,)
    +    rest = ((1, 2),), (2,)
     
    -    rrest = C(rest, rest)
    +    rrest = C(rest, rest)
     
    -    cons = (1, 2), ((1, 2),)
    +    cons = (1, 2), ((1, 2),)
     
    -    uncons = ((1, 2),), (1, 2)
    +    uncons = ((1, 2),), (1, 2)
     
    -    swons = C(swap, cons)
    +    swons = C(swap, cons)
     
    -    return locals()
    +    return locals()
     
    -
    for name, stack_effect_comment in sorted(defs().items()):
    -    print
    -    print compile_(name, stack_effect_comment)
    -    print
    +
    for name, stack_effect_comment in sorted(defs().items()):
    +    print
    +    print compile_(name, stack_effect_comment)
    +    print
     
    def cons(stack):
    @@ -966,57 +966,57 @@ and t
     Python class hierarchy of Joy types and use the issubclass() method
     to establish domain ordering, as well as other handy behaviour that will
     make it fairly easy to reuse most of the code above.

    -
    class AnyJoyType(object):
    +
    class AnyJoyType(object):
     
    -    prefix = 'a'
    +    prefix = 'a'
     
    -    def __init__(self, number):
    -        self.number = number
    +    def __init__(self, number):
    +        self.number = number
     
    -    def __repr__(self):
    -        return self.prefix + str(self.number)
    +    def __repr__(self):
    +        return self.prefix + str(self.number)
     
    -    def __eq__(self, other):
    -        return (
    -            isinstance(other, self.__class__)
    -            and other.prefix == self.prefix
    -            and other.number == self.number
    -        )
    +    def __eq__(self, other):
    +        return (
    +            isinstance(other, self.__class__)
    +            and other.prefix == self.prefix
    +            and other.number == self.number
    +        )
     
    -    def __ge__(self, other):
    -        return issubclass(other.__class__, self.__class__)
    +    def __ge__(self, other):
    +        return issubclass(other.__class__, self.__class__)
     
    -    def __add__(self, other):
    -        return self.__class__(self.number + other)
    -    __radd__ = __add__
    +    def __add__(self, other):
    +        return self.__class__(self.number + other)
    +    __radd__ = __add__
     
    -    def __hash__(self):
    -        return hash(repr(self))
    +    def __hash__(self):
    +        return hash(repr(self))
     
     
    -class NumberJoyType(AnyJoyType): prefix = 'n'
    -class FloatJoyType(NumberJoyType): prefix = 'f'
    -class IntJoyType(FloatJoyType): prefix = 'i'
    +class NumberJoyType(AnyJoyType): prefix = 'n'
    +class FloatJoyType(NumberJoyType): prefix = 'f'
    +class IntJoyType(FloatJoyType): prefix = 'i'
     
     
    -class StackJoyType(AnyJoyType):
    -    prefix = 's'
    +class StackJoyType(AnyJoyType):
    +    prefix = 's'
     
     
    -_R = range(10)
    -A = map(AnyJoyType, _R)
    -N = map(NumberJoyType, _R)
    -S = map(StackJoyType, _R)
    +_R = range(10)
    +A = map(AnyJoyType, _R)
    +N = map(NumberJoyType, _R)
    +S = map(StackJoyType, _R)
     

    Mess with it a little:

    -
    from itertools import permutations
    +
    from itertools import permutations
     

    “Any” types can be specialized to numbers and stacks, but not vice versa:

    -
    for a, b in permutations((A[0], N[0], S[0]), 2):
    -    print a, '>=', b, '->', a >= b
    +
    for a, b in permutations((A[0], N[0], S[0]), 2):
    +    print a, '>=', b, '->', a >= b
     
    a0 >= n0 -> True
    @@ -1030,8 +1030,8 @@ versa:

    Our crude Numerical Tower of numbers > floats > integers works as well (but we’re not going to use it yet):

    -
    for a, b in permutations((A[0], N[0], FloatJoyType(0), IntJoyType(0)), 2):
    -    print a, '>=', b, '->', a >= b
    +
    for a, b in permutations((A[0], N[0], FloatJoyType(0), IntJoyType(0)), 2):
    +    print a, '>=', b, '->', a >= b
     
    a0 >= n0 -> True
    @@ -1051,18 +1051,18 @@ Tower of numbers >
     

    Typing sqr

    -
    dup = (A[1],), (A[1], A[1])
    +
    dup = (A[1],), (A[1], A[1])
     
    -mul = (N[1], N[2]), (N[3],)
    +mul = (N[1], N[2]), (N[3],)
     
    -
    dup
    +
    dup
     
    ((a1,), (a1, a1))
     
    -
    mul
    +
    mul
     
    ((n1, n2), (n3,))
    @@ -1072,9 +1072,9 @@ mul = (N[1], N[2]), (N[3],)
     

    Modifying the Inferencer

    Re-labeling still works fine:

    -
    foo = relabel(dup, mul)
    +
    foo = relabel(dup, mul)
     
    -foo
    +foo
     
    (((a1,), (a1, a1)), ((n1001, n1002), (n1003,)))
    @@ -1084,28 +1084,28 @@ foo
     

    delabel() version 2

    The delabel() function needs an overhaul. It now has to keep track of how many labels of each domain it has “seen”.

    -
    from collections import Counter
    +
    from collections import Counter
     
     
    -def delabel(f, seen=None, c=None):
    -    if seen is None:
    -        assert c is None
    -        seen, c = {}, Counter()
    +def delabel(f, seen=None, c=None):
    +    if seen is None:
    +        assert c is None
    +        seen, c = {}, Counter()
     
    -    try:
    -        return seen[f]
    -    except KeyError:
    -        pass
    +    try:
    +        return seen[f]
    +    except KeyError:
    +        pass
     
    -    if not isinstance(f, tuple):
    -        seen[f] = f.__class__(c[f.prefix] + 1)
    -        c[f.prefix] += 1
    -        return seen[f]
    +    if not isinstance(f, tuple):
    +        seen[f] = f.__class__(c[f.prefix] + 1)
    +        c[f.prefix] += 1
    +        return seen[f]
     
    -    return tuple(delabel(inner, seen, c) for inner in f)
    +    return tuple(delabel(inner, seen, c) for inner in f)
     
    -
    delabel(foo)
    +
    delabel(foo)
     
    (((a1,), (a1, a1)), ((n1, n2), (n3,)))
    @@ -1114,112 +1114,112 @@ def delabel(f, seen=None, c=None):
     

    unify() version 3

    -
    def unify(u, v, s=None):
    -    if s is None:
    -        s = {}
    -    elif s:
    -        u = update(s, u)
    -        v = update(s, v)
    +
    def unify(u, v, s=None):
    +    if s is None:
    +        s = {}
    +    elif s:
    +        u = update(s, u)
    +        v = update(s, v)
     
    -    if u == v:
    -        return s
    +    if u == v:
    +        return s
     
    -    if isinstance(u, AnyJoyType) and isinstance(v, AnyJoyType):
    -        if u >= v:
    -            s[u] = v
    -            return s
    -        if v >= u:
    -            s[v] = u
    -            return s
    -        raise TypeError('Cannot unify %r and %r.' % (u, v))
    +    if isinstance(u, AnyJoyType) and isinstance(v, AnyJoyType):
    +        if u >= v:
    +            s[u] = v
    +            return s
    +        if v >= u:
    +            s[v] = u
    +            return s
    +        raise TypeError('Cannot unify %r and %r.' % (u, v))
     
    -    if isinstance(u, tuple) and isinstance(v, tuple):
    -        if len(u) != len(v) != 2:
    -            raise TypeError(repr((u, v)))
    -        for uu, vv in zip(u, v):
    -            s = unify(uu, vv, s)
    -            if s == False: # (instead of a substitution dict.)
    -                break
    -        return s
    +    if isinstance(u, tuple) and isinstance(v, tuple):
    +        if len(u) != len(v) != 2:
    +            raise TypeError(repr((u, v)))
    +        for uu, vv in zip(u, v):
    +            s = unify(uu, vv, s)
    +            if s == False: # (instead of a substitution dict.)
    +                break
    +        return s
     
    -    if isinstance(v, tuple):
    -        if not stacky(u):
    -            raise TypeError('Cannot unify %r and %r.' % (u, v))
    -        s[u] = v
    -        return s
    +    if isinstance(v, tuple):
    +        if not stacky(u):
    +            raise TypeError('Cannot unify %r and %r.' % (u, v))
    +        s[u] = v
    +        return s
     
    -    if isinstance(u, tuple):
    -        if not stacky(v):
    -            raise TypeError('Cannot unify %r and %r.' % (v, u))
    -        s[v] = u
    -        return s
    +    if isinstance(u, tuple):
    +        if not stacky(v):
    +            raise TypeError('Cannot unify %r and %r.' % (v, u))
    +        s[v] = u
    +        return s
     
    -    return False
    +    return False
     
     
    -def stacky(thing):
    -    return thing.__class__ in {AnyJoyType, StackJoyType}
    +def stacky(thing):
    +    return thing.__class__ in {AnyJoyType, StackJoyType}
     

    Rewrite the stack effect comments:

    -
    def defs():
    +
    def defs():
     
    -    rolldown = (A[1], A[2], A[3]), (A[2], A[3], A[1])
    +    rolldown = (A[1], A[2], A[3]), (A[2], A[3], A[1])
     
    -    rollup = (A[1], A[2], A[3]), (A[3], A[1], A[2])
    +    rollup = (A[1], A[2], A[3]), (A[3], A[1], A[2])
     
    -    pop = (A[1],), ()
    +    pop = (A[1],), ()
     
    -    popop = (A[2], A[1],), ()
    +    popop = (A[2], A[1],), ()
     
    -    popd = (A[2], A[1],), (A[1],)
    +    popd = (A[2], A[1],), (A[1],)
     
    -    popdd = (A[3], A[2], A[1],), (A[2], A[1],)
    +    popdd = (A[3], A[2], A[1],), (A[2], A[1],)
     
    -    swap = (A[1], A[2]), (A[2], A[1])
    +    swap = (A[1], A[2]), (A[2], A[1])
     
    -    rest = ((A[1], S[1]),), (S[1],)
    +    rest = ((A[1], S[1]),), (S[1],)
     
    -    rrest = C(rest, rest)
    +    rrest = C(rest, rest)
     
    -    cons = (A[1], S[1]), ((A[1], S[1]),)
    +    cons = (A[1], S[1]), ((A[1], S[1]),)
     
    -    ccons = C(cons, cons)
    +    ccons = C(cons, cons)
     
    -    uncons = ((A[1], S[1]),), (A[1], S[1])
    +    uncons = ((A[1], S[1]),), (A[1], S[1])
     
    -    swons = C(swap, cons)
    +    swons = C(swap, cons)
     
    -    dup = (A[1],), (A[1], A[1])
    +    dup = (A[1],), (A[1], A[1])
     
    -    dupd = (A[2], A[1]), (A[2], A[2], A[1])
    +    dupd = (A[2], A[1]), (A[2], A[2], A[1])
     
    -    mul = (N[1], N[2]), (N[3],)
    +    mul = (N[1], N[2]), (N[3],)
     
    -    sqrt = C(dup, mul)
    +    sqrt = C(dup, mul)
     
    -    first = ((A[1], S[1]),), (A[1],)
    +    first = ((A[1], S[1]),), (A[1],)
     
    -    second = C(rest, first)
    +    second = C(rest, first)
     
    -    third = C(rest, second)
    +    third = C(rest, second)
     
    -    tuck = (A[2], A[1]), (A[1], A[2], A[1])
    +    tuck = (A[2], A[1]), (A[1], A[2], A[1])
     
    -    over = (A[2], A[1]), (A[2], A[1], A[2])
    +    over = (A[2], A[1]), (A[2], A[1], A[2])
     
    -    succ = pred = (N[1],), (N[2],)
    +    succ = pred = (N[1],), (N[2],)
     
    -    divmod_ = pm = (N[2], N[1]), (N[4], N[3])
    +    divmod_ = pm = (N[2], N[1]), (N[4], N[3])
     
    -    return locals()
    +    return locals()
     
    -
    DEFS = defs()
    +
    DEFS = defs()
     
    -
    for name, stack_effect_comment in sorted(DEFS.items()):
    -    print name, '=', doc_from_stack_effect(*stack_effect_comment)
    +
    for name, stack_effect_comment in sorted(DEFS.items()):
    +    print name, '=', doc_from_stack_effect(*stack_effect_comment)
     
    ccons = (a1 a2 [.1.] -- [a1 a2 .1.])
    @@ -1250,27 +1250,27 @@ def stacky(thing):
     uncons = ([a1 .1.] -- a1 [.1.])
     
    -
    globals().update(DEFS)
    +
    globals().update(DEFS)
     

    Compose dup and mul

    -
    C(dup, mul)
    +
    C(dup, mul)
     
    ((n1,), (n2,))
     

    Revisit the F function, works fine.

    -
    F = reduce(C, (pop, swap, rolldown, rest, rest, cons, cons))
    -F
    +
    F = reduce(C, (pop, swap, rolldown, rest, rest, cons, cons))
    +F
     
    (((a1, (a2, s1)), a3, a4, a5), ((a4, (a3, s1)),))
     
    -
    print doc_from_stack_effect(*F)
    +
    print doc_from_stack_effect(*F)
     
    ([a1 a2 .1.] a3 a4 a5 -- [a4 a3 .1.])
    @@ -1278,26 +1278,26 @@ F
     

    Some otherwise inefficient functions are no longer to be feared. We can also get the effect of combinators in some limited cases.

    -
    def neato(*funcs):
    -    print doc_from_stack_effect(*reduce(C, funcs))
    +
    def neato(*funcs):
    +    print doc_from_stack_effect(*reduce(C, funcs))
     
    -
    # e.g. [swap] dip
    -neato(rollup, swap, rolldown)
    +
    # e.g. [swap] dip
    +neato(rollup, swap, rolldown)
     
    (a1 a2 a3 -- a2 a1 a3)
     
    -
    # e.g. [popop] dipd
    -neato(popdd, rolldown, pop)
    +
    # e.g. [popop] dipd
    +neato(popdd, rolldown, pop)
     
    (a1 a2 a3 a4 -- a3 a4)
     
    -
    # Reverse the order of the top three items.
    -neato(rollup, swap)
    +
    # Reverse the order of the top three items.
    +neato(rollup, swap)
     
    (a1 a2 a3 -- a3 a2 a1)
    @@ -1308,22 +1308,22 @@ neato(rollup, swap)
     

    compile_() version 2

    Because the type labels represent themselves as valid Python identifiers the compile_() function doesn’t need to generate them anymore:

    -
    def compile_(name, f, doc=None):
    -    inputs, outputs = f
    -    if doc is None:
    -        doc = doc_from_stack_effect(inputs, outputs)
    -    i = o = Symbol('stack')
    -    for term in inputs:
    -        i = term, i
    -    for term in outputs:
    -        o = term, o
    -    return '''def %s(stack):
    -    """%s"""
    -    %s = stack
    -    return %s''' % (name, doc, i, o)
    +
    def compile_(name, f, doc=None):
    +    inputs, outputs = f
    +    if doc is None:
    +        doc = doc_from_stack_effect(inputs, outputs)
    +    i = o = Symbol('stack')
    +    for term in inputs:
    +        i = term, i
    +    for term in outputs:
    +        o = term, o
    +    return '''def %s(stack):
    +    """%s"""
    +    %s = stack
    +    return %s''' % (name, doc, i, o)
     
    -
    print compile_('F', F)
    +
    print compile_('F', F)
     
    def F(stack):
    @@ -1334,7 +1334,7 @@ the compile_()
     

    But it cannot magically create new functions that involve e.g. math and such. Note that this is not a sqr function implementation:

    -
    print compile_('sqr', C(dup, mul))
    +
    print compile_('sqr', C(dup, mul))
     
    def sqr(stack):
    @@ -1356,16 +1356,16 @@ functions (at least) are already wrappers it should be straightforward.)

    The functions that can be compiled are the ones that have only AnyJoyType and StackJoyType labels in their stack effect comments. We can write a function to check that:

    -
    from itertools import imap
    +
    from itertools import imap
     
     
    -def compilable(f):
    -    return isinstance(f, tuple) and all(imap(compilable, f)) or stacky(f)
    +def compilable(f):
    +    return isinstance(f, tuple) and all(imap(compilable, f)) or stacky(f)
     
    -
    for name, stack_effect_comment in sorted(defs().items()):
    -    if compilable(stack_effect_comment):
    -        print name, '=', doc_from_stack_effect(*stack_effect_comment)
    +
    for name, stack_effect_comment in sorted(defs().items()):
    +    if compilable(stack_effect_comment):
    +        print name, '=', doc_from_stack_effect(*stack_effect_comment)
     
    ccons = (a1 a2 [.1.] -- [a1 a2 .1.])
    @@ -1465,36 +1465,36 @@ first two rules’ 
     the “truthiness” of StackJoyType to false to let e.g.
     joy.utils.stack.concat work with our stack effect comment cons-list
     tuples.)

    -
    def compose(f, g):
    -    (f_in, f_out), (g_in, g_out) = f, g
    -    s = unify(g_in, f_out)
    -    if s == False:  # s can also be the empty dict, which is ok.
    -        raise TypeError('Cannot unify %r and %r.' % (f_out, g_in))
    -    return update(s, (f_in, g_out))
    +
    def compose(f, g):
    +    (f_in, f_out), (g_in, g_out) = f, g
    +    s = unify(g_in, f_out)
    +    if s == False:  # s can also be the empty dict, which is ok.
    +        raise TypeError('Cannot unify %r and %r.' % (f_out, g_in))
    +    return update(s, (f_in, g_out))
     

    I don’t want to rewrite all the defs myself, so I’ll write a little conversion function instead. This is programmer’s laziness.

    -
    def sequence_to_stack(seq, stack=StackJoyType(23)):
    -    for item in seq: stack = item, stack
    -    return stack
    +
    def sequence_to_stack(seq, stack=StackJoyType(23)):
    +    for item in seq: stack = item, stack
    +    return stack
     
    -NEW_DEFS = {
    -    name: (sequence_to_stack(i), sequence_to_stack(o))
    -    for name, (i, o) in DEFS.iteritems()
    -}
    -NEW_DEFS['stack'] = S[0], (S[0], S[0])
    -NEW_DEFS['swaack'] = (S[1], S[0]), (S[0], S[1])
    -globals().update(NEW_DEFS)
    +NEW_DEFS = {
    +    name: (sequence_to_stack(i), sequence_to_stack(o))
    +    for name, (i, o) in DEFS.iteritems()
    +}
    +NEW_DEFS['stack'] = S[0], (S[0], S[0])
    +NEW_DEFS['swaack'] = (S[1], S[0]), (S[0], S[1])
    +globals().update(NEW_DEFS)
     
    -
    C(stack, uncons)
    +
    C(stack, uncons)
     
    ((a1, s1), (s1, (a1, (a1, s1))))
     
    -
    reduce(C, (stack, uncons, uncons))
    +
    reduce(C, (stack, uncons, uncons))
     
    ((a1, (a2, s1)), (s1, (a2, (a1, (a1, (a2, s1))))))
    @@ -1506,55 +1506,55 @@ globals().update(NEW_DEFS)
     

    doc_from_stack_effect() version 2

    Clunky junk, but it will suffice for now.

    -
    def doc_from_stack_effect(inputs, outputs):
    -    switch = [False]  # Do we need to display the '...' for the rest of the main stack?
    -    i, o = _f(inputs, switch), _f(outputs, switch)
    -    if switch[0]:
    -        i.append('...')
    -        o.append('...')
    -    return '(%s--%s)' % (
    -        ' '.join(reversed([''] + i)),
    -        ' '.join(reversed(o + [''])),
    -    )
    +
    def doc_from_stack_effect(inputs, outputs):
    +    switch = [False]  # Do we need to display the '...' for the rest of the main stack?
    +    i, o = _f(inputs, switch), _f(outputs, switch)
    +    if switch[0]:
    +        i.append('...')
    +        o.append('...')
    +    return '(%s--%s)' % (
    +        ' '.join(reversed([''] + i)),
    +        ' '.join(reversed(o + [''])),
    +    )
     
     
    -def _f(term, switch):
    -    a = []
    -    while term and isinstance(term, tuple):
    -        item, term = term
    -        a.append(item)
    -    assert isinstance(term, StackJoyType), repr(term)
    -    a = [_to_str(i, term, switch) for i in a]
    -    return a
    +def _f(term, switch):
    +    a = []
    +    while term and isinstance(term, tuple):
    +        item, term = term
    +        a.append(item)
    +    assert isinstance(term, StackJoyType), repr(term)
    +    a = [_to_str(i, term, switch) for i in a]
    +    return a
     
     
    -def _to_str(term, stack, switch):
    -    if not isinstance(term, tuple):
    -        if term == stack:
    -            switch[0] = True
    -            return '[...]'
    -        return (
    -            '[.%i.]' % term.number
    -            if isinstance(term, StackJoyType)
    -            else str(term)
    -        )
    +def _to_str(term, stack, switch):
    +    if not isinstance(term, tuple):
    +        if term == stack:
    +            switch[0] = True
    +            return '[...]'
    +        return (
    +            '[.%i.]' % term.number
    +            if isinstance(term, StackJoyType)
    +            else str(term)
    +        )
     
    -    a = []
    -    while term and isinstance(term, tuple):
    -        item, term = term
    -        a.append(_to_str(item, stack, switch))
    -    assert isinstance(term, StackJoyType), repr(term)
    -    if term == stack:
    -        switch[0] = True
    -        end = '...'
    -    else:
    -        end = '.%i.' % term.number
    -    a.append(end)
    -    return '[%s]' % ' '.join(a)
    +    a = []
    +    while term and isinstance(term, tuple):
    +        item, term = term
    +        a.append(_to_str(item, stack, switch))
    +    assert isinstance(term, StackJoyType), repr(term)
    +    if term == stack:
    +        switch[0] = True
    +        end = '...'
    +    else:
    +        end = '.%i.' % term.number
    +    a.append(end)
    +    return '[%s]' % ' '.join(a)
     
    -
    for name, stack_effect_comment in sorted(NEW_DEFS.items()):
    -    print name, '=', doc_from_stack_effect(*stack_effect_comment)
    +
    for name, stack_effect_comment in sorted(NEW_DEFS.items()):
    +    print name, '=', doc_from_stack_effect(*stack_effect_comment)
     
    ccons = (a1 a2 [.1.] -- [a1 a2 .1.])
    @@ -1587,10 +1587,10 @@ def _to_str(term, stack, switch):
     uncons = ([a1 .1.] -- a1 [.1.])
     
    -
    print ; print doc_from_stack_effect(*stack)
    -print ; print doc_from_stack_effect(*C(stack, uncons))
    -print ; print doc_from_stack_effect(*reduce(C, (stack, uncons, uncons)))
    -print ; print doc_from_stack_effect(*reduce(C, (stack, uncons, cons)))
    +
    print ; print doc_from_stack_effect(*stack)
    +print ; print doc_from_stack_effect(*C(stack, uncons))
    +print ; print doc_from_stack_effect(*reduce(C, (stack, uncons, uncons)))
    +print ; print doc_from_stack_effect(*reduce(C, (stack, uncons, cons)))
     
    (... -- ... [...])
    @@ -1602,15 +1602,15 @@ print ; print doc_from_stack_effect(*reduce(C, (stack, uncons, cons)))
     (... a1 -- ... a1 [a1 ...])
     
    -
    print doc_from_stack_effect(*C(ccons, stack))
    +
    print doc_from_stack_effect(*C(ccons, stack))
     
    (... a2 a1 [.1.] -- ... [a2 a1 .1.] [[a2 a1 .1.] ...])
     
    -
    Q = C(ccons, stack)
    +
    Q = C(ccons, stack)
     
    -Q
    +Q
     
    ((s1, (a1, (a2, s2))), (((a2, (a1, s1)), s2), ((a2, (a1, s1)), s2)))
    @@ -1620,17 +1620,17 @@ Q
     

    compile_() version 3

    This makes the compile_() function pretty simple as the stack effect comments are now already in the form needed for the Python code:

    -
    def compile_(name, f, doc=None):
    -    i, o = f
    -    if doc is None:
    -        doc = doc_from_stack_effect(i, o)
    -    return '''def %s(stack):
    -    """%s"""
    -    %s = stack
    -    return %s''' % (name, doc, i, o)
    +
    def compile_(name, f, doc=None):
    +    i, o = f
    +    if doc is None:
    +        doc = doc_from_stack_effect(i, o)
    +    return '''def %s(stack):
    +    """%s"""
    +    %s = stack
    +    return %s''' % (name, doc, i, o)
     
    -
    print compile_('Q', Q)
    +
    print compile_('Q', Q)
     
    def Q(stack):
    @@ -1639,35 +1639,35 @@ comments are now already in the form needed for the Python code:

    return (((a2, (a1, s1)), s2), ((a2, (a1, s1)), s2))
    -
    unstack = (S[1], S[0]), S[1]
    -enstacken = S[0], (S[0], S[1])
    +
    unstack = (S[1], S[0]), S[1]
    +enstacken = S[0], (S[0], S[1])
     
    -
    print doc_from_stack_effect(*unstack)
    +
    print doc_from_stack_effect(*unstack)
     
    ([.1.] --)
     
    -
    print doc_from_stack_effect(*enstacken)
    +
    print doc_from_stack_effect(*enstacken)
     
    (-- [.0.])
     
    -
    print doc_from_stack_effect(*C(cons, unstack))
    +
    print doc_from_stack_effect(*C(cons, unstack))
     
    (a1 [.1.] -- a1)
     
    -
    print doc_from_stack_effect(*C(cons, enstacken))
    +
    print doc_from_stack_effect(*C(cons, enstacken))
     
    (a1 [.1.] -- [[a1 .1.] .2.])
     
    -
    C(cons, unstack)
    +
    C(cons, unstack)
     
    ((s1, (a1, s2)), (a1, s1))
    @@ -1679,23 +1679,23 @@ enstacken = S[0], (S[0], S[1])
     

    Part VI: Multiple Stack Effects

    -
    class IntJoyType(NumberJoyType): prefix = 'i'
    +
    class IntJoyType(NumberJoyType): prefix = 'i'
     
     
    -F = map(FloatJoyType, _R)
    -I = map(IntJoyType, _R)
    +F = map(FloatJoyType, _R)
    +I = map(IntJoyType, _R)
     
    -
    muls = [
    -     ((I[2], (I[1], S[0])), (I[3], S[0])),
    -     ((F[2], (I[1], S[0])), (F[3], S[0])),
    -     ((I[2], (F[1], S[0])), (F[3], S[0])),
    -     ((F[2], (F[1], S[0])), (F[3], S[0])),
    -]
    +
    muls = [
    +     ((I[2], (I[1], S[0])), (I[3], S[0])),
    +     ((F[2], (I[1], S[0])), (F[3], S[0])),
    +     ((I[2], (F[1], S[0])), (F[3], S[0])),
    +     ((F[2], (F[1], S[0])), (F[3], S[0])),
    +]
     
    -
    for f in muls:
    -    print doc_from_stack_effect(*f)
    +
    for f in muls:
    +    print doc_from_stack_effect(*f)
     
    (i1 i2 -- i3)
    @@ -1704,42 +1704,42 @@ I = map(IntJoyType, _R)
     (f1 f2 -- f3)
     
    -
    for f in muls:
    -    try:
    -        e = C(dup, f)
    -    except TypeError:
    -        continue
    -    print doc_from_stack_effect(*dup), doc_from_stack_effect(*f), doc_from_stack_effect(*e)
    +
    for f in muls:
    +    try:
    +        e = C(dup, f)
    +    except TypeError:
    +        continue
    +    print doc_from_stack_effect(*dup), doc_from_stack_effect(*f), doc_from_stack_effect(*e)
     
    (a1 -- a1 a1) (i1 i2 -- i3) (i1 -- i2)
     (a1 -- a1 a1) (f1 f2 -- f3) (f1 -- f2)
     
    -
    from itertools import product
    +
    from itertools import product
     
     
    -def meta_compose(F, G):
    -    for f, g in product(F, G):
    -        try:
    -            yield C(f, g)
    -        except TypeError:
    -            pass
    +def meta_compose(F, G):
    +    for f, g in product(F, G):
    +        try:
    +            yield C(f, g)
    +        except TypeError:
    +            pass
     
     
    -def MC(F, G):
    -    return sorted(set(meta_compose(F, G)))
    +def MC(F, G):
    +    return sorted(set(meta_compose(F, G)))
     
    -
    for f in MC([dup], [mul]):
    -    print doc_from_stack_effect(*f)
    +
    for f in MC([dup], [mul]):
    +    print doc_from_stack_effect(*f)
     
    (n1 -- n2)
     
    -
    for f in MC([dup], muls):
    -    print doc_from_stack_effect(*f)
    +
    for f in MC([dup], muls):
    +    print doc_from_stack_effect(*f)
     
    (f1 -- f2)
    @@ -1793,148 +1793,148 @@ disappears:

    {c: a, d: e, .1.: A* b .0.}
    -
    class KleeneStar(object):
    +
    class KleeneStar(object):
     
    -    kind = AnyJoyType
    +    kind = AnyJoyType
     
    -    def __init__(self, number):
    -        self.number = number
    -        self.count = 0
    -        self.prefix = repr(self)
    +    def __init__(self, number):
    +        self.number = number
    +        self.count = 0
    +        self.prefix = repr(self)
     
    -    def __repr__(self):
    -        return '%s%i*' % (self.kind.prefix, self.number)
    +    def __repr__(self):
    +        return '%s%i*' % (self.kind.prefix, self.number)
     
    -    def another(self):
    -        self.count += 1
    -        return self.kind(10000 * self.number + self.count)
    +    def another(self):
    +        self.count += 1
    +        return self.kind(10000 * self.number + self.count)
     
    -    def __eq__(self, other):
    -        return (
    -            isinstance(other, self.__class__)
    -            and other.number == self.number
    -        )
    +    def __eq__(self, other):
    +        return (
    +            isinstance(other, self.__class__)
    +            and other.number == self.number
    +        )
     
    -    def __ge__(self, other):
    -        return self.kind >= other.kind
    +    def __ge__(self, other):
    +        return self.kind >= other.kind
     
    -    def __add__(self, other):
    -        return self.__class__(self.number + other)
    -    __radd__ = __add__
    +    def __add__(self, other):
    +        return self.__class__(self.number + other)
    +    __radd__ = __add__
     
    -    def __hash__(self):
    -        return hash(repr(self))
    +    def __hash__(self):
    +        return hash(repr(self))
     
    -class AnyStarJoyType(KleeneStar): kind = AnyJoyType
    -class NumberStarJoyType(KleeneStar): kind = NumberJoyType
    -#class FloatStarJoyType(KleeneStar): kind = FloatJoyType
    -#class IntStarJoyType(KleeneStar): kind = IntJoyType
    -class StackStarJoyType(KleeneStar): kind = StackJoyType
    +class AnyStarJoyType(KleeneStar): kind = AnyJoyType
    +class NumberStarJoyType(KleeneStar): kind = NumberJoyType
    +#class FloatStarJoyType(KleeneStar): kind = FloatJoyType
    +#class IntStarJoyType(KleeneStar): kind = IntJoyType
    +class StackStarJoyType(KleeneStar): kind = StackJoyType
     
     
    -As = map(AnyStarJoyType, _R)
    -Ns = map(NumberStarJoyType, _R)
    -Ss = map(StackStarJoyType, _R)
    +As = map(AnyStarJoyType, _R)
    +Ns = map(NumberStarJoyType, _R)
    +Ss = map(StackStarJoyType, _R)
     

    unify() version 4

    Can now return multiple results…

    -
    def unify(u, v, s=None):
    -    if s is None:
    -        s = {}
    -    elif s:
    -        u = update(s, u)
    -        v = update(s, v)
    +
    def unify(u, v, s=None):
    +    if s is None:
    +        s = {}
    +    elif s:
    +        u = update(s, u)
    +        v = update(s, v)
     
    -    if u == v:
    -        return s,
    +    if u == v:
    +        return s,
     
    -    if isinstance(u, AnyJoyType) and isinstance(v, AnyJoyType):
    -        if u >= v:
    -            s[u] = v
    -            return s,
    -        if v >= u:
    -            s[v] = u
    -            return s,
    -        raise TypeError('Cannot unify %r and %r.' % (u, v))
    +    if isinstance(u, AnyJoyType) and isinstance(v, AnyJoyType):
    +        if u >= v:
    +            s[u] = v
    +            return s,
    +        if v >= u:
    +            s[v] = u
    +            return s,
    +        raise TypeError('Cannot unify %r and %r.' % (u, v))
     
    -    if isinstance(u, tuple) and isinstance(v, tuple):
    -        if len(u) != len(v) != 2:
    -            raise TypeError(repr((u, v)))
    +    if isinstance(u, tuple) and isinstance(v, tuple):
    +        if len(u) != len(v) != 2:
    +            raise TypeError(repr((u, v)))
     
    -        a, b = v
    -        if isinstance(a, KleeneStar):
    -            # Two universes, in one the Kleene star disappears and unification
    -            # continues without it...
    -            s0 = unify(u, b)
    +        a, b = v
    +        if isinstance(a, KleeneStar):
    +            # Two universes, in one the Kleene star disappears and unification
    +            # continues without it...
    +            s0 = unify(u, b)
     
    -            # In the other it spawns a new variable.
    -            s1 = unify(u, (a.another(), v))
    +            # In the other it spawns a new variable.
    +            s1 = unify(u, (a.another(), v))
     
    -            t = s0 + s1
    -            for sn in t:
    -                sn.update(s)
    -            return t
    +            t = s0 + s1
    +            for sn in t:
    +                sn.update(s)
    +            return t
     
    -        a, b = u
    -        if isinstance(a, KleeneStar):
    -            s0 = unify(v, b)
    -            s1 = unify(v, (a.another(), u))
    -            t = s0 + s1
    -            for sn in t:
    -                sn.update(s)
    -            return t
    +        a, b = u
    +        if isinstance(a, KleeneStar):
    +            s0 = unify(v, b)
    +            s1 = unify(v, (a.another(), u))
    +            t = s0 + s1
    +            for sn in t:
    +                sn.update(s)
    +            return t
     
    -        ses = unify(u[0], v[0], s)
    -        results = ()
    -        for sn in ses:
    -            results += unify(u[1], v[1], sn)
    -        return results
    +        ses = unify(u[0], v[0], s)
    +        results = ()
    +        for sn in ses:
    +            results += unify(u[1], v[1], sn)
    +        return results
     
    -    if isinstance(v, tuple):
    -        if not stacky(u):
    -            raise TypeError('Cannot unify %r and %r.' % (u, v))
    -        s[u] = v
    -        return s,
    +    if isinstance(v, tuple):
    +        if not stacky(u):
    +            raise TypeError('Cannot unify %r and %r.' % (u, v))
    +        s[u] = v
    +        return s,
     
    -    if isinstance(u, tuple):
    -        if not stacky(v):
    -            raise TypeError('Cannot unify %r and %r.' % (v, u))
    -        s[v] = u
    -        return s,
    +    if isinstance(u, tuple):
    +        if not stacky(v):
    +            raise TypeError('Cannot unify %r and %r.' % (v, u))
    +        s[v] = u
    +        return s,
     
    -    return ()
    +    return ()
     
     
    -def stacky(thing):
    -    return thing.__class__ in {AnyJoyType, StackJoyType}
    +def stacky(thing):
    +    return thing.__class__ in {AnyJoyType, StackJoyType}
     
    -
    a = (As[1], S[1])
    -a
    +
    a = (As[1], S[1])
    +a
     
    (a1*, s1)
     
    -
    b = (A[1], S[2])
    -b
    +
    b = (A[1], S[2])
    +b
     
    (a1, s2)
     
    -
    for result in unify(b, a):
    -    print result, '->', update(result, a), update(result, b)
    +
    for result in unify(b, a):
    +    print result, '->', update(result, a), update(result, b)
     
    {s1: (a1, s2)} -> (a1*, (a1, s2)) (a1, s2)
     {a1: a10001, s2: (a1*, s1)} -> (a1*, s1) (a10001, (a1*, s1))
     
    -
    for result in unify(a, b):
    -    print result, '->', update(result, a), update(result, b)
    +
    for result in unify(a, b):
    +    print result, '->', update(result, a), update(result, b)
     
    {s1: (a1, s2)} -> (a1*, (a1, s2)) (a1, s2)
    @@ -1948,24 +1948,24 @@ b
     (a1*, s1)       [a1*]       (a2, (a1*, s1)) [a2 a1*]
     
    -
    sum_ = ((Ns[1], S[1]), S[0]), (N[0], S[0])
    +
    sum_ = ((Ns[1], S[1]), S[0]), (N[0], S[0])
     
    -print doc_from_stack_effect(*sum_)
    +print doc_from_stack_effect(*sum_)
     
    ([n1* .1.] -- n0)
     
    -
    f = (N[1], (N[2], (N[3], S[1]))), S[0]
    +
    f = (N[1], (N[2], (N[3], S[1]))), S[0]
     
    -print doc_from_stack_effect(S[0], f)
    +print doc_from_stack_effect(S[0], f)
     
    (-- [n1 n2 n3 .1.])
     
    -
    for result in unify(sum_[0], f):
    -    print result, '->', update(result, sum_[1])
    +
    for result in unify(sum_[0], f):
    +    print result, '->', update(result, sum_[1])
     
    {s1: (n1, (n2, (n3, s1)))} -> (n0, s0)
    @@ -1978,88 +1978,88 @@ print doc_from_stack_effect(S[0], f)
     

    compose() version 3

    This function has to be modified to yield multiple results.

    -
    def compose(f, g):
    -    (f_in, f_out), (g_in, g_out) = f, g
    -    s = unify(g_in, f_out)
    -    if not s:
    -        raise TypeError('Cannot unify %r and %r.' % (f_out, g_in))
    -    for result in s:
    -        yield update(result, (f_in, g_out))
    +
    def compose(f, g):
    +    (f_in, f_out), (g_in, g_out) = f, g
    +    s = unify(g_in, f_out)
    +    if not s:
    +        raise TypeError('Cannot unify %r and %r.' % (f_out, g_in))
    +    for result in s:
    +        yield update(result, (f_in, g_out))
     
    -
    def meta_compose(F, G):
    -    for f, g in product(F, G):
    -        try:
    -            for result in C(f, g):
    -                yield result
    -        except TypeError:
    -            pass
    +
    def meta_compose(F, G):
    +    for f, g in product(F, G):
    +        try:
    +            for result in C(f, g):
    +                yield result
    +        except TypeError:
    +            pass
     
     
    -def C(f, g):
    -    f, g = relabel(f, g)
    -    for fg in compose(f, g):
    -        yield delabel(fg)
    +def C(f, g):
    +    f, g = relabel(f, g)
    +    for fg in compose(f, g):
    +        yield delabel(fg)
     
    -
    for f in MC([dup], muls):
    -    print doc_from_stack_effect(*f)
    +
    for f in MC([dup], muls):
    +    print doc_from_stack_effect(*f)
     
    (f1 -- f2)
     (i1 -- i2)
     
    -
    for f in MC([dup], [sum_]):
    -    print doc_from_stack_effect(*f)
    +
    for f in MC([dup], [sum_]):
    +    print doc_from_stack_effect(*f)
     
    ([n1* .1.] -- [n1* .1.] n1)
     
    -
    for f in MC([cons], [sum_]):
    -    print doc_from_stack_effect(*f)
    +
    for f in MC([cons], [sum_]):
    +    print doc_from_stack_effect(*f)
     
    (a1 [.1.] -- n1)
     (n1 [n1* .1.] -- n2)
     
    -
    sum_ = (((N[1], (Ns[1], S[1])), S[0]), (N[0], S[0]))
    -print doc_from_stack_effect(*cons),
    -print doc_from_stack_effect(*sum_),
    +
    sum_ = (((N[1], (Ns[1], S[1])), S[0]), (N[0], S[0]))
    +print doc_from_stack_effect(*cons),
    +print doc_from_stack_effect(*sum_),
     
    -for f in MC([cons], [sum_]):
    -    print doc_from_stack_effect(*f)
    +for f in MC([cons], [sum_]):
    +    print doc_from_stack_effect(*f)
     
    (a1 [.1.] -- [a1 .1.]) ([n1 n1* .1.] -- n0) (n1 [n1* .1.] -- n2)
     
    -
    a = (A[4], (As[1], (A[3], S[1])))
    -a
    +
    a = (A[4], (As[1], (A[3], S[1])))
    +a
     
    (a4, (a1*, (a3, s1)))
     
    -
    b = (A[1], (A[2], S[2]))
    -b
    +
    b = (A[1], (A[2], S[2]))
    +b
     
    (a1, (a2, s2))
     
    -
    for result in unify(b, a):
    -    print result
    +
    for result in unify(b, a):
    +    print result
     
    {a1: a4, s2: s1, a2: a3}
     {a1: a4, s2: (a1*, (a3, s1)), a2: a10003}
     
    -
    for result in unify(a, b):
    -    print result
    +
    for result in unify(a, b):
    +    print result
     
    {s2: s1, a2: a3, a4: a1}
    @@ -2111,19 +2111,19 @@ stack effect we have to “split universes” again and return both.

    We need a type variable for Joy functions that can go in our expressions and be used by the hybrid inferencer/interpreter. They have to store a name and a list of stack effects.

    -
    class FunctionJoyType(AnyJoyType):
    +
    class FunctionJoyType(AnyJoyType):
     
    -    def __init__(self, name, sec, number):
    -        self.name = name
    -        self.stack_effects = sec
    -        self.number = number
    +    def __init__(self, name, sec, number):
    +        self.name = name
    +        self.stack_effects = sec
    +        self.number = number
     
    -    def __add__(self, other):
    -        return self
    -    __radd__ = __add__
    +    def __add__(self, other):
    +        return self
    +    __radd__ = __add__
     
    -    def __repr__(self):
    -        return self.name
    +    def __repr__(self):
    +        return self.name
     
    @@ -2131,47 +2131,47 @@ name and a list of stack effects.

    Specialized for Simple Functions and Combinators

    For non-combinator functions the stack effects list contains stack effect comments (represented by pairs of cons-lists as described above.)

    -
    class SymbolJoyType(FunctionJoyType):
    -    prefix = 'F'
    +
    class SymbolJoyType(FunctionJoyType):
    +    prefix = 'F'
     

    For combinators the list contains Python functions.

    -
    class CombinatorJoyType(FunctionJoyType):
    +
    class CombinatorJoyType(FunctionJoyType):
     
    -    prefix = 'C'
    +    prefix = 'C'
     
    -    def __init__(self, name, sec, number, expect=None):
    -        super(CombinatorJoyType, self).__init__(name, sec, number)
    -        self.expect = expect
    +    def __init__(self, name, sec, number, expect=None):
    +        super(CombinatorJoyType, self).__init__(name, sec, number)
    +        self.expect = expect
     
    -    def enter_guard(self, f):
    -        if self.expect is None:
    -            return f
    -        g = self.expect, self.expect
    -        new_f = list(compose(f, g, ()))
    -        assert len(new_f) == 1, repr(new_f)
    -        return new_f[0][1]
    +    def enter_guard(self, f):
    +        if self.expect is None:
    +            return f
    +        g = self.expect, self.expect
    +        new_f = list(compose(f, g, ()))
    +        assert len(new_f) == 1, repr(new_f)
    +        return new_f[0][1]
     

    For simple combinators that have only one effect (like dip) you only need one function and it can be the combinator itself.

    -
    import joy.library
    +
    import joy.library
     
    -dip = CombinatorJoyType('dip', [joy.library.dip], 23)
    +dip = CombinatorJoyType('dip', [joy.library.dip], 23)
     

    For combinators that can have more than one effect (like branch) you have to write functions that each implement the action of one of the effects.

    -
    def branch_true(stack, expression, dictionary):
    -    (then, (else_, (flag, stack))) = stack
    -    return stack, concat(then, expression), dictionary
    +
    def branch_true(stack, expression, dictionary):
    +    (then, (else_, (flag, stack))) = stack
    +    return stack, concat(then, expression), dictionary
     
    -def branch_false(stack, expression, dictionary):
    -    (then, (else_, (flag, stack))) = stack
    -    return stack, concat(else_, expression), dictionary
    +def branch_false(stack, expression, dictionary):
    +    (then, (else_, (flag, stack))) = stack
    +    return stack, concat(else_, expression), dictionary
     
    -branch = CombinatorJoyType('branch', [branch_true, branch_false], 100)
    +branch = CombinatorJoyType('branch', [branch_true, branch_false], 100)
     

    You can also provide an optional stack effect, input-side only, that @@ -2189,54 +2189,54 @@ that expression.

    updated along with the stack effects after doing unification or we risk losing useful information. This was a straightforward, if awkward, modification to the call structure of meta_compose() et. al.

    -
    ID = S[0], S[0]  # Identity function.
    +
    ID = S[0], S[0]  # Identity function.
     
     
    -def infer(*expression):
    -    return sorted(set(_infer(list_to_stack(expression))))
    +def infer(*expression):
    +    return sorted(set(_infer(list_to_stack(expression))))
     
     
    -def _infer(e, F=ID):
    -    _log_it(e, F)
    -    if not e:
    -        return [F]
    +def _infer(e, F=ID):
    +    _log_it(e, F)
    +    if not e:
    +        return [F]
     
    -    n, e = e
    +    n, e = e
     
    -    if isinstance(n, SymbolJoyType):
    -        eFG = meta_compose([F], n.stack_effects, e)
    -        res = flatten(_infer(e, Fn) for e, Fn in eFG)
    +    if isinstance(n, SymbolJoyType):
    +        eFG = meta_compose([F], n.stack_effects, e)
    +        res = flatten(_infer(e, Fn) for e, Fn in eFG)
     
    -    elif isinstance(n, CombinatorJoyType):
    -        fi, fo = n.enter_guard(F)
    -        res = flatten(_interpret(f, fi, fo, e) for f in n.stack_effects)
    +    elif isinstance(n, CombinatorJoyType):
    +        fi, fo = n.enter_guard(F)
    +        res = flatten(_interpret(f, fi, fo, e) for f in n.stack_effects)
     
    -    elif isinstance(n, Symbol):
    -        assert n not in FUNCTIONS, repr(n)
    -        func = joy.library._dictionary[n]
    -        res = _interpret(func, F[0], F[1], e)
    +    elif isinstance(n, Symbol):
    +        assert n not in FUNCTIONS, repr(n)
    +        func = joy.library._dictionary[n]
    +        res = _interpret(func, F[0], F[1], e)
     
    -    else:
    -        fi, fo = F
    -        res = _infer(e, (fi, (n, fo)))
    +    else:
    +        fi, fo = F
    +        res = _infer(e, (fi, (n, fo)))
     
    -    return res
    +    return res
     
     
    -def _interpret(f, fi, fo, e):
    -    new_fo, ee, _ = f(fo, e, {})
    -    ee = update(FUNCTIONS, ee)  # Fix Symbols.
    -    new_F = fi, new_fo
    -    return _infer(ee, new_F)
    +def _interpret(f, fi, fo, e):
    +    new_fo, ee, _ = f(fo, e, {})
    +    ee = update(FUNCTIONS, ee)  # Fix Symbols.
    +    new_F = fi, new_fo
    +    return _infer(ee, new_F)
     
     
    -def _log_it(e, F):
    -    _log.info(
    -        u'%3i %s ∘ %s',
    -        len(inspect_stack()),
    -        doc_from_stack_effect(*F),
    -        expression_to_string(e),
    -        )
    +def _log_it(e, F):
    +    _log.info(
    +        u'%3i %s%s',
    +        len(inspect_stack()),
    +        doc_from_stack_effect(*F),
    +        expression_to_string(e),
    +        )
     
    @@ -2249,18 +2249,18 @@ module (FIXME link to its docs here!) should be explained… There is cruft to convert the definitions in DEFS to the new SymbolJoyType objects, and some combinators. Here is an example of output from the current code :

    -
    1/0  # (Don't try to run this cell!  It's not going to work.  This is "read only" code heh..)
    +
    1/0  # (Don't try to run this cell!  It's not going to work.  This is "read only" code heh..)
     
    -logging.basicConfig(format='%(message)s', stream=sys.stdout, level=logging.INFO)
    +logging.basicConfig(format='%(message)s', stream=sys.stdout, level=logging.INFO)
     
    -globals().update(FUNCTIONS)
    +globals().update(FUNCTIONS)
     
    -h = infer((pred, s2), (mul, s3), (div, s4), (nullary, (bool, s5)), dipd, branch)
    +h = infer((pred, s2), (mul, s3), (div, s4), (nullary, (bool, s5)), dipd, branch)
     
    -print '-' * 40
    +print '-' * 40
     
    -for fi, fo in h:
    -    print doc_from_stack_effect(fi, fo)
    +for fi, fo in h:
    +    print doc_from_stack_effect(fi, fo)
     
    ---------------------------------------------------------------------------
    @@ -2366,14 +2366,14 @@ relational nature of the stack effect comments to “compute in reverse”
     as it were. There’s a working demo of this at the end of the types
     module. But if you’re interested in all that you should just use Prolog!

    Anyhow, type checking is a few easy steps away.

    -
    def _ge(self, other):
    -    return (issubclass(other.__class__, self.__class__)
    -            or hasattr(self, 'accept')
    -            and isinstance(other, self.accept))
    +
    def _ge(self, other):
    +    return (issubclass(other.__class__, self.__class__)
    +            or hasattr(self, 'accept')
    +            and isinstance(other, self.accept))
     
    -AnyJoyType.__ge__ = _ge
    -AnyJoyType.accept = tuple, int, float, long, str, unicode, bool, Symbol
    -StackJoyType.accept = tuple
    +AnyJoyType.__ge__ = _ge
    +AnyJoyType.accept = tuple, int, float, long, str, unicode, bool, Symbol
    +StackJoyType.accept = tuple
     
    diff --git a/docs/sphinx_docs/_build/html/notebooks/Zipper.html b/docs/sphinx_docs/_build/html/notebooks/Zipper.html index ff13a07..4653021 100644 --- a/docs/sphinx_docs/_build/html/notebooks/Zipper.html +++ b/docs/sphinx_docs/_build/html/notebooks/Zipper.html @@ -42,7 +42,7 @@ the original paper:
    from notebook_preamble import J, V, define
    +
    from notebook_preamble import J, V, define
     
    @@ -52,7 +52,7 @@ strings, Symbols (strings that are names of functions) and sequences (aka lists, aka quoted literals, aka aggregates, etc…), but we can build trees out of sequences.

    -
    J('[1 [2 [3 4 25 6] 7] 8]')
    +
    J('[1 [2 [3 4 25 6] 7] 8]')
     
    [1 [2 [3 4 25 6] 7] 8]
    @@ -75,13 +75,13 @@ datastructure used to keep track of these items is the zipper.)

    show the trace so you can see how it works. If we were going to use these a lot it would make sense to write Python versions for efficiency, but see below.

    -
    define('z-down == [] swap uncons swap')
    -define('z-up == swons swap shunt')
    -define('z-right == [swons] cons dip uncons swap')
    -define('z-left == swons [uncons swap] dip swap')
    +
    define('z-down == [] swap uncons swap')
    +define('z-up == swons swap shunt')
    +define('z-right == [swons] cons dip uncons swap')
    +define('z-left == swons [uncons swap] dip swap')
     
    -
    V('[1 [2 [3 4 25 6] 7] 8] z-down')
    +
    V('[1 [2 [3 4 25 6] 7] 8] z-down')
     
                              . [1 [2 [3 4 25 6] 7] 8] z-down
    @@ -93,7 +93,7 @@ define('z-left == swons [uncons swap] dip swap')
     [] [[2 [3 4 25 6] 7] 8] 1 .
     
    -
    V('[] [[2 [3 4 25 6] 7] 8] 1 z-right')
    +
    V('[] [[2 [3 4 25 6] 7] 8] 1 z-right')
     
                                      . [] [[2 [3 4 25 6] 7] 8] 1 z-right
    @@ -113,43 +113,43 @@ define('z-left == swons [uncons swap] dip swap')
              [1] [8] [2 [3 4 25 6] 7] .
     
    -
    J('[1] [8] [2 [3 4 25 6] 7] z-down')
    +
    J('[1] [8] [2 [3 4 25 6] 7] z-down')
     
    [1] [8] [] [[3 4 25 6] 7] 2
     
    -
    J('[1] [8] [] [[3 4 25 6] 7] 2 z-right')
    +
    J('[1] [8] [] [[3 4 25 6] 7] 2 z-right')
     
    [1] [8] [2] [7] [3 4 25 6]
     
    -
    J('[1] [8] [2] [7] [3 4 25 6] z-down')
    +
    J('[1] [8] [2] [7] [3 4 25 6] z-down')
     
    [1] [8] [2] [7] [] [4 25 6] 3
     
    -
    J('[1] [8] [2] [7] [] [4 25 6] 3 z-right')
    +
    J('[1] [8] [2] [7] [] [4 25 6] 3 z-right')
     
    [1] [8] [2] [7] [3] [25 6] 4
     
    -
    J('[1] [8] [2] [7] [3] [25 6] 4 z-right')
    +
    J('[1] [8] [2] [7] [3] [25 6] 4 z-right')
     
    [1] [8] [2] [7] [4 3] [6] 25
     
    -
    J('[1] [8] [2] [7] [4 3] [6] 25 sqr')
    +
    J('[1] [8] [2] [7] [4 3] [6] 25 sqr')
     
    [1] [8] [2] [7] [4 3] [6] 625
     
    -
    V('[1] [8] [2] [7] [4 3] [6] 625 z-up')
    +
    V('[1] [8] [2] [7] [4 3] [6] 625 z-up')
     
                                  . [1] [8] [2] [7] [4 3] [6] 625 z-up
    @@ -168,13 +168,13 @@ define('z-left == swons [uncons swap] dip swap')
       [1] [8] [2] [7] [3 4 625 6] .
     
    -
    J('[1] [8] [2] [7] [3 4 625 6] z-up')
    +
    J('[1] [8] [2] [7] [3 4 625 6] z-up')
     
    [1] [8] [2 [3 4 625 6] 7]
     
    -
    J('[1] [8] [2 [3 4 625 6] 7] z-up')
    +
    J('[1] [8] [2 [3 4 625 6] 7] z-up')
     
    [1 [2 [3 4 625 6] 7] 8]
    @@ -185,7 +185,7 @@ define('z-left == swons [uncons swap] dip swap')
     

    dip and infra

    In Joy we have the dip and infra combinators which can “target” or “address” any particular item in a Joy tree structure.

    -
    V('[1 [2 [3 4 25 6] 7] 8] [[[[[[sqr] dipd] infra] dip] infra] dip] infra')
    +
    V('[1 [2 [3 4 25 6] 7] 8] [[[[[[sqr] dipd] infra] dip] infra] dip] infra')
     
                                                                    . [1 [2 [3 4 25 6] 7] 8] [[[[[[sqr] dipd] infra] dip] infra] dip] infra
    @@ -236,11 +236,11 @@ been embedded in a nested series of quoted programs, e.g.:

    The Z function isn’t hard to make.

    -
    define('Z == [[] cons cons] step i')
    +
    define('Z == [[] cons cons] step i')
     

    Here it is in action in a simplified scenario.

    -
    V('1 [2 3 4] Z')
    +
    V('1 [2 3 4] Z')
     
                                 . 1 [2 3 4] Z
    @@ -273,7 +273,7 @@ been embedded in a nested series of quoted programs, e.g.:

    And here it is doing the main thing.

    -
    J('[1 [2 [3 4 25 6] 7] 8] [sqr] [dip dip infra dip infra dip infra] Z')
    +
    J('[1 [2 [3 4 25 6] 7] 8] [sqr] [dip dip infra dip infra dip infra] Z')
     
    [1 [2 [3 4 625 6] 7] 8]
    diff --git a/docs/sphinx_docs/notebooks/Newton-Raphson.rst b/docs/sphinx_docs/notebooks/Newton-Raphson.rst
    index cb3f759..b580502 100644
    --- a/docs/sphinx_docs/notebooks/Newton-Raphson.rst
    +++ b/docs/sphinx_docs/notebooks/Newton-Raphson.rst
    @@ -7,7 +7,7 @@ to write a function that can compute the square root of a number.
     Cf. `"Why Functional Programming Matters" by John
     Hughes `__
     
    -.. code:: ipython3
    +.. code:: python
     
         from notebook_preamble import J, V, define
     
    @@ -75,11 +75,11 @@ The generator can be written as:
         1       [23 over / + 2 /]      [dup] swoncat make_generator
         1   [dup 23 over / + 2 /]                    make_generator
     
    -.. code:: ipython3
    +.. code:: python
     
         define('gsra 1 swap [over / + 2 /] cons [dup] swoncat make_generator')
     
    -.. code:: ipython3
    +.. code:: python
     
         J('23 gsra')
     
    @@ -92,7 +92,7 @@ The generator can be written as:
     Let's drive the generator a few time (with the ``x`` combinator) and
     square the approximation to see how well it works...
     
    -.. code:: ipython3
    +.. code:: python
     
         J('23 gsra 6 [x popd] times first sqr')
     
    @@ -142,7 +142,7 @@ Predicate
         abs(a-b)            ε                   <=
         (abs(a-b)<=ε)
     
    -.. code:: ipython3
    +.. code:: python
     
         define('_within_P [first - abs] dip <=')
     
    @@ -156,7 +156,7 @@ Base-Case
           [b G]               first
            b
     
    -.. code:: ipython3
    +.. code:: python
     
         define('_within_B roll< popop first')
     
    @@ -184,7 +184,7 @@ Pretty straightforward:
     
         b [c G] ε within
     
    -.. code:: ipython3
    +.. code:: python
     
         define('_within_R [popd x] dip')
     
    @@ -199,14 +199,14 @@ The recursive function we have defined so far needs a slight preamble:
         [a G] x ε ...
         a [b G] ε ...
     
    -.. code:: ipython3
    +.. code:: python
     
         define('within x 0.000000001 [_within_P] [_within_B] [_within_R] tailrec')
         define('sqrt gsra within')
     
     Try it out...
     
    -.. code:: ipython3
    +.. code:: python
     
         J('36 sqrt')
     
    @@ -216,7 +216,7 @@ Try it out...
         6.0
     
     
    -.. code:: ipython3
    +.. code:: python
     
         J('23 sqrt')
     
    @@ -228,7 +228,7 @@ Try it out...
     
     Check it.
     
    -.. code:: ipython3
    +.. code:: python
     
         4.795831523312719**2
     
    @@ -241,7 +241,7 @@ Check it.
     
     
     
    -.. code:: ipython3
    +.. code:: python
     
         from math import sqrt