diff --git a/Makefile b/Makefile index 3451a37..eb36cd9 100644 --- a/Makefile +++ b/Makefile @@ -26,3 +26,4 @@ test: sdist docs: cd ./docs && python -m nbconvert --to html *.ipynb cd ./docs && python -m nbconvert --to markdown *.ipynb + cd ./docs && python -m nbconvert --to rst *.ipynb diff --git a/docs/0. This Implementation of Joy in Python.html b/docs/0. This Implementation of Joy in Python.html index 6982023..cae3314 100644 --- a/docs/0. This Implementation of Joy in Python.html +++ b/docs/0. This Implementation of Joy in Python.html @@ -12602,7 +12602,7 @@ primrec == [i] genrec
In [ ]:
-
  
+

 
diff --git a/docs/Advent of Code 2017 December 3rd.html b/docs/Advent of Code 2017 December 3rd.html index fb13cb1..80393b6 100644 --- a/docs/Advent of Code 2017 December 3rd.html +++ b/docs/Advent of Code 2017 December 3rd.html @@ -12447,7 +12447,7 @@ div#notebook {
from sympy import floor, lambdify, solve, symbols
 from sympy import init_printing
-init_printing() 
+init_printing()
 
@@ -12600,7 +12600,7 @@ $$4 k \left(k + 1\right) + 2$$
In [19]:
-
%time rank_of(23000000000000)  # Compare runtime with rank_and_offset()!
+
%time rank_of(23000000000000)  # Compare runtime with rank_and_offset()!
 
@@ -12645,7 +12645,7 @@ $$2397916$$
In [20]:
-
%time rank_and_offset(23000000000000)
+
%time rank_and_offset(23000000000000)
 
@@ -12911,7 +12911,7 @@ $$\lfloor{\frac{1}{2} \sqrt{y - 1} - \frac{1}{2}}\rfloor + 1$$
In [28]:
-
%time int(F(23000000000000))  # The clear winner.
+
%time int(F(23000000000000))  # The clear winner.
 
@@ -12981,7 +12981,7 @@ $$2397916$$
In [30]:
-
%time mrank_of(23000000000000)
+
%time mrank_of(23000000000000)
 
@@ -13227,7 +13227,7 @@ $$4572225$$
In [37]:
-
%time aoc20173(23000000000000000000000000)  # Fast for large values.
+
%time aoc20173(23000000000000000000000000)  # Fast for large values.
 
diff --git a/docs/sphinx_docs/conf.py b/docs/sphinx_docs/conf.py index 1157a79..61503ed 100644 --- a/docs/sphinx_docs/conf.py +++ b/docs/sphinx_docs/conf.py @@ -24,7 +24,7 @@ copyright = u'2018, Simon Forman' author = u'Simon Forman' # The short X.Y version -version = u'' +version = u'0.1' # The full version, including alpha/beta/rc tags release = u'0.1.0' diff --git a/docs/sphinx_docs/index.rst b/docs/sphinx_docs/index.rst index 92b29ea..b605b1e 100644 --- a/docs/sphinx_docs/index.rst +++ b/docs/sphinx_docs/index.rst @@ -3,21 +3,44 @@ You can adapt this file completely to your liking, but it should at least contain the root `toctree` directive. -Thun Documentation -================== +Thun |release| Documentation +============================ + +Thun is dialect of Joy written in Python. + +Joy is a programming language created by Manfred von Thun that is easy to +use and understand and has many other nice properties. This Python +package implements an interpreter for a dialect of Joy that attempts to +stay very close to the spirit of Joy but does not precisely match the +behaviour of the original version(s) written in C. The main difference +between Thun and the originals, other than being written in Python, is +that it works by the "Continuation-Passing Style". + + +Quick Start +-------------------------------------------------- + +Install from PyPI in the usual way:: + + $ pip install Thun + +To start the REPL:: + + $ python -m joy + -Hey there! .. toctree:: :maxdepth: 2 :caption: Contents: + joy stack parser pretty + library + lib -.. automodule:: joy.joy - :members: Indices and tables diff --git a/docs/sphinx_docs/joy.rst b/docs/sphinx_docs/joy.rst new file mode 100644 index 0000000..3f32be9 --- /dev/null +++ b/docs/sphinx_docs/joy.rst @@ -0,0 +1,9 @@ + +Joy Interpreter +=============== + + +.. automodule:: joy.joy + :members: + + diff --git a/docs/sphinx_docs/lib.rst b/docs/sphinx_docs/lib.rst new file mode 100644 index 0000000..fe7bbb4 --- /dev/null +++ b/docs/sphinx_docs/lib.rst @@ -0,0 +1,1761 @@ + +Examples (and some documentation) for the Words in the Library +============================================================== + +.. code:: ipython2 + + from notebook_preamble import J, V + +Stack Chatter +============= + +This is what I like to call the functions that just rearrange things on +the stack. (One thing I want to mention is that during a hypothetical +compilation phase these "stack chatter" words effectively disappear, +because we can map the logical stack locations to registers that remain +static for the duration of the computation. This remains to be done but +it's "off the shelf" technology.) + +``clear`` +~~~~~~~~~ + +.. code:: ipython2 + + J('1 2 3 clear') + + +.. parsed-literal:: + + + + +``dup`` ``dupd`` +~~~~~~~~~~~~~~~~ + +.. code:: ipython2 + + J('1 2 3 dup') + + +.. parsed-literal:: + + 1 2 3 3 + + +.. code:: ipython2 + + J('1 2 3 dupd') + + +.. parsed-literal:: + + 1 2 2 3 + + +``enstacken`` ``disenstacken`` ``stack`` ``unstack`` +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +(I may have these paired up wrong. I.e. ``disenstacken`` should be +``unstack`` and vice versa.) + +.. code:: ipython2 + + J('1 2 3 enstacken') # Replace the stack with a quote of itself. + + +.. parsed-literal:: + + [3 2 1] + + +.. code:: ipython2 + + J('4 5 6 [3 2 1] disenstacken') # Unpack a list onto the stack. + + +.. parsed-literal:: + + 4 5 6 3 2 1 + + +.. code:: ipython2 + + J('1 2 3 stack') # Get the stack on the stack. + + +.. parsed-literal:: + + 1 2 3 [3 2 1] + + +.. code:: ipython2 + + 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. + + +.. parsed-literal:: + + 6 5 4 + + +``pop`` ``popd`` ``popop`` +~~~~~~~~~~~~~~~~~~~~~~~~~~ + +.. code:: ipython2 + + J('1 2 3 pop') + + +.. parsed-literal:: + + 1 2 + + +.. code:: ipython2 + + J('1 2 3 popd') + + +.. parsed-literal:: + + 1 3 + + +.. code:: ipython2 + + J('1 2 3 popop') + + +.. parsed-literal:: + + 1 + + +``roll<`` ``rolldown`` ``roll>`` ``rollup`` +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +The "down" and "up" refer to the movement of two of the top three items +(displacing the third.) + +.. code:: ipython2 + + J('1 2 3 roll<') + + +.. parsed-literal:: + + 2 3 1 + + +.. code:: ipython2 + + J('1 2 3 roll>') + + +.. parsed-literal:: + + 3 1 2 + + +``swap`` +~~~~~~~~ + +.. code:: ipython2 + + J('1 2 3 swap') + + +.. parsed-literal:: + + 1 3 2 + + +``tuck`` ``over`` +~~~~~~~~~~~~~~~~~ + +.. code:: ipython2 + + J('1 2 3 tuck') + + +.. parsed-literal:: + + 1 3 2 3 + + +.. code:: ipython2 + + J('1 2 3 over') + + +.. parsed-literal:: + + 1 2 3 2 + + +``unit`` ``quoted`` ``unquoted`` +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +.. code:: ipython2 + + J('1 2 3 unit') + + +.. parsed-literal:: + + 1 2 [3] + + +.. code:: ipython2 + + J('1 2 3 quoted') + + +.. parsed-literal:: + + 1 [2] 3 + + +.. code:: ipython2 + + J('1 [2] 3 unquoted') + + +.. parsed-literal:: + + 1 2 3 + + +.. code:: ipython2 + + V('1 [dup] 3 unquoted') # Unquoting evaluates. Be aware. + + +.. parsed-literal:: + + . 1 [dup] 3 unquoted + 1 . [dup] 3 unquoted + 1 [dup] . 3 unquoted + 1 [dup] 3 . unquoted + 1 [dup] 3 . [i] dip + 1 [dup] 3 [i] . dip + 1 [dup] . i 3 + 1 . dup 3 + 1 1 . 3 + 1 1 3 . + + +List words +========== + +``concat`` ``swoncat`` ``shunt`` +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +.. code:: ipython2 + + J('[1 2 3] [4 5 6] concat') + + +.. parsed-literal:: + + [1 2 3 4 5 6] + + +.. code:: ipython2 + + J('[1 2 3] [4 5 6] swoncat') + + +.. parsed-literal:: + + [4 5 6 1 2 3] + + +.. code:: ipython2 + + J('[1 2 3] [4 5 6] shunt') + + +.. parsed-literal:: + + [6 5 4 1 2 3] + + +``cons`` ``swons`` ``uncons`` +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +.. code:: ipython2 + + J('1 [2 3] cons') + + +.. parsed-literal:: + + [1 2 3] + + +.. code:: ipython2 + + J('[2 3] 1 swons') + + +.. parsed-literal:: + + [1 2 3] + + +.. code:: ipython2 + + J('[1 2 3] uncons') + + +.. parsed-literal:: + + 1 [2 3] + + +``first`` ``second`` ``third`` ``rest`` +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +.. code:: ipython2 + + J('[1 2 3 4] first') + + +.. parsed-literal:: + + 1 + + +.. code:: ipython2 + + J('[1 2 3 4] second') + + +.. parsed-literal:: + + 2 + + +.. code:: ipython2 + + J('[1 2 3 4] third') + + +.. parsed-literal:: + + 3 + + +.. code:: ipython2 + + J('[1 2 3 4] rest') + + +.. parsed-literal:: + + [2 3 4] + + +``flatten`` +~~~~~~~~~~~ + +.. code:: ipython2 + + J('[[1] [2 [3] 4] [5 6]] flatten') + + +.. parsed-literal:: + + [1 2 [3] 4 5 6] + + +``getitem`` ``at`` ``of`` ``drop`` ``take`` +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +``at`` and ``getitem`` are the same function. ``of == swap at`` + +.. code:: ipython2 + + J('[10 11 12 13 14] 2 getitem') + + +.. parsed-literal:: + + 12 + + +.. code:: ipython2 + + J('[1 2 3 4] 0 at') + + +.. parsed-literal:: + + 1 + + +.. code:: ipython2 + + J('2 [1 2 3 4] of') + + +.. parsed-literal:: + + 3 + + +.. code:: ipython2 + + J('[1 2 3 4] 2 drop') + + +.. parsed-literal:: + + [3 4] + + +.. code:: ipython2 + + J('[1 2 3 4] 2 take') # reverses the order + + +.. parsed-literal:: + + [2 1] + + +``reverse`` could be defines as ``reverse == dup size take`` + +``remove`` +~~~~~~~~~~ + +.. code:: ipython2 + + J('[1 2 3 1 4] 1 remove') + + +.. parsed-literal:: + + [2 3 1 4] + + +``reverse`` +~~~~~~~~~~~ + +.. code:: ipython2 + + J('[1 2 3 4] reverse') + + +.. parsed-literal:: + + [4 3 2 1] + + +``size`` +~~~~~~~~ + +.. code:: ipython2 + + J('[1 1 1 1] size') + + +.. parsed-literal:: + + 4 + + +``swaack`` +~~~~~~~~~~ + +"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. + +.. code:: ipython2 + + J('1 2 3 [4 5 6] swaack') + + +.. parsed-literal:: + + 6 5 4 [3 2 1] + + +``choice`` ``select`` +~~~~~~~~~~~~~~~~~~~~~ + +.. code:: ipython2 + + J('23 9 1 choice') + + +.. parsed-literal:: + + 9 + + +.. code:: ipython2 + + J('23 9 0 choice') + + +.. parsed-literal:: + + 23 + + +.. code:: ipython2 + + J('[23 9 7] 1 select') # select is basically getitem, should retire it? + + +.. parsed-literal:: + + 9 + + +.. code:: ipython2 + + J('[23 9 7] 0 select') + + +.. parsed-literal:: + + 23 + + +``zip`` +~~~~~~~ + +.. code:: ipython2 + + J('[1 2 3] [6 5 4] zip') + + +.. parsed-literal:: + + [[6 1] [5 2] [4 3]] + + +.. code:: ipython2 + + J('[1 2 3] [6 5 4] zip [sum] map') + + +.. parsed-literal:: + + [7 7 7] + + +Math words +========== + +``+`` ``add`` +~~~~~~~~~~~~~ + +.. code:: ipython2 + + J('23 9 +') + + +.. parsed-literal:: + + 32 + + +``-`` ``sub`` +~~~~~~~~~~~~~ + +.. code:: ipython2 + + J('23 9 -') + + +.. parsed-literal:: + + 14 + + +``*`` ``mul`` +~~~~~~~~~~~~~ + +.. code:: ipython2 + + J('23 9 *') + + +.. parsed-literal:: + + 207 + + +``/`` ``div`` ``floordiv`` ``truediv`` +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +.. code:: ipython2 + + J('23 9 /') + + +.. parsed-literal:: + + 2.5555555555555554 + + +.. code:: ipython2 + + J('23 -9 truediv') + + +.. parsed-literal:: + + -2.5555555555555554 + + +.. code:: ipython2 + + J('23 9 div') + + +.. parsed-literal:: + + 2 + + +.. code:: ipython2 + + J('23 9 floordiv') + + +.. parsed-literal:: + + 2 + + +.. code:: ipython2 + + J('23 -9 div') + + +.. parsed-literal:: + + -3 + + +.. code:: ipython2 + + J('23 -9 floordiv') + + +.. parsed-literal:: + + -3 + + +``%`` ``mod`` ``modulus`` ``rem`` ``remainder`` +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +.. code:: ipython2 + + J('23 9 %') + + +.. parsed-literal:: + + 5 + + +``neg`` +~~~~~~~ + +.. code:: ipython2 + + J('23 neg -5 neg') + + +.. parsed-literal:: + + -23 5 + + +pow +~~~ + +.. code:: ipython2 + + J('2 10 pow') + + +.. parsed-literal:: + + 1024 + + +``sqr`` ``sqrt`` +~~~~~~~~~~~~~~~~ + +.. code:: ipython2 + + J('23 sqr') + + +.. parsed-literal:: + + 529 + + +.. code:: ipython2 + + J('23 sqrt') + + +.. parsed-literal:: + + 4.795831523312719 + + +``++`` ``succ`` ``--`` ``pred`` +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +.. code:: ipython2 + + J('1 ++') + + +.. parsed-literal:: + + 2 + + +.. code:: ipython2 + + J('1 --') + + +.. parsed-literal:: + + 0 + + +``<<`` ``lshift`` ``>>`` ``rshift`` +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +.. code:: ipython2 + + J('8 1 <<') + + +.. parsed-literal:: + + 16 + + +.. code:: ipython2 + + J('8 1 >>') + + +.. parsed-literal:: + + 4 + + +``average`` +~~~~~~~~~~~ + +.. code:: ipython2 + + J('[1 2 3 5] average') + + +.. parsed-literal:: + + 2.75 + + +``range`` ``range_to_zero`` ``down_to_zero`` +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +.. code:: ipython2 + + J('5 range') + + +.. parsed-literal:: + + [4 3 2 1 0] + + +.. code:: ipython2 + + J('5 range_to_zero') + + +.. parsed-literal:: + + [0 1 2 3 4 5] + + +.. code:: ipython2 + + J('5 down_to_zero') + + +.. parsed-literal:: + + 5 4 3 2 1 0 + + +``product`` +~~~~~~~~~~~ + +.. code:: ipython2 + + J('[1 2 3 5] product') + + +.. parsed-literal:: + + 30 + + +``sum`` +~~~~~~~ + +.. code:: ipython2 + + J('[1 2 3 5] sum') + + +.. parsed-literal:: + + 11 + + +``min`` +~~~~~~~ + +.. code:: ipython2 + + J('[1 2 3 5] min') + + +.. parsed-literal:: + + 1 + + +``gcd`` +~~~~~~~ + +.. code:: ipython2 + + J('45 30 gcd') + + +.. parsed-literal:: + + 15 + + +``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. + +.. code:: ipython2 + + J('[45 30] least_fraction') + + +.. parsed-literal:: + + [3 2] + + +.. code:: ipython2 + + J('[23 12] least_fraction') + + +.. parsed-literal:: + + [23 12] + + +Logic and Comparison +==================== + +``?`` ``truthy`` +~~~~~~~~~~~~~~~~ + +Get the Boolean value of the item on the top of the stack. + +.. code:: ipython2 + + J('23 truthy') + + +.. parsed-literal:: + + True + + +.. code:: ipython2 + + J('[] truthy') # Python semantics. + + +.. parsed-literal:: + + False + + +.. code:: ipython2 + + J('0 truthy') + + +.. parsed-literal:: + + False + + +:: + + ? == dup truthy + +.. code:: ipython2 + + V('23 ?') + + +.. parsed-literal:: + + . 23 ? + 23 . ? + 23 . dup truthy + 23 23 . truthy + 23 True . + + +.. code:: ipython2 + + J('[] ?') + + +.. parsed-literal:: + + [] False + + +.. code:: ipython2 + + J('0 ?') + + +.. parsed-literal:: + + 0 False + + +``&`` ``and`` +~~~~~~~~~~~~~ + +.. code:: ipython2 + + J('23 9 &') + + +.. parsed-literal:: + + 1 + + +``!=`` ``<>`` ``ne`` +~~~~~~~~~~~~~~~~~~~~ + +.. code:: ipython2 + + J('23 9 !=') + + +.. parsed-literal:: + + True + + +| The usual suspects: - ``<`` ``lt`` - ``<=`` ``le`` +| - ``=`` ``eq`` - ``>`` ``gt`` - ``>=`` ``ge`` - ``not`` - ``or`` + +``^`` ``xor`` +~~~~~~~~~~~~~ + +.. code:: ipython2 + + J('1 1 ^') + + +.. parsed-literal:: + + 0 + + +.. code:: ipython2 + + J('1 0 ^') + + +.. parsed-literal:: + + 1 + + +Miscellaneous +============= + +``help`` +~~~~~~~~ + +.. code:: ipython2 + + J('[help] help') + + +.. parsed-literal:: + + Accepts a quoted symbol on the top of the stack and prints its docs. + + + +``parse`` +~~~~~~~~~ + +.. code:: ipython2 + + J('[parse] help') + + +.. parsed-literal:: + + Parse the string on the stack to a Joy expression. + + + +.. code:: ipython2 + + J('1 "2 [3] dup" parse') + + +.. parsed-literal:: + + 1 [2 [3] dup] + + +``run`` +~~~~~~~ + +Evaluate a quoted Joy sequence. + +.. code:: ipython2 + + J('[1 2 dup + +] run') + + +.. parsed-literal:: + + [5] + + +Combinators +=========== + +``app1`` ``app2`` ``app3`` +~~~~~~~~~~~~~~~~~~~~~~~~~~ + +.. code:: ipython2 + + J('[app1] help') + + +.. parsed-literal:: + + Given a quoted program on TOS and anything as the second stack item run + the program and replace the two args with the first result of the + program. + + ... x [Q] . app1 + ----------------------------------- + ... [x ...] [Q] . infra first + + + +.. code:: ipython2 + + J('10 4 [sqr *] app1') + + +.. parsed-literal:: + + 10 160 + + +.. code:: ipython2 + + J('10 3 4 [sqr *] app2') + + +.. parsed-literal:: + + 10 90 160 + + +.. code:: ipython2 + + J('[app2] help') + + +.. parsed-literal:: + + Like app1 with two items. + + ... y x [Q] . app2 + ----------------------------------- + ... [y ...] [Q] . infra first + [x ...] [Q] infra first + + + +.. code:: ipython2 + + J('10 2 3 4 [sqr *] app3') + + +.. parsed-literal:: + + 10 40 90 160 + + +``anamorphism`` +~~~~~~~~~~~~~~~ + +Given an initial value, a predicate function ``[P]``, and a generator +function ``[G]``, the ``anamorphism`` combinator creates a sequence. + +:: + + n [P] [G] anamorphism + --------------------------- + [...] + +Example, ``range``: + +:: + + range == [0 <=] [1 - dup] anamorphism + +.. code:: ipython2 + + J('3 [0 <=] [1 - dup] anamorphism') + + +.. parsed-literal:: + + [2 1 0] + + +``branch`` +~~~~~~~~~~ + +.. code:: ipython2 + + J('3 4 1 [+] [*] branch') + + +.. parsed-literal:: + + 12 + + +.. code:: ipython2 + + J('3 4 0 [+] [*] branch') + + +.. parsed-literal:: + + 7 + + +``cleave`` +~~~~~~~~~~ + +:: + + ... x [P] [Q] cleave + +From the original Joy docs: "The cleave combinator expects two +quotations, and below that an item ``x`` It first executes ``[P]``, with +``x`` on top, and saves the top result element. Then it executes +``[Q]``, again with ``x``, and saves the top result. Finally it restores +the stack to what it was below ``x`` and pushes the two results P(X) and +Q(X)." + +Note that ``P`` and ``Q`` can use items from the stack freely, since the +stack (below ``x``) is restored. ``cleave`` is a kind of *parallel* +primitive, and it would make sense to create a version that uses, e.g. +Python threads or something, to actually run ``P`` and ``Q`` +concurrently. The current implementation of ``cleave`` is a definition +in terms of ``app2``: + +:: + + cleave == [i] app2 [popd] dip + +.. code:: ipython2 + + J('10 2 [+] [-] cleave') + + +.. parsed-literal:: + + 10 12 8 + + +``dip`` ``dipd`` ``dipdd`` +~~~~~~~~~~~~~~~~~~~~~~~~~~ + +.. code:: ipython2 + + J('1 2 3 4 5 [+] dip') + + +.. parsed-literal:: + + 1 2 7 5 + + +.. code:: ipython2 + + J('1 2 3 4 5 [+] dipd') + + +.. parsed-literal:: + + 1 5 4 5 + + +.. code:: ipython2 + + J('1 2 3 4 5 [+] dipdd') + + +.. parsed-literal:: + + 3 3 4 5 + + +``dupdip`` +~~~~~~~~~~ + +Expects a quoted program ``[Q]`` on the stack and some item under it, +``dup`` the item and ``dip`` the quoted program under it. + +:: + + n [Q] dupdip == n Q n + +.. code:: ipython2 + + V('23 [++] dupdip *') # N(N + 1) + + +.. parsed-literal:: + + . 23 [++] dupdip * + 23 . [++] dupdip * + 23 [++] . dupdip * + 23 . ++ 23 * + 24 . 23 * + 24 23 . * + 552 . + + +``genrec`` ``primrec`` +~~~~~~~~~~~~~~~~~~~~~~ + +.. code:: ipython2 + + J('[genrec] help') + + +.. parsed-literal:: + + General Recursion Combinator. + + [if] [then] [rec1] [rec2] genrec + --------------------------------------------------------------------- + [if] [then] [rec1 [[if] [then] [rec1] [rec2] genrec] rec2] ifte + + From "Recursion Theory and Joy" (j05cmp.html) by Manfred von Thun: + "The genrec combinator takes four program parameters in addition to + whatever data parameters it needs. Fourth from the top is an if-part, + followed by a then-part. If the if-part yields true, then the then-part + is executed and the combinator terminates. The other two parameters are + the rec1-part and the rec2-part. If the if-part yields false, the + rec1-part is executed. Following that the four program parameters and + the combinator are again pushed onto the stack bundled up in a quoted + form. Then the rec2-part is executed, where it will find the bundled + form. Typically it will then execute the bundled form, either with i or + with app2, or some other combinator." + + The way to design one of these is to fix your base case [then] and the + test [if], and then treat rec1 and rec2 as an else-part "sandwiching" + a quotation of the whole function. + + For example, given a (general recursive) function 'F': + + F == [I] [T] [R1] [R2] genrec + + If the [I] if-part fails you must derive R1 and R2 from: + + ... R1 [F] R2 + + Just set the stack arguments in front, and figure out what R1 and R2 + have to do to apply the quoted [F] in the proper way. In effect, the + genrec combinator turns into an ifte combinator with a quoted copy of + the original definition in the else-part: + + F == [I] [T] [R1] [R2] genrec + == [I] [T] [R1 [F] R2] ifte + + (Primitive recursive functions are those where R2 == i. + + P == [I] [T] [R] primrec + == [I] [T] [R [P] i] ifte + == [I] [T] [R P] ifte + ) + + + +.. code:: ipython2 + + J('3 [1 <=] [] [dup --] [i *] genrec') + + +.. parsed-literal:: + + 6 + + +``i`` +~~~~~ + +.. code:: ipython2 + + V('1 2 3 [+ +] i') + + +.. parsed-literal:: + + . 1 2 3 [+ +] i + 1 . 2 3 [+ +] i + 1 2 . 3 [+ +] i + 1 2 3 . [+ +] i + 1 2 3 [+ +] . i + 1 2 3 . + + + 1 5 . + + 6 . + + +``ifte`` +~~~~~~~~ + +:: + + [predicate] [then] [else] ifte + +.. code:: ipython2 + + J('1 2 [1] [+] [*] ifte') + + +.. parsed-literal:: + + 3 + + +.. code:: ipython2 + + J('1 2 [0] [+] [*] ifte') + + +.. parsed-literal:: + + 2 + + +``infra`` +~~~~~~~~~ + +.. code:: ipython2 + + V('1 2 3 [4 5 6] [* +] infra') + + +.. parsed-literal:: + + . 1 2 3 [4 5 6] [* +] infra + 1 . 2 3 [4 5 6] [* +] infra + 1 2 . 3 [4 5 6] [* +] infra + 1 2 3 . [4 5 6] [* +] infra + 1 2 3 [4 5 6] . [* +] infra + 1 2 3 [4 5 6] [* +] . infra + 6 5 4 . * + [3 2 1] swaack + 6 20 . + [3 2 1] swaack + 26 . [3 2 1] swaack + 26 [3 2 1] . swaack + 1 2 3 [26] . + + +``loop`` +~~~~~~~~ + +.. code:: ipython2 + + J('[loop] help') + + +.. parsed-literal:: + + Basic loop combinator. + + ... True [Q] loop + ----------------------- + ... Q [Q] loop + + ... False [Q] loop + ------------------------ + ... + + + +.. code:: ipython2 + + V('3 dup [1 - dup] loop') + + +.. parsed-literal:: + + . 3 dup [1 - dup] loop + 3 . dup [1 - dup] loop + 3 3 . [1 - dup] loop + 3 3 [1 - dup] . loop + 3 . 1 - dup [1 - dup] loop + 3 1 . - dup [1 - dup] loop + 2 . dup [1 - dup] loop + 2 2 . [1 - dup] loop + 2 2 [1 - dup] . loop + 2 . 1 - dup [1 - dup] loop + 2 1 . - dup [1 - dup] loop + 1 . dup [1 - dup] loop + 1 1 . [1 - dup] loop + 1 1 [1 - dup] . loop + 1 . 1 - dup [1 - dup] loop + 1 1 . - dup [1 - dup] loop + 0 . dup [1 - dup] loop + 0 0 . [1 - dup] loop + 0 0 [1 - dup] . loop + 0 . + + +``map`` ``pam`` +~~~~~~~~~~~~~~~ + +.. code:: ipython2 + + J('10 [1 2 3] [*] map') + + +.. parsed-literal:: + + 10 [10 20 30] + + +.. code:: ipython2 + + J('10 5 [[*][/][+][-]] pam') + + +.. parsed-literal:: + + 10 5 [50 2.0 15 5] + + +``nullary`` ``unary`` ``binary`` ``ternary`` +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +Run a quoted program enforcing +`arity `__. + +.. code:: ipython2 + + J('1 2 3 4 5 [+] nullary') + + +.. parsed-literal:: + + 1 2 3 4 5 9 + + +.. code:: ipython2 + + J('1 2 3 4 5 [+] unary') + + +.. parsed-literal:: + + 1 2 3 4 9 + + +.. code:: ipython2 + + J('1 2 3 4 5 [+] binary') # + has arity 2 so this is technically pointless... + + +.. parsed-literal:: + + 1 2 3 9 + + +.. code:: ipython2 + + J('1 2 3 4 5 [+] ternary') + + +.. parsed-literal:: + + 1 2 9 + + +``step`` +~~~~~~~~ + +.. code:: ipython2 + + J('[step] help') + + +.. parsed-literal:: + + Run a quoted program on each item in a sequence. + + ... [] [Q] . step + ----------------------- + ... . + + + ... [a] [Q] . step + ------------------------ + ... a . Q + + + ... [a b c] [Q] . step + ---------------------------------------- + ... a . Q [b c] [Q] step + + The step combinator executes the quotation on each member of the list + on top of the stack. + + + +.. code:: ipython2 + + V('0 [1 2 3] [+] step') + + +.. parsed-literal:: + + . 0 [1 2 3] [+] step + 0 . [1 2 3] [+] step + 0 [1 2 3] . [+] step + 0 [1 2 3] [+] . step + 0 1 [+] . i [2 3] [+] step + 0 1 . + [2 3] [+] step + 1 . [2 3] [+] step + 1 [2 3] . [+] step + 1 [2 3] [+] . step + 1 2 [+] . i [3] [+] step + 1 2 . + [3] [+] step + 3 . [3] [+] step + 3 [3] . [+] step + 3 [3] [+] . step + 3 3 [+] . i + 3 3 . + + 6 . + + +``times`` +~~~~~~~~~ + +.. code:: ipython2 + + V('3 2 1 2 [+] times') + + +.. parsed-literal:: + + . 3 2 1 2 [+] times + 3 . 2 1 2 [+] times + 3 2 . 1 2 [+] times + 3 2 1 . 2 [+] times + 3 2 1 2 . [+] times + 3 2 1 2 [+] . times + 3 2 1 . + 1 [+] times + 3 3 . 1 [+] times + 3 3 1 . [+] times + 3 3 1 [+] . times + 3 3 . + + 6 . + + +``b`` +~~~~~ + +.. code:: ipython2 + + J('[b] help') + + +.. parsed-literal:: + + b == [i] dip i + + ... [P] [Q] b == ... [P] i [Q] i + ... [P] [Q] b == ... P Q + + + +.. code:: ipython2 + + V('1 2 [3] [4] b') + + +.. parsed-literal:: + + . 1 2 [3] [4] b + 1 . 2 [3] [4] b + 1 2 . [3] [4] b + 1 2 [3] . [4] b + 1 2 [3] [4] . b + 1 2 . 3 4 + 1 2 3 . 4 + 1 2 3 4 . + + +``while`` +~~~~~~~~~ + +:: + + [predicate] [body] while + +.. code:: ipython2 + + J('3 [0 >] [dup --] while') + + +.. parsed-literal:: + + 3 2 1 0 + + +``x`` +~~~~~ + +.. code:: ipython2 + + J('[x] help') + + +.. parsed-literal:: + + x == dup i + + ... [Q] x = ... [Q] dup i + ... [Q] x = ... [Q] [Q] i + ... [Q] x = ... [Q] Q + + + +.. code:: ipython2 + + V('1 [2] [i 3] x') # Kind of a pointless example. + + +.. parsed-literal:: + + . 1 [2] [i 3] x + 1 . [2] [i 3] x + 1 [2] . [i 3] x + 1 [2] [i 3] . x + 1 [2] [i 3] . i 3 + 1 [2] . i 3 3 + 1 . 2 3 3 + 1 2 . 3 3 + 1 2 3 . 3 + 1 2 3 3 . + + +``void`` +======== + +Implements `**Laws of Form** +*arithmetic* `__ +over quote-only datastructures (that is, datastructures that consist +soley of containers, without strings or numbers or anything else.) + +.. code:: ipython2 + + J('[] void') + + +.. parsed-literal:: + + False + + +.. code:: ipython2 + + J('[[]] void') + + +.. parsed-literal:: + + True + + +.. code:: ipython2 + + J('[[][[]]] void') + + +.. parsed-literal:: + + True + + +.. code:: ipython2 + + J('[[[]][[][]]] void') + + +.. parsed-literal:: + + False + diff --git a/docs/sphinx_docs/library.rst b/docs/sphinx_docs/library.rst index a08d41b..886836a 100644 --- a/docs/sphinx_docs/library.rst +++ b/docs/sphinx_docs/library.rst @@ -1,9 +1,9 @@ -Functions, Combinators and Definitions +Function Reference ====================================== -. . automodule:: joy.library +.. automodule:: joy.pribrary :members: diff --git a/joy/joy.py b/joy/joy.py index 430a2ab..901b159 100644 --- a/joy/joy.py +++ b/joy/joy.py @@ -1,53 +1,26 @@ # -*- coding: utf-8 -*- +# +# Copyright © 2014, 2015, 2017, 2018 Simon Forman +# +# This file is part of Thun +# +# Thun is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. +# +# Thun is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with Thun. If not see . +# ''' - - -A dialect of Joy in Python. - - -Joy is a programming language created by Manfred von Thun that is easy to -use and understand and has many other nice properties. This Python script -is an interpreter for a dialect of Joy that attempts to stay very close -to the spirit of Joy but does not precisely match the behaviour of the -original version(s) written in C. A Tkinter GUI is provided as well. - - - Copyright © 2014, 2016, 2017 Simon Forman - - This file is part of Thun. - - Thun is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - Thun is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with Thun. If not see . - - -§ joy() - -The basic joy() function is quite straightforward. It iterates through a -sequence of terms which are either literals (strings, numbers, sequences) -or functions. Literals are put onto the stack and functions are -executed. - -Every Joy function is an unary mapping from stacks to stacks. Even -literals are considered to be functions that accept a stack and return a -new stack with the literal value on top. - -Exports: - - joy(stack, expression, dictionary, viewer=None) - - run(text, stack, dictionary, viewer=None) - - repl(stack=(), dictionary=()) +This module implements an interpreter for a dialect of Joy that +attempts to stay very close to the spirit of Joy but does not precisely +match the behaviour of the original version(s) written in C. ''' from __future__ import print_function @@ -62,8 +35,13 @@ from .utils.pretty_print import TracePrinter def joy(stack, expression, dictionary, viewer=None): - ''' - Evaluate the Joy expression on the stack. + '''Evaluate the Joy expression on the stack. + + The basic joy() function is quite straightforward. It iterates through a + sequence of terms which are either literals (strings, numbers, sequences) + or functions. Literals are put onto the stack and functions are + executed. + :param quote stack: The stack. :param quote expression: The expression to evaluate. diff --git a/joy/pribrary.py b/joy/pribrary.py new file mode 100644 index 0000000..a38f3c3 --- /dev/null +++ b/joy/pribrary.py @@ -0,0 +1,1437 @@ +# -*- coding: utf-8 -*- +# +# Copyright © 2014, 2015, 2017, 2018 Simon Forman +# +# This file is part of Thun +# +# Thun is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. +# +# Thun is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with Thun. If not see . +# +''' +This module contains the Joy function infrastructure and a library of +functions. Its main export is a Python function initialize() that +returns a dictionary of Joy functions suitable for use with the joy() +function. +''' +from inspect import getdoc +from functools import wraps +import operator, math + +from .parser import text_to_expression, Symbol +from .utils.stack import list_to_stack, iter_stack, pick, pushback +from .utils.brutal_hackery import rename_code_object + + +_dictionary = {} + + +def inscribe(function): + '''A decorator to inscribe functions into the default dictionary.''' + _dictionary[function.name] = function + return function + + +def initialize(): + '''Return a dictionary of Joy functions for use with joy().''' + return _dictionary.copy() + + +ALIASES = ( + ('add', ['+']), + ('and', ['&']), + ('bool', ['truthy']), + ('mul', ['*']), + ('truediv', ['/']), + ('mod', ['%', 'rem', 'remainder', 'modulus']), + ('eq', ['=']), + ('ge', ['>=']), + ('getitem', ['pick', 'at']), + ('gt', ['>']), + ('le', ['<=']), + ('lshift', ['<<']), + ('lt', ['<']), + ('ne', ['<>', '!=']), + ('rshift', ['>>']), + ('sub', ['-']), + ('xor', ['^']), + ('succ', ['++']), + ('pred', ['--']), + ('rolldown', ['roll<']), + ('rollup', ['roll>']), + ('id', ['•']), + ) + + +def add_aliases(D, A): + ''' + Given a dict and a iterable of (name, [alias, ...]) pairs, create + additional entries in the dict mapping each alias to the named function + if it's in the dict. Aliases for functions not in the dict are ignored. + ''' + for name, aliases in A: + try: + F = D[name] + except KeyError: + continue + for alias in aliases: + D[alias] = F + + +definitions = ('''\ +second == rest first +third == rest rest first +of == swap at +product == 1 swap [*] step +swons == swap cons +swoncat == swap concat +flatten == [] swap [concat] step +unit == [] cons +quoted == [unit] dip +unquoted == [i] dip +enstacken == stack [clear] dip +disenstacken == ? [uncons ?] loop pop +? == dup truthy +dinfrirst == dip infra first +nullary == [stack] dinfrirst +unary == [stack [pop] dip] dinfrirst +binary == [stack [popop] dip] dinfrirst +ternary == [stack [popop pop] dip] dinfrirst +pam == [i] map +run == [] swap infra +sqr == dup mul +size == 0 swap [pop ++] step +cleave == [i] app2 [popd] dip +average == [sum 1.0 *] [size] cleave / +gcd == 1 [tuck modulus dup 0 >] loop pop +least_fraction == dup [gcd] infra [div] concat map +*fraction == [uncons] dip uncons [swap] dip concat [*] infra [*] dip cons +*fraction0 == concat [[swap] dip * [*] dip] infra +down_to_zero == [0 >] [dup --] while +range_to_zero == unit [down_to_zero] infra +anamorphism == [pop []] swap [dip swons] genrec +range == [0 <=] [1 - dup] anamorphism +while == swap [nullary] cons dup dipd concat loop +dudipd == dup dipd +primrec == [i] genrec +step_zero == 0 roll> step +''' + +##Zipper +##z-down == [] swap uncons swap +##z-up == swons swap shunt +##z-right == [swons] cons dip uncons swap +##z-left == swons [uncons swap] dip swap + +##Quadratic Formula +##divisor == popop 2 * +##minusb == pop neg +##radical == swap dup * rollup * 4 * - sqrt +##root1 == + swap / +##root2 == - swap / +##q0 == [[divisor] [minusb] [radical]] pam +##q1 == [[root1] [root2]] pam +##quadratic == [q0] ternary i [q1] ternary + +# Project Euler +##'''\ +##PE1.1 == + dup [+] dip +##PE1.2 == dup [3 & PE1.1] dip 2 >> +##PE1.3 == 14811 swap [PE1.2] times pop +##PE1 == 0 0 66 [7 PE1.3] times 4 PE1.3 pop +##''' +#PE1.2 == [PE1.1] step +#PE1 == 0 0 66 [[3 2 1 3 1 2 3] PE1.2] times [3 2 1 3] PE1.2 pop +) + + +def FunctionWrapper(f): + '''Set name attribute.''' + if not f.__doc__: + raise ValueError('Function %s must have doc string.' % f.__name__) + f.name = f.__name__.rstrip('_') # Don't shadow builtins. + return f + + +def SimpleFunctionWrapper(f): + ''' + Wrap functions that take and return just a stack. + ''' + @FunctionWrapper + @wraps(f) + @rename_code_object(f.__name__) + def inner(stack, expression, dictionary): + return f(stack), expression, dictionary + return inner + + +def BinaryBuiltinWrapper(f): + ''' + Wrap functions that take two arguments and return a single result. + ''' + @FunctionWrapper + @wraps(f) + @rename_code_object(f.__name__) + def inner(stack, expression, dictionary): + (a, (b, stack)) = stack + result = f(b, a) + return (result, stack), expression, dictionary + return inner + + +def UnaryBuiltinWrapper(f): + ''' + Wrap functions that take one argument and return a single result. + ''' + @FunctionWrapper + @wraps(f) + @rename_code_object(f.__name__) + def inner(stack, expression, dictionary): + (a, stack) = stack + result = f(a) + return (result, stack), expression, dictionary + return inner + + +class DefinitionWrapper(object): + ''' + Provide implementation of defined functions, and some helper methods. + ''' + + def __init__(self, name, body_text, doc=None): + self.name = self.__name__ = name + self.body = text_to_expression(body_text) + self._body = tuple(iter_stack(self.body)) + self.__doc__ = doc or body_text + + def __call__(self, stack, expression, dictionary): + expression = list_to_stack(self._body, expression) + return stack, expression, dictionary + + @classmethod + def parse_definition(class_, defi): + ''' + Given some text describing a Joy function definition parse it and + return a DefinitionWrapper. + ''' + name, proper, body_text = (n.strip() for n in defi.partition('==')) + if not proper: + raise ValueError('Definition %r failed' % (defi,)) + return class_(name, body_text) + + @classmethod + def add_definitions(class_, defs, dictionary): + ''' + Scan multi-line string defs for definitions and add them to the + dictionary. + ''' + for definition in _text_to_defs(defs): + class_.add_def(definition, dictionary) + + @classmethod + def add_def(class_, definition, dictionary): + ''' + Add the definition to the dictionary. + ''' + F = class_.parse_definition(definition) + dictionary[F.name] = F + + +def _text_to_defs(text): + return (line.strip() for line in text.splitlines() if '==' in line) + + +# +# Functions +# + + +@inscribe +@SimpleFunctionWrapper +def parse(stack): + '''Parse the string on the stack to a Joy expression.''' + text, stack = stack + expression = text_to_expression(text) + return expression, stack + + +@inscribe +@SimpleFunctionWrapper +def first(stack): + ''' + :: + + first == uncons pop + + ''' + ((head, tail), stack) = stack + return head, stack + + +@inscribe +@SimpleFunctionWrapper +def rest(stack): + ''' + :: + + rest == uncons popd + + ''' + ((head, tail), stack) = stack + return tail, stack + + +@inscribe +@SimpleFunctionWrapper +def getitem(stack): + ''' + :: + + getitem == drop first + + Expects an integer and a quote on the stack and returns the item at the + nth position in the quote counting from 0. + :: + + [a b c d] 0 getitem + ------------------------- + a + + ''' + n, (Q, stack) = stack + return pick(Q, n), stack + + +@inscribe +@SimpleFunctionWrapper +def drop(stack): + ''' + :: + + drop == [rest] times + + Expects an integer and a quote on the stack and returns the quote with + n items removed off the top. + :: + + [a b c d] 2 drop + ---------------------- + [c d] + + ''' + n, (Q, stack) = stack + while n > 0: + try: + _, Q = Q + except ValueError: + raise IndexError + n -= 1 + return Q, stack + + +@inscribe +@SimpleFunctionWrapper +def take(stack): + ''' + Expects an integer and a quote on the stack and returns the quote with + just the top n items in reverse order (because that's easier and you can + use reverse if needed.) + :: + + [a b c d] 2 take + ---------------------- + [b a] + + ''' + n, (Q, stack) = stack + x = () + while n > 0: + try: + item, Q = Q + except ValueError: + raise IndexError + x = item, x + n -= 1 + return x, stack + + +@inscribe +@SimpleFunctionWrapper +def choice(stack): + ''' + Use a Boolean value to select one of two items. + :: + + A B False choice + ---------------------- + A + + + A B True choice + --------------------- + B + + Currently Python semantics are used to evaluate the "truthiness" of the + Boolean value (so empty string, zero, etc. are counted as false, etc.) + ''' + (if_, (then, (else_, stack))) = stack + return then if if_ else else_, stack + + +@inscribe +@SimpleFunctionWrapper +def select(stack): + ''' + Use a Boolean value to select one of two items from a sequence. + :: + + [A B] False select + ------------------------ + A + + + [A B] True select + ----------------------- + B + + The sequence can contain more than two items but not fewer. + Currently Python semantics are used to evaluate the "truthiness" of the + Boolean value (so empty string, zero, etc. are counted as false, etc.) + ''' + (flag, (choices, stack)) = stack + (else_, (then, _)) = choices + return then if flag else else_, stack + + +@inscribe +@SimpleFunctionWrapper +def max_(S): + '''Given a list find the maximum.''' + tos, stack = S + return max(iter_stack(tos)), stack + + +@inscribe +@SimpleFunctionWrapper +def min_(S): + '''Given a list find the minimum.''' + tos, stack = S + return min(iter_stack(tos)), stack + + +@inscribe +@SimpleFunctionWrapper +def sum_(S): + '''Given a quoted sequence of numbers return the sum. + + sum == 0 swap [+] step + ''' + tos, stack = S + return sum(iter_stack(tos)), stack + + +@inscribe +@SimpleFunctionWrapper +def remove(S): + ''' + Expects an item on the stack and a quote under it and removes that item + from the the quote. The item is only removed once. + :: + + [1 2 3 1] 1 remove + ------------------------ + [2 3 1] + + ''' + (tos, (second, stack)) = S + l = list(iter_stack(second)) + l.remove(tos) + return list_to_stack(l), stack + + +@inscribe +@SimpleFunctionWrapper +def unique(S): + '''Given a list remove duplicate items.''' + tos, stack = S + I = list(iter_stack(tos)) + list_to_stack(sorted(set(I), key=I.index)) + return list_to_stack(sorted(set(I), key=I.index)), stack + + +@inscribe +@SimpleFunctionWrapper +def sort_(S): + '''Given a list return it sorted.''' + tos, stack = S + return list_to_stack(sorted(iter_stack(tos))), stack + + +@inscribe +@SimpleFunctionWrapper +def cons(S): + ''' + The cons operator expects a list on top of the stack and the potential + member below. The effect is to add the potential member into the + aggregate. + ''' + (tos, (second, stack)) = S + return (second, tos), stack + + +@inscribe +@SimpleFunctionWrapper +def uncons(S): + ''' + Inverse of cons, removes an item from the top of the list on the stack + and places it under the remaining list. + ''' + (tos, stack) = S + item, tos = tos + return tos, (item, stack) + + +@inscribe +@SimpleFunctionWrapper +def clear(stack): + '''Clear everything from the stack. + :: + + ... clear + --------------- + + ''' + return () + + +@inscribe +@SimpleFunctionWrapper +def dup(S): + '''Duplicate the top item on the stack.''' + (tos, stack) = S + return tos, (tos, stack) + + +@inscribe +@SimpleFunctionWrapper +def over(S): + ''' + Copy the second item down on the stack to the top of the stack. + :: + + a b over + -------------- + a b a + + ''' + second = S[1][0] + return second, S + + +@inscribe +@SimpleFunctionWrapper +def tuck(S): + ''' + Copy the item at TOS under the second item of the stack. + :: + + a b tuck + -------------- + b a b + + ''' + (tos, (second, stack)) = S + return tos, (second, (tos, stack)) + + +@inscribe +@SimpleFunctionWrapper +def swap(S): + '''Swap the top two items on stack.''' + (tos, (second, stack)) = S + return second, (tos, stack) + + +@inscribe +@SimpleFunctionWrapper +def swaack(stack): + '''swap stack''' + old_stack, stack = stack + return stack, old_stack + + +@inscribe +@SimpleFunctionWrapper +def stack_(stack): + ''' + The stack operator pushes onto the stack a list containing all the + elements of the stack. + ''' + return stack, stack + + +@inscribe +@SimpleFunctionWrapper +def unstack(stack): + ''' + The unstack operator expects a list on top of the stack and makes that + the stack discarding the rest of the stack. + ''' + return stack[0] + + +@inscribe +@SimpleFunctionWrapper +def pop(stack): + '''Pop and discard the top item from the stack.''' + return stack[1] + + +@inscribe +@SimpleFunctionWrapper +def popd(stack): + '''Pop and discard the second item from the stack.''' + (tos, (_, stack)) = stack + return tos, stack + + +@inscribe +@SimpleFunctionWrapper +def popdd(stack): + '''Pop and discard the third item from the stack.''' + (tos, (second, (_, stack))) = stack + return tos, (second, stack) + + +@inscribe +@SimpleFunctionWrapper +def popop(stack): + '''Pop and discard the first and second items from the stack.''' + return stack[1][1] + + +@inscribe +@SimpleFunctionWrapper +def dupd(S): + '''Duplicate the second item on the stack.''' + (tos, (second, stack)) = S + return tos, (second, (second, stack)) + + +@inscribe +@SimpleFunctionWrapper +def reverse(S): + '''Reverse the list on the top of the stack. + :: + + reverse == [] swap shunt + ''' + (tos, stack) = S + res = () + for term in iter_stack(tos): + res = term, res + return res, stack + + +@inscribe +@SimpleFunctionWrapper +def concat(S): + '''Concatinate the two lists on the top of the stack.''' + (tos, (second, stack)) = S + for term in reversed(list(iter_stack(second))): + tos = term, tos + return tos, stack + + +@inscribe +@SimpleFunctionWrapper +def shunt(xxx_todo_changeme3): + '''Like concat but reverses the top list into the second. + :: + + shunt == [swons] step + + ''' + (tos, (second, stack)) = xxx_todo_changeme3 + while tos: + term, tos = tos + second = term, second + return second, stack + + +@inscribe +@SimpleFunctionWrapper +def zip_(S): + ''' + Replace the two lists on the top of the stack with a list of the pairs + from each list. The smallest list sets the length of the result list. + ''' + (tos, (second, stack)) = S + accumulator = [ + (a, (b, ())) + for a, b in zip(iter_stack(tos), iter_stack(second)) + ] + return list_to_stack(accumulator), stack + + +@inscribe +@SimpleFunctionWrapper +def succ(S): + '''Increment TOS.''' + (tos, stack) = S + return tos + 1, stack + + +@inscribe +@SimpleFunctionWrapper +def pred(S): + '''Decrement TOS.''' + (tos, stack) = S + return tos - 1, stack + + +@inscribe +@SimpleFunctionWrapper +def pm(stack): + ''' + Plus or minus + :: + + a b pm + ------------- + a+b a-b + + ''' + a, (b, stack) = stack + p, m, = b + a, b - a + return m, (p, stack) + + +def floor(n): + return int(math.floor(n)) + +floor.__doc__ = math.floor.__doc__ + + +@inscribe +@SimpleFunctionWrapper +def divmod_(S): + ''' + divmod(x, y) -> (quotient, remainder) + + Return the tuple (x//y, x%y). Invariant: div*y + mod == x. + ''' + a, (b, stack) = S + d, m = divmod(a, b) + return d, (m, stack) + + +def sqrt(a): + ''' + Return the square root of the number a. + Negative numbers return complex roots. + ''' + try: + r = math.sqrt(a) + except ValueError: + assert a < 0, repr(a) + r = math.sqrt(-a) * 1j + return r + + +@inscribe +@SimpleFunctionWrapper +def rollup(S): + ''' + :: + + a b c + ----------- + b c a + + ''' + (a, (b, (c, stack))) = S + return b, (c, (a, stack)) + + +@inscribe +@SimpleFunctionWrapper +def rolldown(S): + ''' + :: + + a b c + ----------- + c a b + + ''' + (a, (b, (c, stack))) = S + return c, (a, (b, stack)) + + +#def execute(S): +# (text, stack) = S +# if isinstance(text, str): +# return run(text, stack) +# return stack + + +@inscribe +@SimpleFunctionWrapper +def id_(stack): + '''The identity function.''' + return stack + + +@inscribe +@SimpleFunctionWrapper +def void(stack): + '''True if the form on TOS is void otherwise False.''' + form, stack = stack + return _void(form), stack + + +def _void(form): + return any(not _void(i) for i in iter_stack(form)) + + + +## transpose +## sign +## take + + +@inscribe +@FunctionWrapper +def words(stack, expression, dictionary): + '''Print all the words in alphabetical order.''' + print((' '.join(sorted(dictionary)))) + return stack, expression, dictionary + + +@inscribe +@FunctionWrapper +def sharing(stack, expression, dictionary): + '''Print redistribution information.''' + print("You may convey verbatim copies of the Program's source code as" + ' you receive it, in any medium, provided that you conspicuously' + ' and appropriately publish on each copy an appropriate copyright' + ' notice; keep intact all notices stating that this License and' + ' any non-permissive terms added in accord with section 7 apply' + ' to the code; keep intact all notices of the absence of any' + ' warranty; and give all recipients a copy of this License along' + ' with the Program.' + ' You should have received a copy of the GNU General Public License' + ' along with Thun. If not see .') + return stack, expression, dictionary + + +@inscribe +@FunctionWrapper +def warranty(stack, expression, dictionary): + '''Print warranty information.''' + print('THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY' + ' APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE' + ' COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM' + ' "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR' + ' IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES' + ' OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE' + ' ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS' + ' WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE' + ' COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION.') + return stack, expression, dictionary + + +# def simple_manual(stack): +# ''' +# Print words and help for each word. +# ''' +# for name, f in sorted(FUNCTIONS.items()): +# d = getdoc(f) +# boxline = '+%s+' % ('-' * (len(name) + 2)) +# print('\n'.join(( +# boxline, +# '| %s |' % (name,), +# boxline, +# d if d else ' ...', +# '', +# '--' * 40, +# '', +# ))) +# return stack + + +@inscribe +@FunctionWrapper +def help_(S, expression, dictionary): + '''Accepts a quoted symbol on the top of the stack and prints its docs.''' + ((symbol, _), stack) = S + word = dictionary[symbol] + print((getdoc(word))) + return stack, expression, dictionary + + +# +# § Combinators +# + + +# Several combinators depend on other words in their definitions, +# we use symbols to prevent hard-coding these, so in theory, you +# could change the word in the dictionary to use different semantics. +S_choice = Symbol('choice') +S_first = Symbol('first') +S_getitem = Symbol('getitem') +S_genrec = Symbol('genrec') +S_loop = Symbol('loop') +S_i = Symbol('i') +S_ifte = Symbol('ifte') +S_infra = Symbol('infra') +S_step = Symbol('step') +S_times = Symbol('times') +S_swaack = Symbol('swaack') +S_truthy = Symbol('truthy') + + +@inscribe +@FunctionWrapper +def i(stack, expression, dictionary): + ''' + The i combinator expects a quoted program on the stack and unpacks it + onto the pending expression for evaluation. + :: + + [Q] i + ----------- + Q + + ''' + quote, stack = stack + return stack, pushback(quote, expression), dictionary + + +@inscribe +@FunctionWrapper +def x(stack, expression, dictionary): + ''' + :: + + x == dup i + + ... [Q] x = ... [Q] dup i + ... [Q] x = ... [Q] [Q] i + ... [Q] x = ... [Q] Q + + ''' + quote, _ = stack + return stack, pushback(quote, expression), dictionary + + +@inscribe +@FunctionWrapper +def b(stack, expression, dictionary): + ''' + :: + + b == [i] dip i + + ... [P] [Q] b == ... [P] i [Q] i + ... [P] [Q] b == ... P Q + + ''' + q, (p, (stack)) = stack + return stack, pushback(p, pushback(q, expression)), dictionary + + +@inscribe +@FunctionWrapper +def dupdip(stack, expression, dictionary): + ''' + :: + + [F] dupdip == dup [F] dip + + ... a [F] dupdip + ... a dup [F] dip + ... a a [F] dip + ... a F a + + ''' + F, stack = stack + a = stack[0] + return stack, pushback(F, (a, expression)), dictionary + + +@inscribe +@FunctionWrapper +def infra(stack, expression, dictionary): + ''' + Accept a quoted program and a list on the stack and run the program + with the list as its stack. + :: + + ... [a b c] [Q] . infra + ----------------------------- + c b a . Q [...] swaack + + ''' + (quote, (aggregate, stack)) = stack + return aggregate, pushback(quote, (stack, (S_swaack, expression))), dictionary + + +@inscribe +@FunctionWrapper +def genrec(stack, expression, dictionary): + ''' + General Recursion Combinator. + :: + + [if] [then] [rec1] [rec2] genrec + --------------------------------------------------------------------- + [if] [then] [rec1 [[if] [then] [rec1] [rec2] genrec] rec2] ifte + + From "Recursion Theory and Joy" (j05cmp.html) by Manfred von Thun: + "The genrec combinator takes four program parameters in addition to + whatever data parameters it needs. Fourth from the top is an if-part, + followed by a then-part. If the if-part yields true, then the then-part + is executed and the combinator terminates. The other two parameters are + the rec1-part and the rec2-part. If the if-part yields false, the + rec1-part is executed. Following that the four program parameters and + the combinator are again pushed onto the stack bundled up in a quoted + form. Then the rec2-part is executed, where it will find the bundled + form. Typically it will then execute the bundled form, either with i or + with app2, or some other combinator." + + The way to design one of these is to fix your base case [then] and the + test [if], and then treat rec1 and rec2 as an else-part "sandwiching" + a quotation of the whole function. + + For example, given a (general recursive) function 'F': + :: + + F == [I] [T] [R1] [R2] genrec + + If the [I] if-part fails you must derive R1 and R2 from: + :: + + ... R1 [F] R2 + + Just set the stack arguments in front, and figure out what R1 and R2 + have to do to apply the quoted [F] in the proper way. In effect, the + genrec combinator turns into an ifte combinator with a quoted copy of + the original definition in the else-part: + :: + + F == [I] [T] [R1] [R2] genrec + == [I] [T] [R1 [F] R2] ifte + + Primitive recursive functions are those where R2 == i. + :: + + P == [I] [T] [R] primrec + == [I] [T] [R [P] i] ifte + == [I] [T] [R P] ifte + + ''' + (rec2, (rec1, stack)) = stack + (then, (if_, _)) = stack + F = (if_, (then, (rec1, (rec2, (S_genrec, ()))))) + else_ = pushback(rec1, (F, rec2)) + return (else_, stack), (S_ifte, expression), dictionary + + +@inscribe +@FunctionWrapper +def map_(S, expression, dictionary): + ''' + Run the quoted program on TOS on the items in the list under it, push a + new list with the results (in place of the program and original list. + ''' +# (quote, (aggregate, stack)) = S +# results = list_to_stack([ +# joy((term, stack), quote, dictionary)[0][0] +# for term in iter_stack(aggregate) +# ]) +# return (results, stack), expression, dictionary + (quote, (aggregate, stack)) = S + if not aggregate: + return (aggregate, stack), expression, dictionary + batch = () + for term in iter_stack(aggregate): + s = term, stack + batch = (s, (quote, (S_infra, (S_first, batch)))) + stack = (batch, ((), stack)) + return stack, (S_infra, expression), dictionary + + +#def cleave(S, expression, dictionary): +# ''' +# The cleave combinator expects two quotations, and below that an item X. +# It first executes [P], with X on top, and saves the top result element. +# Then it executes [Q], again with X, and saves the top result. +# Finally it restores the stack to what it was below X and pushes the two +# results P(X) and Q(X). +# ''' +# (Q, (P, (x, stack))) = S +# p = joy((x, stack), P, dictionary)[0][0] +# q = joy((x, stack), Q, dictionary)[0][0] +# return (q, (p, stack)), expression, dictionary + + +@inscribe +@FunctionWrapper +def branch(stack, expression, dictionary): + ''' + Use a Boolean value to select one of two quoted programs to run. + + :: + + branch == roll< choice i + + :: + + False [F] [T] branch + -------------------------- + F + + True [F] [T] branch + ------------------------- + T + + ''' + (then, (else_, (flag, stack))) = stack + return stack, pushback(then if flag else else_, expression), dictionary + + +@inscribe +@FunctionWrapper +def ifte(stack, expression, dictionary): + ''' + If-Then-Else Combinator + :: + + ... [if] [then] [else] ifte + --------------------------------------------------- + ... [[else] [then]] [...] [if] infra select i + + + + + ... [if] [then] [else] ifte + ------------------------------------------------------- + ... [else] [then] [...] [if] infra first choice i + + + Has the effect of grabbing a copy of the stack on which to run the + if-part using infra. + ''' + (else_, (then, (if_, stack))) = stack + expression = (S_infra, (S_first, (S_choice, (S_i, expression)))) + stack = (if_, (stack, (then, (else_, stack)))) + return stack, expression, dictionary + + +@inscribe +@FunctionWrapper +def dip(stack, expression, dictionary): + ''' + The dip combinator expects a quoted program on the stack and below it + some item, it hoists the item into the expression and runs the program + on the rest of the stack. + :: + + ... x [Q] dip + ------------------- + ... Q x + + ''' + (quote, (x, stack)) = stack + expression = (x, expression) + return stack, pushback(quote, expression), dictionary + + +@inscribe +@FunctionWrapper +def dipd(S, expression, dictionary): + ''' + Like dip but expects two items. + :: + + ... y x [Q] dip + --------------------- + ... Q y x + + ''' + (quote, (x, (y, stack))) = S + expression = (y, (x, expression)) + return stack, pushback(quote, expression), dictionary + + +@inscribe +@FunctionWrapper +def dipdd(S, expression, dictionary): + ''' + Like dip but expects three items. + :: + + ... z y x [Q] dip + ----------------------- + ... Q z y x + + ''' + (quote, (x, (y, (z, stack)))) = S + expression = (z, (y, (x, expression))) + return stack, pushback(quote, expression), dictionary + + +@inscribe +@FunctionWrapper +def app1(S, expression, dictionary): + ''' + Given a quoted program on TOS and anything as the second stack item run + the program and replace the two args with the first result of the + program. + :: + + ... x [Q] . app1 + ----------------------------------- + ... [x ...] [Q] . infra first + ''' + (quote, (x, stack)) = S + stack = (quote, ((x, stack), stack)) + expression = (S_infra, (S_first, expression)) + return stack, expression, dictionary + + +@inscribe +@FunctionWrapper +def app2(S, expression, dictionary): + '''Like app1 with two items. + :: + + ... y x [Q] . app2 + ----------------------------------- + ... [y ...] [Q] . infra first + [x ...] [Q] infra first + + ''' + (quote, (x, (y, stack))) = S + expression = (S_infra, (S_first, + ((x, stack), (quote, (S_infra, (S_first, + expression)))))) + stack = (quote, ((y, stack), stack)) + return stack, expression, dictionary + + +@inscribe +@FunctionWrapper +def app3(S, expression, dictionary): + '''Like app1 with three items. + :: + + ... z y x [Q] . app3 + ----------------------------------- + ... [z ...] [Q] . infra first + [y ...] [Q] infra first + [x ...] [Q] infra first + + ''' + (quote, (x, (y, (z, stack)))) = S + expression = (S_infra, (S_first, + ((y, stack), (quote, (S_infra, (S_first, + ((x, stack), (quote, (S_infra, (S_first, + expression)))))))))) + stack = (quote, ((z, stack), stack)) + return stack, expression, dictionary + + +@inscribe +@FunctionWrapper +def step(S, expression, dictionary): + ''' + Run a quoted program on each item in a sequence. + :: + + ... [] [Q] . step + ----------------------- + ... . + + + ... [a] [Q] . step + ------------------------ + ... a . Q + + + ... [a b c] [Q] . step + ---------------------------------------- + ... a . Q [b c] [Q] step + + The step combinator executes the quotation on each member of the list + on top of the stack. + ''' + (quote, (aggregate, stack)) = S + if not aggregate: + return stack, expression, dictionary + head, tail = aggregate + stack = quote, (head, stack) + if tail: + expression = tail, (quote, (S_step, expression)) + expression = S_i, expression + return stack, expression, dictionary + + +@inscribe +@FunctionWrapper +def times(stack, expression, dictionary): + ''' + times == [-- dip] cons [swap] infra [0 >] swap while pop + :: + + ... n [Q] . times + --------------------- w/ n <= 0 + ... . + + + ... 1 [Q] . times + --------------------------------- + ... . Q + + + ... n [Q] . times + --------------------------------- w/ n > 1 + ... . Q (n - 1) [Q] times + + ''' + # times == [-- dip] cons [swap] infra [0 >] swap while pop + (quote, (n, stack)) = stack + if n <= 0: + return stack, expression, dictionary + n -= 1 + if n: + expression = n, (quote, (S_times, expression)) + expression = pushback(quote, expression) + return stack, expression, dictionary + + +# The current definition above works like this: + +# [P] [Q] while +# -------------------------------------- +# [P] nullary [Q [P] nullary] loop + +# while == [pop i not] [popop] [dudipd] primrec + +#def while_(S, expression, dictionary): +# '''[if] [body] while''' +# (body, (if_, stack)) = S +# while joy(stack, if_, dictionary)[0][0]: +# stack = joy(stack, body, dictionary)[0] +# return stack, expression, dictionary + + +@inscribe +@FunctionWrapper +def loop(stack, expression, dictionary): + ''' + Basic loop combinator. + :: + + ... True [Q] loop + ----------------------- + ... Q [Q] loop + + ... False [Q] loop + ------------------------ + ... + + ''' + quote, (flag, stack) = stack + if flag: + expression = pushback(quote, (quote, (S_loop, expression))) + return stack, expression, dictionary + + +#def nullary(S, expression, dictionary): +# ''' +# Run the program on TOS and return its first result without consuming +# any of the stack (except the program on TOS.) +# ''' +# (quote, stack) = S +# result = joy(stack, quote, dictionary) +# return (result[0][0], stack), expression, dictionary +# +# +#def unary(S, expression, dictionary): +# (quote, stack) = S +# _, return_stack = stack +# result = joy(stack, quote, dictionary)[0] +# return (result[0], return_stack), expression, dictionary +# +# +#def binary(S, expression, dictionary): +# (quote, stack) = S +# _, (_, return_stack) = stack +# result = joy(stack, quote, dictionary)[0] +# return (result[0], return_stack), expression, dictionary +# +# +#def ternary(S, expression, dictionary): +# (quote, stack) = S +# _, (_, (_, return_stack)) = stack +# result = joy(stack, quote, dictionary)[0] +# return (result[0], return_stack), expression, dictionary + + +# FunctionWrapper(binary), +# FunctionWrapper(cleave), +# FunctionWrapper(nullary), +# FunctionWrapper(ternary), +# FunctionWrapper(unary), +# FunctionWrapper(while_), + + +for F in ( + BinaryBuiltinWrapper(operator.add), + BinaryBuiltinWrapper(operator.and_), + BinaryBuiltinWrapper(operator.div), + BinaryBuiltinWrapper(operator.eq), + BinaryBuiltinWrapper(operator.floordiv), + BinaryBuiltinWrapper(operator.ge), + BinaryBuiltinWrapper(operator.gt), + BinaryBuiltinWrapper(operator.le), + BinaryBuiltinWrapper(operator.lshift), + BinaryBuiltinWrapper(operator.lt), + BinaryBuiltinWrapper(operator.mod), + BinaryBuiltinWrapper(operator.mul), + BinaryBuiltinWrapper(operator.ne), + BinaryBuiltinWrapper(operator.or_), + BinaryBuiltinWrapper(operator.pow), + BinaryBuiltinWrapper(operator.rshift), + BinaryBuiltinWrapper(operator.sub), + BinaryBuiltinWrapper(operator.truediv), + BinaryBuiltinWrapper(operator.xor), + + UnaryBuiltinWrapper(abs), + UnaryBuiltinWrapper(bool), + UnaryBuiltinWrapper(floor), + UnaryBuiltinWrapper(operator.neg), + UnaryBuiltinWrapper(operator.not_), + UnaryBuiltinWrapper(sqrt), + ): + inscribe(F) +del F # Otherwise Sphinx autodoc will pick it up. + + +add_aliases(_dictionary, ALIASES) + + +DefinitionWrapper.add_definitions(definitions, _dictionary) diff --git a/joy/utils/stack.py b/joy/utils/stack.py index c5ff7a9..478521d 100644 --- a/joy/utils/stack.py +++ b/joy/utils/stack.py @@ -23,8 +23,8 @@ When talking about Joy we use the terms "stack", "list", "sequence", permits certain operations such as iterating and pushing and popping values from (at least) one end. -We use the venerable two-tuple recursive form of sequences where the -empty tuple () is the empty stack and (head, rest) gives the recursive +We use the `cons list`_, a venerable two-tuple recursive sequence datastructure, where the +empty tuple ``()`` is the empty stack and ``(head, rest)`` gives the recursive form of a stack with one or more items on it:: stack := () | (item, stack) @@ -50,6 +50,9 @@ in this case "(head, tail)", and Python takes care of unpacking the incoming tuple and assigning values to the names. (Note that Python syntax doesn't require parentheses around tuples used in expressions where they would be redundant.) + +.. _cons list: https://en.wikipedia.org/wiki/Cons#Lists + ''' ##We have two very simple functions to build up a stack from a Python @@ -135,8 +138,8 @@ def pushback(quote, expression): ## return list_to_stack(list(iter_stack(quote)), expression) - # This is slightly faster and won't break the - # recursion limit on long quotes. + # In-lining is slightly faster (and won't break the + # recursion limit on long quotes.) ## temp = [] ## while quote: